<?php

namespace Simplyin\Simplyin_W_Plugin\Hooks;

use Simplyin\Simplyin_W_Plugin\Service\Order\Order_Data_Handler;
use WC_Order;

class simplyInOnOrderCreate {


	public function run( WC_Order $order ) {

		global $woocommerce;
		$plugin_version      = SimplyInGetPluginVersion();
		$woocommerce_version = get_option( 'woocommerce_version' );

		$payment_method_data = SimplyInGetPaymentMethodData( $order );

		$simplyin_phone_number      = SimplyInGetSanitizedPostData( 'simplyin-phone' ) ?: SimplyInGetSanitizedPostData( 'phoneAppInputField' );
		$simplyin_phone_prefix      = SimplyInGetSanitizedPostData( 'simplyin-phone-prefix' ) ?: SimplyInGetSanitizedPostData( 'phoneAppInputPrefix' );
		$simplyin_Token_Input_Value = simplyin()
			->get_simplyin_session()
			->get( 'simplyin_auth_token', '' );
		$create_new_accountVal      = SimplyInGetSanitizedPostData( 'simply-save-checkbox' );
		$parcel_machine_id          = SimplyInGetSanitizedPostDataParcelMachineId();
		$parcel_provider_name       = '';
		$custom_tax_field_id        = SimplyInGetSanitizedPostData( 'simply_tax_label_id' );
		$simply_billing_id          = SimplyInGetSanitizedPostData( 'simply_billing_id' );
		$simply_shipping_id         = SimplyInGetSanitizedPostData( 'simply_shipping_id' );

		$simplyin_session = simplyin()->get_simplyin_session();
		if ( empty( $simply_billing_id ) ) {
			$simply_billing_id = (string) $simplyin_session->get( 'simplyin_billing', '' );
		}
		if ( empty( $simply_shipping_id ) ) {
			$simply_shipping_id = (string) $simplyin_session->get( 'simplyin_shipping', '' );
		}
		if ( empty( $parcel_machine_id ) ) {
			// Prefer exact lockerId if stored, otherwise fallback to legacy selected _id
			$parcel_machine_id = (string) $simplyin_session->get( 'simplyin_parcel_locker_id', '' );
			if ( empty( $parcel_machine_id ) ) {
				$parcel_machine_id = (string) $simplyin_session->get( 'simplyin_parcel', '' );
			}
		}
		$parcel_provider_name = (string) $simplyin_session->get( 'simplyin_parcel_provider', '' );
		$tax_id                     = SimplyInGetSanitizedPostData( $custom_tax_field_id );

		$locale        = get_locale();
		$language_code = strtoupper( substr( $locale, 0, 2 ) );

		$full_phone_number = $simplyin_phone_prefix . ' ' . $simplyin_phone_number;

		$handler_params = [
			'payment_method_data'   => $payment_method_data,
			'plugin_version'        => $plugin_version,
			'woocommerce_version'   => $woocommerce_version,
			'tax_id'                => $tax_id,
			'language_code'         => $language_code,
			'parcel_machine_id'     => $parcel_machine_id,
			'parcel_provider_name'  => $parcel_provider_name,
			'phone_app_input_field' => $full_phone_number,
			'simply_billing_id'     => $simply_billing_id,
			'simply_shipping_id'    => $simply_shipping_id,
		];

		$handler = new Order_Data_Handler();

		simplyin()
			->get_simplyin_logger()
			->log_if_wpdebug_on( sprintf( "[simplyInOnOrderCreate] [run] [request fields: %s]",
				wp_json_encode( [
					'prefix'                     => $simplyin_phone_prefix,
					'phoneAppInputField'         => $full_phone_number,
					'simplyin_Token_Input_Value' => $simplyin_Token_Input_Value,
					'create_new_accountVal'      => $create_new_accountVal,
					'parcel_machine_id'          => $parcel_machine_id,
					'custom_tax_field_id'        => $custom_tax_field_id,
					'simply_billing_id'          => $simply_billing_id,
					'simply_shipping_id'         => $simply_shipping_id,
					'tax_id'                     => $tax_id,
					'locale'                     => $locale,
					'language_code'              => $language_code,
				] )

			),
				"api-call" );

		$api           = simplyin()->get_api();
		$merchantToken = get_option( 'simplyin_api_key' );


		if ( SimplyInShouldCreateNewAccount( $create_new_accountVal,
			$simplyin_Token_Input_Value ) ) {

			$body_data = $handler->build_create_order_and_account_payload( $order, $handler_params );


			$response = $api->sendRequest(
				'checkout/createOrderAndAccount',
				'POST',
				$body_data
			);

			if ( $response && isset( $response->authToken ) && ! empty( $response->authToken ) ) {
				$order->update_meta_data( '_simplyin_registration_auth_token', $response->authToken );
				$order->save_meta_data();
				simplyin()
					->get_simplyin_logger()
					->log_if_wpdebug_on( sprintf( "[simplyInOnOrderCreate] [createOrderAndAccount] [authToken saved to order meta] [order_id: %s]",
						$order->get_id() ),
						"api-call" );
			}

			$created_order = null;
			if ( isset( $response->createdOrder ) ) {
				$created_order = $response->createdOrder;
			} elseif ( isset( $response->data ) && isset( $response->data->shopOrderNumber ) ) {
				$created_order = $response->data;
			}

			if ( $created_order && isset( $created_order->shopOrderNumber ) && $created_order->shopOrderNumber == $order->get_order_number() ) {
				$order->update_meta_data( 'SimplyInOrderId',
					$created_order->_id );
				$order->update_meta_data( 'SimplyInOrderExported', 1 );
				$order->save_meta_data();
			}
		} elseif ( SimplyInHasAuthToken( $simplyin_Token_Input_Value ) ) {
			$body_data = $handler->build_create_order_without_account_payload( $order, $handler_params );


			$response = $api->sendRequest(
				'checkout/createOrderWithoutAccount',
				'POST',
				$body_data,
				[ 'api_token' => urlencode( $simplyin_Token_Input_Value ) ]
			);

			if ( $response && isset( $response->createdOrder ) && isset( $response->createdOrder->shopOrderNumber ) && $response->createdOrder->shopOrderNumber == $order->get_order_number() ) {
				$order->update_meta_data( 'SimplyInOrderId',
					$response->createdOrder->_id );
				$order->update_meta_data( 'SimplyInOrderExported', 1 );
				$order->save_meta_data();
			}

			//			$order_email   = $order->get_billing_email();
			//			$shopOrderNumber = $order->get_order_number();
			//			$merchantToken = get_option( 'simplyin_api_key' );
			//			$newOrderStatus = 'InTransit';
			//
			//			$new_body_data = [
			//				'email'           => $order_email,
			//				'shopOrderNumber' => $shopOrderNumber,
			//				"newOrderStatus" => $newOrderStatus,
			//				"apiKey" => $merchantToken,
			//				'trackings'       => [
			//					[
			//						'number'   => '55555',
			//					],
			//				],
			//			];
			//
			//			$plaintext = json_encode($new_body_data,JSON_UNESCAPED_SLASHES);
			//
			//			$key           = simplyinGetSecretKey($order_email);
			//			$encryptedData = simplyinEncrypt($plaintext, $key);
			//			$hashedEmail   = simplyinHashEmail($order_email);
			//			$orderData = [];
			//			$orderData['encryptedOrderStatusChangeContent'] = $encryptedData;
			//			$orderData['hashedEmail'] = $hashedEmail;
			//
			//			$secondResponse = json_encode(
			//				sendPostRequest(
			//					$orderData,
			//					'encryption/saveEncryptedOrderStatusChange',
			//					$merchantToken
			//				)
			//			);
			//			if ($secondResponse && isset($secondResponse->success) && $secondResponse->success == true) {
			//				$order->update_meta_data('SecondRequestDone', 1);
			//				$order->save_meta_data();
			//			} else {
			//				error_log('Encrypted tracking update failed: ' . print_r($secondResponse, true));
			//			}
		}
	}
}
