<?php
/**
 * Plugin Name: Simply.IN
 * Version: 6.0.2
 * Plugin URI: https://wordpress.org/plugins/simplyin/
 * Description: A powerful checkout add-on that doesn’t replace your existing checkout but enhances it — boosting conversion with a lightning-fast, secure, 1-click experience that keeps shoppers in your store.
 * Tested up to: 7.0
 * Requires PHP: 7.4
 * Author: Simply.IN
 * Author URI: https://simply.in
 * Requires Plugins: woocommerce
 * Text Domain: simplyin
 * License: GPLv3
 * License URI: https://www.gnu.org/licenses/gpl-3.0.html
 *
 * Copyright 2025 Simply.IN
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

use Simplyin\Simplyin_W_Plugin\Admin\Block_Checkout_Notice;
use Simplyin\Simplyin_W_Plugin\Assets;
use Simplyin\Simplyin_W_Plugin\Hooks\Hooks;
use Simplyin\Simplyin_W_Plugin\Payments\Gateway\Gateway_Helper;
use Simplyin\Simplyin_W_Plugin\Plugin;
use Simplyin\Simplyin_W_Plugin\Service\Order\Tax_Id_Resolver;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Requirement config shared by bootstrap and activation validation.
 *
 * @return array<string, mixed>
 */
function simplyin_get_plugin_requirements_config(): array {
	return [
		'__FILE__'                => __FILE__,
		'name'                    => 'Simply.In',
		'slug'                    => 'simplyin',
		'lang_dir'                => 'lang',
		'text_domain'             => 'simplyin',
		'min_php_int'             => 70400,
		'min_php'                 => 7.4,
		'required_plugins'        => [ 'woocommerce' ],
		'wc_min_version'          => '7.4',
		'required_php_extensions' => [ 'curl' ],
	];
}

/**
 * @return bool
 */
function simplyin_passes_requirements_check(): bool {
	require_once __DIR__ . '/system_check.php';

	return ( new SimplyIN_System_Check( simplyin_get_plugin_requirements_config() ) )->evaluate_system();
}

/**
 * Load Composer, register plugin lifecycle, env, hooks (after requirements passed).
 *
 * @return void
 */
function simplyin_load_plugin_after_requirements_met(): void {
	$config = simplyin_get_plugin_requirements_config();

	require_once __DIR__ . '/vendor/autoload.php';

	simplyin()->execute( $config );

	define( 'SIMPLYIN_CONTENT_TYPE_JSON', 'Content-Type: application/json' );

	require_once __DIR__ . '/Simplyin_Env.php';

	$env = Simplyin_Env::read();

	if ( ! isset( $env['APP_ENV'] ) ) {
		$env['APP_ENV'] = 'prod';
	}

	switch ( $env['APP_ENV'] ) {
		case 'preprod':
			$backendEnvironment          = $env['BACKEND_ENVIRONMENT_PREPROD'];
			$environmentVersion          = $env['APP_VERSION_PREFIX_PREPROD'];
			simplyin()::$logger_enabled = true;
			break;

		case 'stage':
			$backendEnvironment          = $env['BACKEND_ENVIRONMENT_STAGE'];
			$environmentVersion          = $env['APP_VERSION_PREFIX_STAGE'];
			simplyin()::$logger_enabled = true;
			break;

		case 'dev':
			$backendEnvironment          = $env['BACKEND_ENVIRONMENT_DEV'];
			$environmentVersion          = $env['APP_VERSION_PREFIX_DEV'];
			simplyin()::$logger_enabled = true;
			break;

		default:
			$backendEnvironment          = $env['BACKEND_ENVIRONMENT_PROD'];
			$environmentVersion          = $env['APP_VERSION_PREFIX_PROD'];
			simplyin()::$logger_enabled = false;
	}

	global $simplyin_config;
	$simplyin_config = [
		'backendSimplyIn'      => $backendEnvironment,
		'environmentVersion'   => $environmentVersion,
	];

	simplyin()->set_simplyin_config( $simplyin_config );

	if ( (string) get_option( 'SimplyInApiConnection' ) === '1' ) {
		$hooks = new Hooks();
		$hooks->init();
	}
}

function simplyin(): Plugin {
	static $instance = null;
	if ( null === $instance ) {
		$instance = new Plugin();
	}
	return $instance;
}

/**
 * Validates requirements on Activate; disables plugin instead of unsafe half-active state.
 *
 * @return void
 */
function simplyin_handle_plugin_activation(): void {
	if ( simplyin_passes_requirements_check() ) {
		simplyinActivate();

		return;
	}

	if ( ! function_exists( 'deactivate_plugins' ) ) {
		require_once ABSPATH . 'wp-admin/includes/plugin.php';
	}

	deactivate_plugins( plugin_basename( __FILE__ ), true, false );

	$config  = simplyin_get_plugin_requirements_config();
	$wc_need = isset( $config['wc_min_version'] ) ? (string) $config['wc_min_version'] : '';

	$woo_line = $wc_need !== ''
		? sprintf(
			'WooCommerce must be installed, active, and version %s or newer.',
			esc_html( $wc_need )
		)
		: 'WooCommerce must be installed and active.';

	wp_die(
		wp_kses_post(
			sprintf(
				'<p><strong>%1$s</strong></p><p>%2$s</p><p><a href="%3$s">&larr; %4$s</a></p>',
				esc_html(
					'Simply.IN cannot be activated because system requirements were not met (PHP version, extensions, or WooCommerce version).'
				),
				$woo_line,
				esc_url( admin_url( 'plugins.php' ) ),
				esc_html( 'Return to Plugins' )
			)
		),
		esc_html( 'Simply.IN — activation blocked' ),
		[ 'response' => 500 ]
	);
}

register_activation_hook( __FILE__, 'simplyin_handle_plugin_activation' );

function simplyin_bootstrap(): bool {
	if ( ! simplyin_passes_requirements_check() ) {
		return false;
	}

	simplyin_load_plugin_after_requirements_met();

	return true;
}

if ( ! simplyin_bootstrap() ) {
	return;
}

function SimplyInGetPluginVersion() {
	if ( function_exists( 'get_plugin_data' ) ) {
		$plugin_data = get_plugin_data( __FILE__, false, false );

		return $plugin_data['Version'];
	}

	return '6.0.2';
}

/**
 * Runs plugin setup after activation (requirements already verified).
 *
 * @see simplyin_handle_plugin_activation()
 *
 * @return void
 */
function simplyinActivate() {

	update_option( 'SimplyIn_Backend_Url',
		simplyin()->get_backend_simplyin_url() );
	update_option( 'SimplyIn_Environment',
		simplyin()->get_environment_version_prefix() );
	simplyin()->update_option( 'SimplyInSettingsErrorMsg',
		0 );
	Gateway_Helper::enable_gateway();
}

simplyin()->get_app()->run();

( new Block_Checkout_Notice() )->register();

function simplyinEncrypt( $plaintext, $secret_key, $cipher = "aes-256-cbc" ) {
	$ivlen = openssl_cipher_iv_length( $cipher );
	$iv    = openssl_random_pseudo_bytes( $ivlen );

	$ciphertext_raw = openssl_encrypt( $plaintext,
		$cipher,
		$secret_key,
		OPENSSL_RAW_DATA,
		$iv );
	if ( $ciphertext_raw === false ) {
		return false;
	}

	return base64_encode( $iv . $ciphertext_raw );
}

function simplyinHashEmail( $order_email ) {
	return hash( 'sha256',
		"--" . $order_email . "--" ); // Get raw binary output
}

function simplyinGetSecretKey( $order_email ) {
	return hash( 'sha256',
		"__" . $order_email . "__",
		true ); // Get raw binary output
}


if ( (string) get_option( 'SimplyInApiConnection' ) === '1' ) {

	// Path A (priority 1, synchronous): sends encrypted status change to
	// encryption/saveEncryptedOrderStatusChange for ALL orders. Filtered by $stopStatuses.
	// Path B (Simplyin_Sync::change_status, priority 10, async): queues update_order_status
	// to background for orders with SimplyInOrderId only — different API endpoint.
	// Both registrations are intentional: they call different API endpoints.
	add_action( 'woocommerce_order_status_changed',
		function ( $order_id, $old_status, $new_status, $order ) {

			simplyin()
				->get_api()
				->simplyInOnOrderUpdate(
					$old_status,
					$new_status,
					$order );

		},
		1,
		4 );

	if ( ! function_exists( 'simplyInCustomOverrideCheckoutFields' ) ) {
		function simplyInCustomOverrideCheckoutFields( $fields ) {
			$fields['billing']['billing_email'] = [
				'label'       => __( 'Email', 'simplyin' ),
				'placeholder' => _x( 'Enter your email',
					'placeholder',
					'simplyin' ),
				'required'    => true,
				'clear'       => false,
				'type'        => 'text',
				'id'          => 'billing_email',
				'class'       => [ 'my-css' ],
				'priority'    => 1,
			];

			return $fields;
		}
	}

	/**
	 * Get Assets instance.
	 *
	 * @return Assets
	 */
	if ( ! function_exists( 'simplyin_assets' ) ) {
		function simplyin_assets(): Assets {
			static $assets = null;

			if ( null === $assets ) {
				$assets = new Assets( __FILE__ );
			}

			return $assets;
		}
	}

	/**
	 * Enqueue widget assets on checkout (classic + blocks).
	 *
	 * @return void
	 */
	if ( ! function_exists( 'simplyin_load_react_app_for_checkout' ) ) {
		function simplyin_load_react_app_for_checkout(): void {
			$is_classic_checkout = function_exists( 'is_checkout' ) && true === is_checkout();

			$post_id = get_queried_object_id();
			$content = ( 0 < $post_id ) ? (string) get_post_field( 'post_content', $post_id ) : '';

			$is_block_checkout = false;
			if ( '' !== $content && function_exists( 'has_block' ) ) {
				$is_block_checkout = has_block( 'woocommerce/checkout', $content );
			}

			$is_shortcode_checkout = false;
			if ( '' !== $content && function_exists( 'has_shortcode' ) ) {
				$is_shortcode_checkout = has_shortcode( $content, 'woocommerce_checkout' );
			}

			if ( true !== $is_classic_checkout && true !== $is_block_checkout && true !== $is_shortcode_checkout ) {
				return;
			}

			if ( function_exists( 'is_order_received_page' ) && true === is_order_received_page() ) {
				return;
			}

			simplyin_load_react_app( simplyin_assets() );
		}
	}

	/**
	 * Load React app assets and inline config.
	 *
	 * @param Assets $assets Assets helper.
	 *
	 * @return void
	 */
	if ( ! function_exists( 'simplyin_load_react_app' ) ) {
		function simplyin_load_react_app( Assets $assets ): void {
			$assets->enqueue_script(
				'simplyin-widget-js',
				'public/widget/front.js',
				array( 'jquery', 'wp-element' ),
				true
			);

			$assets->enqueue_inline_style_from_file(
				'simplyin-widget-css',
				'public/widget/front.css'
			);

			simplyin_add_js_default_header( $assets );
		}
	}

	if ( ! function_exists( 'simplyin_add_js_default_header' ) ) {
		function simplyin_add_js_default_header( Assets $assets, $override = [] ) {
			$current_user      = wp_get_current_user();
			$current_language  = get_locale();
			$customer_email    = $current_user->user_email ?? null;
			$hide_phone_field  = false;
			$new_account_phone = false;

			if ( $current_user && $customer_email ) {
				$hide_phone_field  = (bool) email_exists( $customer_email );
				$new_account_phone = get_user_meta( $current_user->ID,
					'billing_phone',
					true );
			}

			$return = [
				'ajax_token'        => wp_create_nonce( 'simplyin_ajax' ),
				'labels'            => [
					'banner_text'                 => __( 'Here you can shop with',
						'simplyin' ),
					'data_saved'                  => __( 'Data completed', 'simplyin' ),
					'data_confirm'                => __( 'Confirm profile', 'simplyin' ),
					'change'                      => __( 'Change', 'simplyin' ),
					'cancel'                      => __( 'Cancel', 'simplyin' ),
					'edit'                        => __( 'Edit', 'simplyin' ),
					'distance'                    => __( 'Distance', 'simplyin' ),
					'delete'                      => __( 'Delete', 'simplyin' ),
					'code_invalid'                => __( 'Invalid code',
						'simplyin' ),
					'confirm_delete'              => __( 'Confirm delete',
						'simplyin' ),
					'delete_header'               => __( 'Delete address',
						'simplyin' ),
					'no_parcel_lockers'           => __( 'No available parcel lockers',
						'simplyin' ),
					'no_delivery_points'          => __( 'No available delivery points',
						'simplyin' ),
					'from'                        => __( 'from', 'simplyin' ),
					'service_type_parcel_machine' => __( 'Parcel locker', 'simplyin' ),
					'service_type_service_point'  => __( 'Pickup point', 'simplyin' ),
				],
				'currency'          => html_entity_decode( get_woocommerce_currency_symbol() ),
				'controllers'       => [
					'ajax'         => esc_url( admin_url( 'admin-ajax.php' ) ),
					'blocks_nonce' => wp_create_nonce( 'simplyin_block_payment' ),
				],
				'customer_email'    => $customer_email,
				'save_checkbox'     => ( get_option( 'simplyin_register_by_default' ) === 'off' || get_option( 'simplyin_register_by_default' ) === '' ) ? '0' : '1',
				'files_url'         => $assets->url( '' ),
				'currentLanguage'   => $current_language,
				'customer'          => [
					'logged' => is_user_logged_in(),
					'email'  => $customer_email,
				],
				'hide_phone_field'  => $hide_phone_field,
				'new_account_phone' => $new_account_phone,
				'is_block_checkout' => has_block( 'woocommerce/checkout' ) ? 'true' : 'false',
			];

			global $wp_query;

			if ( is_order_received_page() ) {
				$order_id = absint( $wp_query->query_vars['order-received'] );
				$order    = wc_get_order( $order_id );
				if ( $order && is_user_logged_in() ) {
					$return['order'] = [
						'order_id'    => $order_id,
						'order_token' => wp_create_nonce( 'order_' . $order_id ),
					];
				}
			}

			if ( ! empty( $override ) ) {
				$return = array_merge_recursive( $return, $override );
			}

			$json          = wp_json_encode( $return );
			$inline_script = "window.simplyin = $json;";
			wp_add_inline_script( 'simplyin-widget-js', $inline_script, 'before' );
		}
	}

	if ( ! function_exists( 'SimplyInAddCheckboxFlagField' ) ) {
		function SimplyInAddCheckboxFlagField() {
			$checkout = WC()->checkout();

			if ( isset( $checkout->checkout_fields['extra_fields'] ) ) {
				foreach ( $checkout->checkout_fields['extra_fields'] as $key => $field ) {
					woocommerce_form_field( $key,
						$field,
						$checkout->get_value( $key ) );
				}
			}
		}
	}

	if ( ! function_exists( 'SimplyInSaveFlagCheckboxValue' ) ) {
		function SimplyInSaveFlagCheckboxValue( $order_id ) {
			if ( isset( $_POST['simplyin_create_account_token'] ) ) {
				$nonce = sanitize_text_field( wp_unslash( $_POST['simplyin_create_account_token'] ) );
				if ( wp_verify_nonce( $nonce, 'simplyin_create_account_nonce' ) ) {
					$checkbox_status = ! empty( $_POST['simply-save-checkbox'] );
					$order           = wc_get_order( $order_id );
					$order->update_meta_data( 'simply-save-checkbox',
						$checkbox_status );
					$order->save_meta_data();
				}
			}
		}
	}

	if ( ! function_exists( 'SimplyInAddTaxIdToBilling' ) ) {
		function SimplyInAddTaxIdToBilling( $fields ): array {
			if ( function_exists( 'woocommerce_register_additional_checkout_field' ) ) {
				return $fields;
			}
			$candidates = array_values(
				array_filter(
					(array) apply_filters(
						'simplyin_tax_id_field_candidates',
						Tax_Id_Resolver::EXTERNAL_FIELD_CANDIDATES
					),
					static fn( $candidate ) => is_string( $candidate ) && (bool) preg_match( '/^[a-z0-9_]+$/i', $candidate )
				)
			);

			$nip_label_keywords = (array) apply_filters(
				'simplyin_tax_id_label_keywords',
				[ 'nip', 'vat', 'tax id', 'tax no', 'numer podatkowy' ]
			);

			$billing      = $fields['billing'] ?? [];
			$detected_key = '';

			foreach ( $billing as $key => $field ) {
				if ( 'billing_tax_id_simply' === $key ) {
					continue;
				}

				if ( in_array( $key, $candidates, true ) ) {
					$detected_key = $key;
					break;
				}
			}

			if ( '' === $detected_key ) {
				foreach ( $billing as $key => $field ) {
					if ( 'billing_tax_id_simply' === $key ) {
						continue;
					}

					$label = strtolower( (string) ( $field['label'] ?? '' ) );

					foreach ( $nip_label_keywords as $keyword ) {
						if ( is_string( $keyword ) && false !== strpos( $label, strtolower( $keyword ) ) ) {
							$detected_key = $key;
							break 2;
						}
					}
				}
			}

			if ( '' === $detected_key ) {
				$fields['billing']['billing_tax_id_simply'] = [
					'type'        => 'text',
					'label'       => __( 'Taxpayer Identification Number', 'simplyin' ),
					'placeholder' => __( 'Enter your Taxpayer Identification Number', 'simplyin' ),
					'required'    => false,
					'class'       => [ 'form-row-wide' ],
					'clear'       => true,
					'priority'    => 99,
				];
			}

			$fields['extra_fields']['simply_tax_label_id'] = [
				'type'    => 'text',
				'label'   => 'simply_tax_label_id',
				'required' => false,
				'class'   => [ 'form-row-wide' ],
				'clear'   => true,
				'default' => $detected_key,
			];

			$fields['extra_fields']['simply_billing_id'] = [
				'type'     => 'text',
				'label'    => 'simply_billing_id',
				'required' => false,
				'class'    => [ 'form-row-wide' ],
				'clear'    => true,
			];

			$fields['extra_fields']['simply_shipping_id'] = [
				'type'     => 'text',
				'label'    => 'simply_shipping_id',
				'required' => false,
				'class'    => [ 'form-row-wide' ],
				'clear'    => true,
			];

			return $fields;
		}
	}

	add_action(
		'woocommerce_init',
		function () {
			if ( ! function_exists( 'woocommerce_register_additional_checkout_field' ) ) {
				return;
			}

			woocommerce_register_additional_checkout_field( [
				'id'       => 'simplyin/billing_tax_id_simply',
				'location' => 'order',
				'type'     => 'text',
				'label'    => __( 'Taxpayer Identification Number', 'simplyin' ),
			] );

			$simplyin_register_by_default = get_option( 'simplyin_register_by_default' );

			woocommerce_register_additional_checkout_field( [
				'id'       => 'simplyin/simply-save-checkbox',
				'label'    => 'Save my data',
				'location' => 'order',
				'type'     => 'checkbox',
				'default'  => $simplyin_register_by_default !== 'off' && $simplyin_register_by_default !== '',
			] );

			woocommerce_register_additional_checkout_field( [
				'id'       => 'simplyin/simply_tax_label_id',
				'label'    => 'Simply Tax Label ID',
				'location' => 'order',
				'type'     => 'text',
			] );

			woocommerce_register_additional_checkout_field( [
				'id'       => 'simplyin/simply_billing_id',
				'label'    => 'Simply Billing ID',
				'location' => 'order',
				'type'     => 'text',
			] );

			woocommerce_register_additional_checkout_field( [
				'id'       => 'simplyin/simply_shipping_id',
				'label'    => 'Simply Shipping ID',
				'location' => 'order',
				'type'     => 'text',
			] );

			woocommerce_register_additional_checkout_field( [
				'id'       => 'simplyin/phoneAppInputField',
				'label'    => 'Phone App Input Field',
				'location' => 'order',
				'type'     => 'text',
			] );

			woocommerce_register_additional_checkout_field( [
				'id'       => 'simplyin/phoneAppInputPrefix',
				'label'    => 'Phone App Input Prefix',
				'location' => 'order',
				'type'     => 'text',
			] );
		}
	);

	if ( ! function_exists( 'SimplyInBlockCheckoutSaveTaxIdToOrder' ) ) {
		function SimplyInBlockCheckoutSaveTaxIdToOrder(
			WC_Order $order,
			$request
		) {

			$parameters = $request->get_json_params();
			$additional = $parameters['additional_fields'] ?? [];

			$tax_id_value           = isset( $additional['simplyin/billing_tax_id_simply'] )
				? sanitize_text_field( (string) $additional['simplyin/billing_tax_id_simply'] )
				: '';
			$billing_id             = sanitize_text_field( $additional['simplyin/simply_billing_id'] ?? '' );
			$shipping_id            = sanitize_text_field( $additional['simplyin/simply_shipping_id'] ?? '' );
			$save_checkbox          = $additional['simplyin/simply-save-checkbox'] ?? false;
			$phone_app_input_field  = sanitize_text_field( $additional['simplyin/phoneAppInputField'] ?? '' );
			$phone_app_input_prefix = sanitize_text_field( $additional['simplyin/phoneAppInputPrefix'] ?? '' );

			if ( $tax_id_value !== '' ) {
				$order->update_meta_data( '_billing_tax_id_simply', $tax_id_value );
			}
			$order->update_meta_data( '_simply_billing_id', $billing_id );
			$order->update_meta_data( '_simply_shipping_id', $shipping_id );
			$order->update_meta_data( '_simply-save-checkbox', $save_checkbox == 1 ? 'on' : '' );
			$order->update_meta_data( '_phoneAppInputField', $phone_app_input_field );
			$order->update_meta_data( '_phoneAppInputPrefix', $phone_app_input_prefix );

			// WC Blocks stores registered additional fields as _wc_other/<namespace>/<field_id>.
			// Remove them to avoid duplicate meta alongside our own _simply_* keys.
			$order->delete_meta_data( '_wc_other/simplyin/simply-save-checkbox' );
			$order->delete_meta_data( '_wc_other/simplyin/simply_billing_id' );
			$order->delete_meta_data( '_wc_other/simplyin/simply_shipping_id' );
			$order->delete_meta_data( '_wc_other/simplyin/phoneAppInputField' );
			$order->delete_meta_data( '_wc_other/simplyin/phoneAppInputPrefix' );
			$order->save_meta_data();
		}
	}

	if ( ! function_exists( 'SimplyInSaveTaxIdToOrder' ) ) {
		function SimplyInSaveTaxIdToOrder( $order_id ) {
			if ( isset( $_POST['simplyin_checkout_token'] ) ) {
				$nonce = sanitize_text_field( wp_unslash( $_POST['simplyin_checkout_token'] ) );

				if ( ! wp_verify_nonce( $nonce, 'simplyin_checkout_nonce' ) ) {

					return;
				}

				$order = wc_get_order( $order_id );
				if ( ! $order ) {
					return;
				}

				if ( ! empty( $_POST['billing_tax_id_simply'] ) ) {
					$order->update_meta_data( '_billing_tax_id_simply',
						sanitize_text_field( wp_unslash( $_POST['billing_tax_id_simply'] ) ) );
				}
				if ( ! empty( $_POST['simply_tax_label_id'] ) ) {
					$order->update_meta_data( '_simply_tax_label_id',
						sanitize_text_field( wp_unslash( $_POST['simply_tax_label_id'] ) ) );
				}
				if ( ! empty( $_POST['simply_billing_id'] ) ) {
					$order->update_meta_data( '_simply_billing_id',
						sanitize_text_field( wp_unslash( $_POST['simply_billing_id'] ) ) );
				}
				if ( ! empty( $_POST['simply_shipping_id'] ) ) {
					$order->update_meta_data( '_simply_shipping_id',
						sanitize_text_field( wp_unslash( $_POST['simply_shipping_id'] ) ) );
				}
				if ( ! empty( $_POST['phoneAppInputField'] ) ) {
					$order->update_meta_data( '_phoneAppInputField',
						sanitize_text_field( wp_unslash( $_POST['phoneAppInputField'] ) ) );
				}
				if ( ! empty( $_POST['phoneAppInputPrefix'] ) ) {
					$order->update_meta_data( '_phoneAppInputPrefix',
						sanitize_text_field( wp_unslash( $_POST['phoneAppInputPrefix'] ) ) );
				}

				$simplyin_save_checkbox = isset( $_POST['simply-save-checkbox'] ) ? sanitize_text_field( wp_unslash( $_POST['simply-save-checkbox'] ) ) : false;

				$order->update_meta_data( '_simply-save-checkbox',
					sanitize_text_field( $simplyin_save_checkbox ) );
				$order->save_meta_data();
			}
		}
	}


	if ( ! function_exists( 'SimplyInAddjQueryToFrontend' ) ) {
		function SimplyInAddjQueryToFrontend() {
			wp_enqueue_script( 'jquery' );
			wp_enqueue_script( 'jquery-ui-autocomplete' );
			wp_enqueue_script( 'jquery-ui-autocomplete-css' );
		}
	}

	if ( ! function_exists( 'SimplyInSaveCustomCheckoutField' ) ) {
		function SimplyInSaveCustomCheckoutField( $order_id ) {
			if ( isset( $_POST['simplyin_checkout_token'] ) ) {
				$nonce = sanitize_text_field( wp_unslash( $_POST['simplyin_checkout_token'] ) );

				if ( ! wp_verify_nonce( $nonce, 'simplyin_checkout_nonce' ) ) {

					return;
				}

				if ( ! empty( $_POST['billing_tax_id_simply'] ) ) {
					$order = wc_get_order( $order_id );
					if ( ! $order ) {
						return;
					}
					$order->update_meta_data( '_billing_tax_id_simply',
						sanitize_text_field( wp_unslash( $_POST['billing_tax_id_simply'] ) ) );
					$order->save_meta_data();
				}
			}
		}
	}

	if ( ! function_exists( 'SimplyInDisplayCustomOrderData' ) ) {
		function SimplyInDisplayCustomOrderData( $order ) {
			if ( $order instanceof WC_Order ) {
				// Check private key first, fall back to legacy public key for orders saved before unification.
				$billing_tax_id = $order->get_meta( '_billing_tax_id_simply' )
					?: $order->get_meta( 'billing_tax_id_simply' );
				if ( ! empty( $billing_tax_id ) ) {
					echo '<p><strong>Tax ID:</strong> ' . esc_html( $billing_tax_id ) . '</p>';
				}
			}
		}
	}

	if ( ! function_exists( 'SimplyInGetPaymentMethodData' ) ) {
		function SimplyInGetPaymentMethodData( $order ) {
			$payment_method       = $order->get_payment_method();
			$payment_gateways     = WC()->payment_gateways->get_available_payment_gateways();
			$payment_method_title = isset( $payment_gateways[ $payment_method ] ) ? $payment_gateways[ $payment_method ]->get_title() : '';

			return [
				'method' => $payment_method,
				'title'  => $payment_method_title,
			];
		}
	}

	if ( ! function_exists( 'SimplyInGetSanitizedPostData' ) ) {
		function SimplyInGetSanitizedPostData( $field_name ) {
			if ( isset( $_POST['simplyin_checkout_token'] ) ) {
				$nonce = sanitize_text_field( wp_unslash( $_POST['simplyin_checkout_token'] ) );

				if ( ! wp_verify_nonce( $nonce, 'simplyin_checkout_nonce' ) ) {

					return '';
				}

				return isset( $_POST[ $field_name ] )
					? sanitize_text_field( wp_unslash( $_POST[ $field_name ] ) ) : '';
			}

			if ( isset( $_POST['simplyin_blocks_token'] ) ) {
				$nonce_blocks = sanitize_text_field( wp_unslash( $_POST['simplyin_blocks_token'] ) );
				if ( wp_verify_nonce( $nonce_blocks, 'simplyin_blocks_nonce' ) ) {
					return isset( $_POST[ $field_name ] )
						? sanitize_text_field( wp_unslash( $_POST[ $field_name ] ) ) : '';
				}
			}

			if ( defined( 'REST_REQUEST' ) && REST_REQUEST && isset( $_POST[ $field_name ] ) ) {
				return sanitize_text_field( wp_unslash( $_POST[ $field_name ] ) );
			}

			return '';
		}
	}

	if ( ! function_exists( 'SimplyInGetSanitizedPostDataParcelMachineId' ) ) {
		function SimplyInGetSanitizedPostDataParcelMachineId(
			$field_name = 'parcel_machine_id'
		) {

			if ( isset( $_POST['simplyin_checkout_token'] ) ) {
				$nonce = sanitize_text_field( wp_unslash( $_POST['simplyin_checkout_token'] ) );

				if ( ! wp_verify_nonce( $nonce, 'simplyin_checkout_nonce' ) ) {

					return '';
				}

				if ( isset( $_POST[ $field_name ] ) ) {


					if ( is_array( $_POST[ $field_name ] ) && ! empty( $_POST[ $field_name ] )
					     && isset( $_POST[ $field_name ][0] )
					     && is_string( $_POST[ $field_name ][0] ) ) {
						return sanitize_text_field( wp_unslash( $_POST[ $field_name ][0] ) );
					}

					return sanitize_text_field( wp_unslash( $_POST[ $field_name ] ) );
				}

			}

			if ( isset( $_POST['simplyin_blocks_token'] ) ) {
				$nonce_blocks = sanitize_text_field( wp_unslash( $_POST['simplyin_blocks_token'] ) );
				if ( wp_verify_nonce( $nonce_blocks,
						'simplyin_blocks_nonce' ) && isset( $_POST[ $field_name ] ) ) {
					if ( is_array( $_POST[ $field_name ] ) && ! empty( $_POST[ $field_name ] )
					     && isset( $_POST[ $field_name ][0] )
					     && is_string( $_POST[ $field_name ][0] ) ) {
						return sanitize_text_field( wp_unslash( $_POST[ $field_name ][0] ) );
					}

					return sanitize_text_field( wp_unslash( $_POST[ $field_name ] ) );
				}
			}

			if ( defined( 'REST_REQUEST' ) && REST_REQUEST && isset( $_POST[ $field_name ] ) ) {
				if ( is_array( $_POST[ $field_name ] ) && ! empty( $_POST[ $field_name ] )
				     && isset( $_POST[ $field_name ][0] )
				     && is_string( $_POST[ $field_name ][0] ) ) {
					return sanitize_text_field( wp_unslash( $_POST[ $field_name ][0] ) );
				}

				return sanitize_text_field( wp_unslash( $_POST[ $field_name ] ) );
			}

			return '';
		}
	}

	if ( ! function_exists( 'SimplyInShouldCreateNewAccount' ) ) {
		function SimplyInShouldCreateNewAccount(
			$create_new_accountVal,
			$simplyin_Token_Input_Value
		): bool {
			return $create_new_accountVal === "on" && empty( $simplyin_Token_Input_Value );
		}
	}

	if ( ! function_exists( 'SimplyInHasAuthToken' ) ) {
		function SimplyInHasAuthToken( $simplyin_Token_Input_Value ): bool {
			return ! empty( $simplyin_Token_Input_Value );
		}
	}

	add_filter( 'cron_schedules', 'simplyin_add_update_cron_interval' );

	if ( ! function_exists( 'simplyin_add_update_cron_interval' ) ) {
		function simplyin_add_update_cron_interval( $schedules ) {
			$schedules['simplyin_update_interval'] = [
				'interval' => 60 * 60 * 24,
				'display'  => esc_html__( 'Simply.IN Update Interval',
					'simplyin' ),
			];

			return $schedules;
		}
	}


	// One-time migration: remove the legacy event registered under the old typo name.
	$simplyin_legacy_cron = wp_next_scheduled( 'simplyin_add_udpate_cron_interval' );
	if ( $simplyin_legacy_cron ) {
		wp_unschedule_event( $simplyin_legacy_cron, 'simplyin_add_udpate_cron_interval' );
	}

	// Schedule an action if it's not already scheduled
	if ( ! wp_next_scheduled( 'simplyin_add_update_cron_interval' ) ) {
		wp_schedule_event( time(),
			'simplyin_update_interval',
			'simplyin_add_update_cron_interval' );
	}

	// Hook into that action that'll fire every three minutes
	add_action( 'simplyin_add_update_cron_interval',
		'simplyin_update_interval_event_func' );

	if ( ! function_exists( 'simplyin_update_interval_event_func' ) ) {
		function simplyin_update_interval_event_func() {
			$simplyin_plugin = simplyin()->get_app();
			simplyin()
				->get_simplyin_logger()
				->log_if_wpdebug_on( "SimplyIn Sync started", "sync" );
			$simplyin_plugin->sync->sync();
		}
	}

}


/**
 * Deactivation hook.
 */
function simplyin_deactivate() {
	wp_clear_scheduled_hook( 'simplyin_add_update_cron_interval' );
	simplyin()
		->get_simplyin_logger()
		->log_if_wpdebug_on( "SimplyIn Plugin Deactivated", "general" );
}

register_deactivation_hook( __FILE__, 'simplyin_deactivate' );

add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ),
	'simplyin_add_settings_link' );
function simplyin_add_settings_link( array $links ): array {
	$settings_url  = admin_url( 'admin.php?page=simplyin-settings' );
	$settings_link = sprintf( '<a href="%s">%s</a>',
		esc_url( $settings_url ),
		__( 'Settings', 'simplyin' ) );

	array_unshift( $links, $settings_link );

	return $links;
}
