<?php
/**
 * Plugin Name: Simply.IN
 * Version: 5.5.4
 * Plugin URI: https://wordpress.org/plugins/simplyin/
 * Description: Simply.IN – maximum convenience and higher conversions with lightning-fast checkout!
 * Tested up to: 6.8.3
 * Requires PHP: 7.4
 * Author: Simply.IN
 * Author URI: https://simply.in
 * Domain Path: /lang/
 * 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
 */


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


$config = [
	'__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'          => 8.9,
	'required_php_extensions' => [ 'curl' ],
];


require_once __DIR__ . '/system_check.php';
if ( ( new SimplyIN_System_Check( $config ) )->evaluate_system() ) {
	require_once __DIR__ . '/vendor/autoload.php';

	function simplyin(): \Simplyin\Simplyin_W_Plugin\Plugin {
		return new \Simplyin\Simplyin_W_Plugin\Plugin();
	}

	simplyin()->execute( $config );
} else {
	return;
}

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['APP_VERSION_PREFIX_STAGE'];
		$environmentVersion         = $env['APP_VERSION_PREFIX_STAGE'];
		simplyin()::$logger_enabled = true;
		break;

	case 'dev':
		$backendEnvironment         = $env['APP_VERSION_PREFIX_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;
}

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

simplyin()->set_simplyin_config( $simplyin_config );

if ( get_option( 'SimplyInApiConnection' ) === '1' ) {
	$hooks = new \Simplyin\Simplyin_W_Plugin\Hooks\Hooks();

	$hooks->init();

}

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

		return $plugin_data['Version'];
	}

	return '5.5.4';
}


/**
 * Activation hook.
 */
function simpylinActivate() {

	update_option( 'SimplyIn_Backend_Url',
		simplyin()->get_backend_simplyin_url() );
	update_option( 'SimplyIn_Environment',
		simplyin()->get_environment_version_prefix() );
	//update_option( 'simplyin_api_key', "" );
	//update_option( 'SimplyInApiConnection', 0 );
	simplyin()->update_option( 'SimplyInSettingsErrorMsg',
		0 );
}

register_activation_hook( __FILE__, 'simpylinActivate' );

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


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 ( get_option( 'SimplyInApiConnection' ) === '1' ) {

	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 );

	function addCustomStringToOrderDetailsCustomer( $order ) {

		$billing_tax_id = get_post_meta( $order->get_id(),
			'_billing_tax_id_simply',
			true );

		echo '<script>const areaname = document.querySelector(".woocommerce-column--billing-address").querySelector(".woocommerce-customer-details--email");
	const newNode = document.createElement("div");
	const taxIdText =  "tax id: " + ' . json_encode( $billing_tax_id ) . '
	newNode.innerText=taxIdText;
	areaname.parentNode.appendChild(newNode);</script>';
	}

	add_action( 'woocommerce_order_details_after_customer_details',
		'addCustomStringToOrderDetailsCustomer',
		10,
		1 );

	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;
	}

	add_filter( 'woocommerce_checkout_fields',
		'simplyInCustomOverrideCheckoutFields',
		100,
		1 );

	add_action( 'woocommerce_after_checkout_form', 'SimplyInLoadReactApp' );

	add_action( 'wp_enqueue_scripts',
		'SimplyInLoadReactAppForBlockCheckout',
		9999 );

	function SimplyInLoadReactAppForBlockCheckout() {

		if ( has_block( 'woocommerce/checkout' ) && ! is_order_received_page() ) {
			SimplyInLoadReactApp();
		}
	}

	function SimplyInLoadReactApp() {
		// If is order received page
		if ( is_checkout() && ! empty( is_wc_endpoint_url( 'order-received' ) ) ) {
			return;
		}

		wp_enqueue_script(
			'SimplyInAppData',
			plugin_dir_url( __FILE__ ) . 'public/widget/front.js',
			[ 'jquery', 'wp-element' ],
			wp_rand(),
			true
		);

		wp_enqueue_style(
			'SimplyInAppData',
			plugin_dir_url( __FILE__ ) . 'public/widget/front.css',
			[],
			wp_rand(),
			'all'
		);

		$current_user = wp_get_current_user();
		unset( $current_user->user_pass );

		SimplyInGetJsDefaultHeader();
	}

	function SimplyInGetJsDefaultHeader( $override = [] ) {
		$current_user      = wp_get_current_user();
		$current_language  = get_locale();
		$customer_email    = $current_user->user_email;
		$hide_phone_field  = false;
		$new_account_phone = false;

		if ( $customer_email ) {
			$hide_phone_field  = email_exists( $customer_email ) ? true : false;
			$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' ),
				'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' ),
			],
			'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' ) ? '1' : '0',
			'files_url'         => plugin_dir_url( __FILE__ ),
			'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( 'SimplyInAppData', $inline_script, 'before' );
	}

	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 ) );
			}
		}
	}

	add_action( 'woocommerce_checkout_after_order_review',
		'SimplyInAddCheckboxFlagField' );//get_option( 'SimplyInApiConnection' )

	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();
			}
		}
	}

	add_action( 'woocommerce_checkout_update_order_meta',
		'SimplyInSaveFlagCheckboxValue' );

	function SimplyInTaxIdFieldTranslate( $string ) {
		$translations = [
			'pl_PL' => [
				'Tax ID'            => 'Tax identification number (NIP)',
				'Enter your Tax ID' => 'Enter your NIP number',
			],
			'en_US' => [
				'Tax ID'            => 'Tax ID',
				'Enter your Tax ID' => 'Enter your Tax ID',
			],
		];

		$locale = get_locale();
		if ( isset( $translations[ $locale ][ $string ] ) ) {
			return $translations[ $locale ][ $string ];
		} else {
			return $string; // Fallback to English if no translation found
		}
	}

	function SimplyInAddTaxIdToBilling( $fields ) {
		$fields['billing']['billing_tax_id_simply']    = [
			'type'        => 'text',
			'label'       => SimplyInTaxIdFieldTranslate( 'Tax ID' ),
			'placeholder' => SimplyInTaxIdFieldTranslate( 'Enter your Tax ID' ),
			'required'    => false,
			'class'       => [ 'form-row-wide' ],
		];
		$fields['extra_fields']['simply_tax_label_id'] = [
			'type'     => 'text',
			'label'    => 'simply_tax_label_id',
			'required' => false,
			'class'    => [ 'form-row-wide' ],
			'clear'    => true,
		];

		$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 () {
			woocommerce_register_additional_checkout_field( [
				'id'       => 'simplyin/billing_tax_id_simply',
				'location' => 'order',
				'type'     => 'text',
				'label'    => SimplyInTaxIdFieldTranslate( 'Tax ID' ),
			] );

			$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 == 'on' ? '1' : '0',
			] );

			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',
			] );
		}
	);

	add_filter( 'woocommerce_checkout_fields', 'SimplyInAddTaxIdToBilling' );

	add_action( 'woocommerce_checkout_update_order_meta',
		'SimplyInSaveTaxIdToOrder' );

	add_action( 'woocommerce_store_api_checkout_update_order_from_request',
		'SimplyInBlockCheckoutSaveTaxIdToOrder',
		10,
		2 );
	function SimplyInBlockCheckoutSaveTaxIdToOrder(
		WC_Order $order,
		$request
	) {

		$parameters = $request->get_json_params();

		$tax_label_id           = $parameters['additional_fields']['simplyin/billing_tax_id_simply'];
		$billing_id             = $parameters['additional_fields']['simplyin/simply_billing_id'];
		$shipping_id            = $parameters['additional_fields']['simplyin/simply_shipping_id'];
		$save_checkbox          = $parameters['additional_fields']['simplyin/simply-save-checkbox'];
		$phone_app_input_field  = $parameters['additional_fields']['simplyin/phoneAppInputField'];
		$phone_app_input_prefix = $parameters['additional_fields']['simplyin/phoneAppInputPrefix'];

		$_POST['simply_tax_label_id']  = $tax_label_id;
		$_POST['simply_billing_id']    = $billing_id;
		$_POST['simply_shipping_id']   = $shipping_id;
		$_POST['simply-save-checkbox'] = $save_checkbox == 1 ? 'on' : false;
		$_POST['phoneAppInputField']   = $phone_app_input_field;
		$_POST['phoneAppInputPrefix']  = $phone_app_input_prefix;

		$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();
	}

	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 ( ! 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();
		}
	}


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

	add_action( 'wp_enqueue_scripts', 'SimplyInAddjQueryToFrontend' );

	add_action( 'woocommerce_checkout_update_order_meta',
		'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 );
				$order->update_meta_data( 'billing_tax_id_simply',
					sanitize_text_field( wp_unslash( $_POST['billing_tax_id_simply'] ) ) );
				$order->save_meta_data();
			}
		}
	}

	add_action( 'woocommerce_admin_order_data_after_billing_address',
		'SimplyInDisplayCustomOrderData' );

	function SimplyInDisplayCustomOrderData( $order ) {
		if ( $order instanceof WC_Order ) {
			$billing_tax_id = $order->get_meta( 'billing_tax_id_simply' );
			if ( ! empty( $billing_tax_id ) ) {
				echo '<p><strong>Tax ID:</strong> ' . esc_html( $billing_tax_id ) . '</p>';
			}
		}
	}

	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,
		];
	}

	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 '';
	}

	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 '';
	}

	function SimplyInShouldCreateNewAccount(
		$create_new_accountVal,
		$simplyin_Token_Input_Value
	) {
		return $create_new_accountVal === "on" && empty( $simplyin_Token_Input_Value );
	}

	function SimplyInHasAuthToken( $simplyin_Token_Input_Value ) {
		return ! empty( $simplyin_Token_Input_Value );
	}

	add_filter( 'cron_schedules', 'simplyin_add_udpate_cron_interval' );

	function simplyin_add_udpate_cron_interval( $schedules ) {
		$schedules['simplyin_update_interval'] = [
			'interval' => 60 * 60 * 2,
			'display'  => esc_html__( 'SimplyIn Update Interval',
				'simplyin' ),
		];

		return $schedules;
	}


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

	// Hook into that action that'll fire every three minutes
	add_action( 'simplyin_add_udpate_cron_interval',
		'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_udpate_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;
}
