<?php
/**
 * Plugin Name: Simply.IN
 * Version: 5.5.12
 * 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: 6.9
 * Requires PHP: 7.4
 * Author: Simply.IN
 * Author URI: https://simply.in
 * 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\Assets;
use Simplyin\Simplyin_W_Plugin\Hooks\Hooks;
use Simplyin\Simplyin_W_Plugin\Payments\Gateway\Gateway_Helper;
use Simplyin\Simplyin_W_Plugin\Plugin;

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(): Plugin {
		return new 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 Hooks();

	$hooks->init();

}

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

		return $plugin_data['Version'];
	}

	return '5.5.12';
}


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

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

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

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

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

		return $assets;
	}

	add_action( 'wp_enqueue_scripts', 'simplyin_load_react_app_for_checkout', 50 );

	/**
	 * Enqueue widget assets on checkout (classic + blocks).
	 *
	 * @return void
	 */
	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
	 */
	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 );
	}

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

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