<?php
/**
 * FunnelKit Square Integration for WooCommerce
 *
 * This file handles the WooCommerce Settings integration for Square payments.
 *
 * @package FunnelKit_Square
 * @version 1.0.0
 */

namespace FKWCSQ\Includes\Integrations;

use FKWCSQ\Includes\Modules\Connection\MiddleWare;
use FKWCSQ\Includes\Webhooks\Simple_Webhook_Simulator;

use function wp_nonce_url;
use function wp_verify_nonce;
use function wp_safe_redirect;
use function admin_url;
use function get_option;
use function update_option;
use function sanitize_text_field;
use function esc_html__;
use function esc_html;
use function esc_url;
use function do_action;
use function wp_create_nonce;
use function wp_localize_script;

/**
 * WooCommerce Settings Integration
 *
 * @package FunnelKit_Square
 */

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

/**
 * Class WC_Settings
 */
class WC_Settings {

	/**
	 * Initialize the integration
	 */
	public static function init() {

		\add_filter( 'woocommerce_settings_tabs_array', array( __CLASS__, 'add_settings_tab' ), 50 );
		\add_action( 'woocommerce_sections_fkwcsq_square_api', array( __CLASS__, 'add_breadcrumb' ) );
		\add_action( 'woocommerce_sections_checkout', array( __CLASS__, 'add_breadcrumb' ) );
		\add_action( 'woocommerce_settings_fkwcsq_square_api', array( __CLASS__, 'output_settings' ) );
		\add_action( 'woocommerce_settings_save_fkwcsq_square_api', array( __CLASS__, 'save_settings' ) );
		\add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_scripts' ) );
		\add_action( 'admin_init', array( __CLASS__, 'handle_disconnect' ) );
		\add_action( 'admin_init', array( __CLASS__, 'load_connection_module' ) );
		\add_action( 'woocommerce_admin_field_square_connect', array( __CLASS__, 'render_square_connect_field' ) );
		\add_action( 'woocommerce_admin_field_square_test_connection', array( __CLASS__, 'render_square_test_connection_field' ) );
		\add_action( 'woocommerce_admin_field_manual_sync', array( __CLASS__, 'render_manual_sync_field' ) );
		\add_action( 'woocommerce_admin_field_square_import_products', array( __CLASS__, 'render_square_import_products_field' ) );
		\add_action( 'woocommerce_admin_field_webhook_simulation', array( __CLASS__, 'render_webhook_simulation_field' ) );
		\add_action( 'wp_ajax_fkwcsq_test_square_connection', array( __CLASS__, 'ajax_test_square_connection' ) );
		\add_action( 'wp_ajax_fkwcsq_import_square_products', array( __CLASS__, 'ajax_import_square_products' ) );
		\add_action( 'wp_ajax_fkwcsq_manual_sync', array( __CLASS__, 'ajax_manual_sync' ) );

		// Initialize simple webhook simulator
		Simple_Webhook_Simulator::init();
	}

	/**
	 * Initialize the connection module for Square integration.
	 *
	 * @return object Instance of the MiddleWare class.
	 */
	public static function fkwcsq_init_connection_module() {
		return MiddleWare::get_instance();
	}

	/**
	 * Handle connection callback from Square OAuth
	 * This replaces the functionality from Main.php's load_connection_module method
	 */
	public static function load_connection_module() {
		MiddleWare::get_instance()->handle_middleware_callback();
		MiddleWare::get_instance()->handle_disconnect_action();
	}

	/**
	 * Add new settings tab to the WooCommerce settings tabs array.
	 *
	 * @param array $settings_tabs Array of WooCommerce setting tabs.
	 *
	 * @return array $settings_tabs Array of WooCommerce setting tabs.
	 */
	public static function add_settings_tab( $settings_tabs ) {
		$settings_tabs['fkwcsq_square_api'] = 'Square';

		return $settings_tabs;
	}

	/**
	 * Add breadcrumb navigation
	 */
	public static function add_breadcrumb() {
		$current_tab     = isset( $_GET['tab'] ) ? sanitize_text_field( wp_unslash( $_GET['tab'] ) ) : ''; //phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$current_section = isset( $_GET['section'] ) ? sanitize_text_field( wp_unslash( $_GET['section'] ) ) : ''; //phpcs:ignore WordPress.Security.NonceVerification.Recommended

		$is_square_settings = ( $current_tab === 'fkwcsq_square_api' && empty( $current_section ) );
		$is_credit_cards    = ( $current_tab === 'checkout' && $current_section === 'fkwcsq_square' );
		$is_google_pay      = ( $current_tab === 'checkout' && $current_section === 'fkwcsq_google_pay' );
		$is_apple_pay       = ( $current_tab === 'checkout' && $current_section === 'fkwcsq_apple_pay' );
		$is_gift_card       = ( $current_tab === 'checkout' && $current_section === 'fkwcsq_gift_card' );
		$is_ach             = ( $current_tab === 'checkout' && $current_section === 'fkwcsq_ach' );
		$is_cash_app        = ( $current_tab === 'checkout' && $current_section === 'fkwcsq_cash_app' );
		$is_afterpay        = ( $current_tab === 'checkout' && $current_section === 'fkwcsq_afterpay' );

		// Only show the below HTML if any of the conditions match above.
		if ( ! $is_square_settings && ! $is_credit_cards && ! $is_google_pay && ! $is_apple_pay && ! $is_gift_card && ! $is_ach && ! $is_cash_app && ! $is_afterpay ) {
			return;
		}

		?>
		<ul class="subsubsub">
			<li>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=wc-settings&tab=fkwcsq_square_api' ) ); ?>"
					class="<?php echo esc_attr( $is_square_settings ? 'current' : '' ); ?>">
					<?php esc_html_e( 'Square Settings', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?>
				</a> |
			</li>
			<li>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=wc-settings&tab=checkout&section=fkwcsq_square' ) ); ?>"
					class="<?php echo esc_attr( $is_credit_cards ? 'current' : '' ); ?>">
					<?php esc_html_e( 'Credit Cards', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?>
				</a> |
			</li>
			<li>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=wc-settings&tab=checkout&section=fkwcsq_google_pay' ) ); ?>"
					class="<?php echo esc_attr( $is_google_pay ? 'current' : '' ); ?>">
					<?php esc_html_e( 'Google Pay', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?>
				</a> |
			</li>
			<li>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=wc-settings&tab=checkout&section=fkwcsq_apple_pay' ) ); ?>"
					class="<?php echo esc_attr( $is_apple_pay ? 'current' : '' ); ?>">
					<?php esc_html_e( 'Apple Pay', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?>
				</a> |
			</li>
			<li>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=wc-settings&tab=checkout&section=fkwcsq_ach' ) ); ?>"
					class="<?php echo esc_attr( $is_ach ? 'current' : '' ); ?>">
					<?php esc_html_e( 'ACH', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?>
				</a> |
			</li>
			<li>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=wc-settings&tab=checkout&section=fkwcsq_cash_app' ) ); ?>"
					class="<?php echo esc_attr( $is_cash_app ? 'current' : '' ); ?>">
					<?php esc_html_e( 'Cash App', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?>
				</a> |
			</li>
			<li>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=wc-settings&tab=checkout&section=fkwcsq_afterpay' ) ); ?>"
					class="<?php echo esc_attr( $is_afterpay ? 'current' : '' ); ?>">
					<?php esc_html_e( 'Afterpay', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?>
				</a> |
			</li>
			<li>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=wc-settings&tab=checkout&section=fkwcsq_gift_card' ) ); ?>"
					class="<?php echo esc_attr( $is_gift_card ? 'current' : '' ); ?>">
					<?php esc_html_e( 'Gift Cards', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?>
				</a>
			</li>
		</ul>
		<br class="clear" />
		<?php
	}

	/**
	 * Get all the settings for this plugin for @return array Array of settings
	 *
	 * @see woocommerce_admin_fields() function.
	 */
	public static function get_settings() {
		$settings        = array();
		$sandbox_tokens  = get_option( 'fkwcsq_sandbox_tokens', array() );
		$fkwcsq_settings = get_option( 'fkwcsq_settings', array() );

		$settings[] = array(
			'title' => __( 'Link Your Square Account', 'funnelkit-payment-gateway-square-for-woocommerce' ),
			'type'  => 'title',
			'desc'  => __( 'Seamlessly integrate your Square account to start processing payments on your WooCommerce store. <a href="https://funnelkit.com/docs/square-gateway-for-woocommerce/getting-started/setup/" class="fkwcsq-learn-more">Learn More</a>', 'funnelkit-payment-gateway-square-for-woocommerce' ),
			'id'    => 'fkwcsq_square_general_settings',
		);

		$settings[] = array(
			'title'    => __( 'Choose Environment', 'funnelkit-payment-gateway-square-for-woocommerce' ),
			'desc'     => __( 'Select whether you are in Sandbox (for testing) or Production (for live transactions).', 'funnelkit-payment-gateway-square-for-woocommerce' ),
			'id'       => 'fkwcsq_settings[environment]',
			'type'     => 'select',
			'options'  => array(
				'sandbox'            => __( 'Test Mode', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'sandbox_admin_only' => __( 'Test Mode (For administrators)', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'production'         => __( 'Live Mode', 'funnelkit-payment-gateway-square-for-woocommerce' ),
			),
			'default'  => 'production',
			'class'    => 'wc-enhanced-select',
			'desc_tip' => true,
		);

		$settings[] = array(
			'title'   => __( 'Sandbox API Key', 'funnelkit-payment-gateway-square-for-woocommerce' ),
			/* translators: %s: URL to Square Sandbox Documentation */
			'desc'    => sprintf( __( 'Enter the application ID for the Square sandbox environment, used for testing. <a href="%s" target="_blank">Where to find these keys</a>', 'funnelkit-payment-gateway-square-for-woocommerce' ), 'https://funnelkit.com/docs/square-gateway-for-woocommerce/getting-started/production-and-sandbox-mode/#sandbox-mode' ),
			'id'      => 'fkwcsq_settings[sandbox_application_id]',
			'type'    => 'text',
			'default' => '',
			'value'   => isset( $sandbox_tokens['application_id'] ) ? $sandbox_tokens['application_id'] : '',
			'css'     => 'width: 400px;',
			'class'   => 'sandbox-field',
		);

		$settings[]   = array(
			'title'   => __( 'Sandbox Access Token', 'funnelkit-payment-gateway-square-for-woocommerce' ),
			/* translators: %s: URL to Square Sandbox Documentation */
			'desc'    => sprintf( __( 'Enter the token for authentication in the sandbox environment. Ensure it is from the correct account. <a href="%s" target="_blank">Where to find these keys</a>', 'funnelkit-payment-gateway-square-for-woocommerce' ), 'https://funnelkit.com/docs/square-gateway-for-woocommerce/getting-started/production-and-sandbox-mode/#sandbox-mode' ),
			'id'      => 'fkwcsq_settings[sandbox_access_token]',
			'type'    => 'text',
			'default' => '',
			'value'   => isset( $sandbox_tokens['access_token'] ) ? $sandbox_tokens['access_token'] : '',
			'css'     => 'width: 400px;',
			'class'   => 'sandbox-field',
		);
		$site_url     = site_url( '/' );
		$redirect_uri = admin_url( 'admin.php?page=wc-settings&tab=fkwcsq_square_api' );

		$test_url = sprintf(
			'https://secure-auth.funnelkit.com/square/index.php/connect?site_url=%s&redirect_uri=%s&sandbox=1',
			rawurlencode( $site_url ),
			rawurlencode( $redirect_uri )
		);

		$decoded_url = urldecode( $test_url );

		// Only show this block when query param fkwcsq_sandbox_connect=yes is present
		if ( isset( $_GET['fkwcsq_sandbox_connect'] ) && 'yes' === sanitize_text_field( wp_unslash( $_GET['fkwcsq_sandbox_connect'] ) ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$settings[] = array(
				'title' => __( 'Test with URL', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'desc'  => sprintf(
					/* translators: 1: Test URL link, 2: Decoded URL in code tags */
					__( 'Click <a href="%1$s" rel="noopener noreferrer">here</a> to test the Square OAuth connection in sandbox mode.<br><code>%2$s</code>', 'funnelkit-payment-gateway-square-for-woocommerce' ),
					esc_url( $test_url ),
					esc_html( $decoded_url )
				),
				'type'  => 'title',
				'class' => 'sandbox-field',
				'id'    => 'fkwcsq_square_test_sandbox_url',
			);
		}

		$settings[] = array(
			'type'  => 'square_connect',
			'id'    => 'fkwcsq_connect_button',
			'title' => '',
			'desc'  => '',
		);

		// Add Test Connection button
		$settings[] = array(
			'title' => __( 'Verify Connection', 'funnelkit-payment-gateway-square-for-woocommerce' ),
			'type'  => 'square_test_connection',
			'id'    => 'fkwcsq_test_connection_button',
			'desc'  => __( 'Click to verify the connection. A successful connection will enable payment processing.', 'funnelkit-payment-gateway-square-for-woocommerce' ),
		);

		$settings[] = array(
			'type' => 'sectionend',
			'id'   => 'fkwcsq_square_general_settings',
		);

		// Add Webhook Simulation button only if Square is configured
		if ( \FKWCSQ\Square::is_configured() ) {
			$settings[] = array(
				'title' => __( 'Webhook Simulation', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'type'  => 'webhook_simulation',
				'id'    => 'fkwcsq_webhook_simulation_button',
				'desc'  => __( 'Click to simulate a webhook event and test webhook processing.', 'funnelkit-payment-gateway-square-for-woocommerce' ),
			);
		}

		$settings[] = array(
			'type' => 'sectionend',
			'id'   => 'fkwcsq_webhook_simulation_section',
		);

			$settings[] = array(
				'title' => __( 'Choose Business Location', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'type'  => 'title',
				'desc'  => __( 'Select the Square location where your payments will be processed. Ensure it matches your actual business location.', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'id'    => 'fkwcsq_square_additional_settings',
			);
			$locations  = get_option( 'fkwcsq_locations', array() );
			$options    = array();
			if ( ! empty( $locations ) ) {
				foreach ( $locations as $loc ) {
					$options[ $loc['id'] ] = $loc['name'] . ( isset( $loc['address']['locality'] ) ? ' (' . $loc['address']['locality'] . ')' : '' );
				}
			}
			$settings[] = array(
				'title'   => __( 'Production Location', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'desc'    => __( 'Select the Square location to use for payments.', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'id'      => 'fkwcsq_settings[location_id]',
				'type'    => 'select',
				'options' => $options,
				'default' => isset( $fkwcsq_settings['location_id'] ) ? $fkwcsq_settings['location_id'] : '',
				'class'   => 'wc-enhanced-select',
				'value'   => isset( $fkwcsq_settings['location_id'] ) ? $fkwcsq_settings['location_id'] : '',
			);

			$sandbox_locations = get_option( 'fkwcsq_sandbox_locations', array() );
			$sandbox_options   = array();
			if ( ! empty( $sandbox_locations ) ) {
				foreach ( $sandbox_locations as $loc ) {
					$sandbox_options[ $loc['id'] ] = $loc['name'] . ( isset( $loc['address']['locality'] ) ? ' (' . $loc['address']['locality'] . ')' : '' );
				}
			}
			$settings[] = array(
				'title'   => __( 'Sandbox Location', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'desc'    => __( 'Select the Square location to use for payments.', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'id'      => 'fkwcsq_settings[sandbox_location_id]',
				'type'    => 'select',
				'options' => $sandbox_options,
				'default' => isset( $fkwcsq_settings['sandbox_location_id'] ) ? $fkwcsq_settings['sandbox_location_id'] : '',
				'class'   => 'wc-enhanced-select',
				'value'   => isset( $fkwcsq_settings['sandbox_location_id'] ) ? $fkwcsq_settings['sandbox_location_id'] : '',
			);

			$settings[] = array(
				'type' => 'sectionend',
				'id'   => 'fkwcsq_square_general_settings',
			);
			// General Settings Section
			$settings[] = array(
				'title' => __( 'Data Sync Settings', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'type'  => 'title',
				'desc'  => __( 'Choose how you want store data (products, inventory, customers, categories) to sync between your WooCommerce store and Square, ensuring consistency across platforms. </br><a href="https://funnelkit.com/docs/square-gateway-for-woocommerce/product-data-sync/settings/" class="fkwcsq-learn-more">Learn More about Sync</a>', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'id'    => 'fkwcsq_square_additional_settings',
			);
			$settings[] = array(
				'title'   => __( 'Data Sync Preferences', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'desc'    => __( 'Choose the sync direction: Square (Square to WooCommerce), WooCommerce (WooCommerce to Square), or Disabled (no sync).', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'id'      => 'fkwcsq_settings[sync_direction]',
				'type'    => 'select',
				'options' => array(
					'disabled'    => __( 'Disabled', 'funnelkit-payment-gateway-square-for-woocommerce' ),
					'square'      => __( 'Square', 'funnelkit-payment-gateway-square-for-woocommerce' ),
					'woocommerce' => __( 'WooCommerce', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				),
				'default' => 'disabled',
				'class'   => 'wc-enhanced-select fkwcsq-sync-direction',
			);

			$settings[] = array(
				'title'   => __( 'Sync Frequency', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'desc'    => __( 'Set the interval for syncing store data. Choose the frequency that best suits your store\'s needs.', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'id'      => 'fkwcsq_settings[sync_interval]',
				'type'    => 'select',
				'options' => array(
					'15min' => __( '15 minutes', 'funnelkit-payment-gateway-square-for-woocommerce' ),
					'30min' => __( '30 minutes', 'funnelkit-payment-gateway-square-for-woocommerce' ),
					'1h'    => __( '1 hour', 'funnelkit-payment-gateway-square-for-woocommerce' ),
					'2h'    => __( '2 hours', 'funnelkit-payment-gateway-square-for-woocommerce' ),
					'3h'    => __( '3 hours', 'funnelkit-payment-gateway-square-for-woocommerce' ),
					'6h'    => __( '6 hours', 'funnelkit-payment-gateway-square-for-woocommerce' ),
					'8h'    => __( '8 hours', 'funnelkit-payment-gateway-square-for-woocommerce' ),
					'12h'   => __( '12 hours', 'funnelkit-payment-gateway-square-for-woocommerce' ),
					'24h'   => __( '24 hours', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				),
				'default' => '15min',
				'class'   => 'wc-enhanced-select',
			);

			$settings[] = array(
				'title' => __( 'Manual Sync', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'type'  => 'manual_sync',
			);

			$settings[] = array(
				'type' => 'sectionend',
				'id'   => 'fkwcsq_square_sync_settings',
			);

			$settings[] = array(
				'title' => __( 'Import Products', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'type'  => 'square_import_products',
			);

			$settings[] = array(
				'type' => 'sectionend',
				'id'   => 'fkwcsq_square_import_section',
			);

			// General Settings Section
			$settings[] = array(
				'title' => __( 'General Settings', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'type'  => 'title',
				'desc'  => '',
				'id'    => 'fkwcsq_square_additional_settings',
			);

			$settings[] = array(
				'title'   => __( 'Enable Debug Logging', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'desc'    => __( 'Log any debug messages to help diagnose issues related to payment processing.', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'id'      => 'fkwcsq_settings[enable_logging]',
				'type'    => 'checkbox',
				'default' => 'yes',
			);

			$settings[] = array(
				'title'   => __( 'Create Customer in Square', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'desc'    => __( 'Automatically create a customer in Square when an order is placed on your WooCommerce store.', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'id'      => 'fkwcsq_settings[create_customer]',
				'type'    => 'checkbox',
				'default' => 'no',
			);

			$settings[] = array(
				'title'   => __( 'Sync WooCommerce orders from Square', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'desc'    => __( 'Create WooCommerce orders when Square sends a payment for this location from outside your checkout (e.g. POS, invoices). Turn off to stop creating those orders.', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'id'      => 'fkwcsq_settings[sync_woocommerce_order_from_square]',
				'type'    => 'checkbox',
				'default' => 'yes',
			);

			$settings[] = array(
				'type' => 'sectionend',
				'id'   => 'fkwcsq_square_additional_settings',
			);

			return $settings;
	}

	/**
	 * Handle disconnect action
	 */
	public static function handle_disconnect() {
		if ( isset( $_GET['fkwcsq_disconnect'] ) && isset( $_GET['_wpnonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'fkwcsq_disconnect' ) ) {
			$connection = self::fkwcsq_init_connection_module();
			$connection->disconnect();

			// Redirect back to the settings page with a success message
			wp_safe_redirect(
				add_query_arg(
					array(
						'page'       => 'wc-settings',
						'tab'        => 'fkwcsq_square_api',
						'connection' => 'disconnected',
					),
					admin_url( 'admin.php' )
				)
			);
			exit;
		}
	}

	/**
	 * Render the Square connect field type
	 */
	public static function render_square_connect_field() {
		$connection         = self::fkwcsq_init_connection_module();
		$settings           = get_option( 'fkwcsq_settings', array() );
		$sandbox_tokens     = get_option( 'fkwcsq_sandbox_tokens', array() );
		$prod_tokens        = get_option( 'fkwcsq_tokens', array() );
		$production_connect = false;
		$sandboxconnect     = false;

		if ( ! empty( $prod_tokens['access_token'] ) ) {
			$production_connect = true;
		} elseif ( ! empty( $sandbox_tokens['access_token'] ) ) {
			$sandboxconnect = true;
		}

		// Fetch business/location name for the current environment
		$business_name = '';
		if ( $production_connect ) {
			$locations   = get_option( 'fkwcsq_locations', array() );
			$location_id = isset( $settings['location_id'] ) ? $settings['location_id'] : '';
			if ( ! empty( $locations ) && $location_id ) {
				foreach ( $locations as $loc ) {
					if ( isset( $loc['id'] ) && $loc['id'] === $location_id ) {
						$business_name = $loc['name'];
						break;
					}
				}
			}
		} elseif ( $sandboxconnect ) {
			$sandbox_locations = get_option( 'fkwcsq_sandbox_locations', array() );
			$location_id       = isset( $settings['sandbox_location_id'] ) ? $settings['sandbox_location_id'] : '';
			if ( ! empty( $sandbox_locations ) && $location_id ) {
				foreach ( $sandbox_locations as $loc ) {
					if ( isset( $loc['id'] ) && $loc['id'] === $location_id ) {
						$business_name = $loc['name'];
						break;
					}
				}
			}
		}
		?>
		<tr valign="top" class="fkwcsq-connection-row">
			<th scope="row" class="titledesc">
				<label><?php esc_html_e( 'Link Your Square Account', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?></label>
			</th>
			<td class="forminp">
				<div class="fkwcsq-connection-block fkwcsq-production-block">
					<?php if ( $production_connect ) : ?>
						<div class="fkwcsq-connection-status connected">
							<p>
								<span class="dashicons dashicons-yes-alt"></span>
								<?php
								echo esc_html__( 'Connected to Square', 'funnelkit-payment-gateway-square-for-woocommerce' );
								if ( $business_name ) {
									echo ' ' . esc_html__( 'as', 'funnelkit-payment-gateway-square-for-woocommerce' ) . ' ' . esc_html( $business_name );
								}
								echo ' ' . esc_html__( 'in', 'funnelkit-payment-gateway-square-for-woocommerce' ) . ' <strong>' . esc_html__( 'Production', 'funnelkit-payment-gateway-square-for-woocommerce' ) . '</strong> ' . esc_html__( 'mode', 'funnelkit-payment-gateway-square-for-woocommerce' );
								?>
							</p>
							<p>
								<a href="
								<?php
								echo esc_url(
									wp_nonce_url(
										add_query_arg(
											array(
												'page' => 'wc-settings',
												'tab'  => 'fkwcsq_square_api',
												'fkwcsq_disconnect' => '1',
											),
											admin_url( 'admin.php' )
										),
										'fkwcsq_disconnect'
									)
								);
								?>
								" class="button button-secondary fkwcsq-disconnect-button">
									<?php echo esc_html__( 'Disconnect from Square', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?>
								</a>
							</p>
						</div>

					<?php else : ?>
						<div class="fkwcsq-connection-status not-connected">
							<p>
								<a href="#"
								class="button button-primary square-connect-btn"
								data-url="<?php echo esc_url( $connection->get_connection_url() ); ?>">
									<?php echo esc_html__( 'Connect with Square', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?>
								</a>
							</p>
						</div>

					<?php endif; ?>
				</div>
			</td>
		</tr>
		<?php

		// Display connection errors if any
		if ( isset( $_GET['connection'] ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$message           = '';
			$type              = 'error';
			$connection_status = \sanitize_text_field( wp_unslash( $_GET['connection'] ) ); //phpcs:ignore WordPress.Security.NonceVerification.Recommended

			switch ( $connection_status ) {
				case 'error':
					$message = \__( 'Connection to Square failed. Please try again.', 'funnelkit-payment-gateway-square-for-woocommerce' );
					break;
				case 'success':
					$message = \__( 'Successfully connected to Square!', 'funnelkit-payment-gateway-square-for-woocommerce' );
					$type    = 'success';
					break;
				case 'disconnected':
					$message = \__( 'Successfully disconnected from Square.', 'funnelkit-payment-gateway-square-for-woocommerce' );
					$type    = 'success';
					break;
			}

			if ( $message ) {
				?>
				<tr>
					<td colspan="2">
						<div class="notice notice-<?php echo \esc_attr( $type ); ?>">
							<p><?php echo \esc_html( $message ); ?></p>
						</div>
						<script>
						document.addEventListener('DOMContentLoaded', function() {
							if (window.history && window.history.replaceState) {
								const url = new URL(window.location);
								url.searchParams.delete('connection');
								url.searchParams.delete('error');
								url.searchParams.delete('disconnected');
								window.history.replaceState({}, document.title, url.toString());
							}
						});
						</script>
					</td>
				</tr>
				<?php
			}
		}

		// Display sync result notices
		if ( isset( $_GET['sync_result'] ) && isset( $_GET['sync_message'] ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$sync_result  = sanitize_text_field( wp_unslash( $_GET['sync_result'] ) ); //phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$sync_message = sanitize_text_field( wp_unslash( $_GET['sync_message'] ) ); //phpcs:ignore WordPress.Security.NonceVerification.Recommended

			$type = $sync_result === 'success' ? 'success' : 'error';
			?>
			<tr>
				<td colspan="2">
					<div class="notice notice-<?php echo esc_attr( $type ); ?> is-dismissible">
						<p><?php echo esc_html( $sync_message ); ?></p>
					</div>
				</td>
			</tr>
			<?php
		}
	}

	/**
	 * Render manual sync field
	 */
	public static function render_manual_sync_field() {
		?>
		<tr valign="top">
			<th scope="row" class="titledesc">
				<label><?php esc_html_e( 'Manual Sync', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?></label>
				<span class="woocommerce-help-tip" data-tip="<?php esc_attr_e( 'This will sync products, categories, inventory, and customers between your WooCommerce store and Square based on your current sync settings.', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?>"></span>
			</th>
			<td class="forminp">
				<button type="button" class="button button-primary" id="fkwcsq-manual-sync">
					<?php esc_html_e( 'Sync Now ( Products, Categories, Inventory, Customers )', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?>
				</button>
				<span id="fkwcsq-manual-sync-result" style="margin-left:10px;"></span>
				<p class="description">
					<?php esc_html_e( 'Please contact support for any syncing related queries or issues.', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?>
					<a href="https://funnelkit.com/support/" target="_blank" ><?php esc_html_e( 'Contact Support', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?></a>
				</p>
				<?php
				$settings  = get_option( 'fkwcsq_settings', array() );
				$direction = isset( $settings['sync_direction'] ) ? $settings['sync_direction'] : 'disabled';

				if ( $direction !== 'disabled' ) {
					$last_sync  = get_option( 'fkwcsq_last_sync', '' );
					$sync_hooks = array( 'fkwcsq_sync_products', 'fkwcsq_sync_categories', 'fkwcsq_sync_inventory', 'fkwcsq_sync_customers' );

					$next_sync = null;
					foreach ( $sync_hooks as $hook ) {
						$timestamp = as_next_scheduled_action( $hook );
						if ( $timestamp && ( $next_sync === null || $timestamp < $next_sync ) ) {
							$next_sync = $timestamp;
						}
					}

					?>
					<p class="description sync-timing">
						<?php
						if ( ! empty( $last_sync ) ) {
							/* translators: %s: Last sync date and time */
							printf( esc_html__( 'Last synced: %s', 'funnelkit-payment-gateway-square-for-woocommerce' ), esc_html( wp_date( 'M j, Y g:i A', strtotime( $last_sync ) ) ) );
						}

						if ( $next_sync ) {
							// translators: %s: Next sync date and time
							echo ! empty( $last_sync ) ? sprintf( esc_html__( ' | Next sync: %s', 'funnelkit-payment-gateway-square-for-woocommerce' ), esc_html( get_date_from_gmt( gmdate( 'Y-m-d H:i:s', $next_sync ), 'M j, Y g:i A' ) ) )
								// translators: %s: Next sync date and time
								: sprintf( esc_html__( 'Next sync: %s', 'funnelkit-payment-gateway-square-for-woocommerce' ), esc_html( get_date_from_gmt( gmdate( 'Y-m-d H:i:s', $next_sync ), 'M j, Y g:i A' ) ) );
						}
						?>
					</p>
					<?php
					if ( ! empty( $last_sync ) ) {
						// Get sync statuses
						$sync_statuses = array(
							'products'   => get_option( 'fkwcsq_products_sync_status', array() ),
							'categories' => get_option( 'fkwcsq_categories_sync_status', array() ),
							'inventory'  => get_option( 'fkwcsq_inventory_sync_status', array() ),
							'customers'  => get_option( 'fkwcsq_customers_sync_status', array() ),
						);

						// Check overall status
						$any_failed     = false;
						$last_timestamp = '';

						foreach ( $sync_statuses as $status ) {
							if ( ! empty( $status ) ) {
								if ( $status['status'] === 'failed' ) {
									$any_failed = true;
								}
								if ( empty( $last_timestamp ) || strtotime( $status['timestamp'] ) > strtotime( $last_timestamp ) ) {
									$last_timestamp = $status['timestamp'];
								}
							}
						}

						if ( ! empty( $last_timestamp ) ) {
							$status_text  = $any_failed ? __( 'Failed', 'funnelkit-payment-gateway-square-for-woocommerce' ) : __( 'Succeeded', 'funnelkit-payment-gateway-square-for-woocommerce' );
							$status_class = $any_failed ? 'fkwcsq-sync-failed' : 'fkwcsq-sync-success';
							?>
								<p class="sync-status <?php echo esc_attr( $status_class ); ?> description">
								<?php esc_html_e( 'Last sync status:', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?>
									<strong><?php echo esc_html( $status_text ); ?></strong>
								</p>
								<?php
						}
					}
					?>
					<?php
				}
				?>
			</td>
		</tr>
		<?php
	}

	/**
	 * Render the Square import products field
	 */
	public static function render_square_import_products_field() {
		?>
		<table class="form-table" id="fkwcsq-import-products-table">

			<tbody>
			<tr valign="top">
				<th scope="row" class="titledesc">
					<label><?php esc_html_e( 'Import Products', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?></label>
					<span class="woocommerce-help-tip" data-tip="<?php esc_attr_e( 'This will import all products from your Square account to WooCommerce.', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?>"></span>
				</th>
				<td class="forminp">
					<button type="button" class="button button-primary" id="fkwcsq-import-square-products" style="font-weight: bold;">
						<?php esc_html_e( 'Import All Square Products', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?>
					</button>
					<span id="fkwcsq-import-square-products-result" style="margin-left:10px;"></span>
				</td>
			</tr>
			</tbody>
		</table>
		<?php
	}

	/**
	 * Render the Square test connection field
	 */
	public static function render_square_test_connection_field() {
		?>
		<tr valign="top">
			<th scope="row" class="titledesc">
				<label><?php esc_html_e( 'Verify Connection', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?></label>
			</th>
			<td class="forminp">
				<button type="button" class="button" id="fkwcsq-test-connection"><?php esc_html_e( 'Verify Connection', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?></button>
				<span id="fkwcsq-test-connection-result" style="margin-left:10px;"></span>
				<p class="description"><?php esc_html_e( 'Click to verify the connection. A successful connection will enable payment processing.', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?></p>
			</td>
		</tr>
		<?php
	}

	/**
	 * Output the settings.
	 */
	public static function output_settings() {
		$settings        = self::get_settings();
		$fkwcsq_settings = \get_option( 'fkwcsq_settings', array() );
		$sandbox_tokens  = \get_option( 'fkwcsq_sandbox_tokens', array() );

		// Pre-fill values from main plugin settings
		foreach ( $settings as &$setting ) {
			if ( isset( $setting['id'] ) ) {
				if ( strpos( $setting['id'], 'fkwcsq_settings[' ) === 0 ) {
					$key = str_replace( array( 'fkwcsq_settings[', ']' ), '', $setting['id'] );

					// For sandbox fields, get values from sandbox_tokens
					if ( $key === 'sandbox_application_id' && isset( $sandbox_tokens['application_id'] ) ) {
						$setting['value'] = $sandbox_tokens['application_id'];
					} elseif ( $key === 'sandbox_access_token' && isset( $sandbox_tokens['access_token'] ) ) {
						$setting['value'] = $sandbox_tokens['access_token'];
					} elseif ( $setting['type'] === 'checkbox' ) {
						$setting['checked'] = isset( $fkwcsq_settings[ $key ] ) && $fkwcsq_settings[ $key ] === 'yes';
					} elseif ( isset( $fkwcsq_settings[ $key ] ) ) {
						$setting['value'] = $fkwcsq_settings[ $key ];
					}
				}
			}
		}

		\woocommerce_admin_fields( $settings );

		?>
		<?php
	}

	/**
	 * Save the settings.
	 */
	public static function save_settings() {
		// Check user permissions
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			return;
		}
		if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), 'woocommerce-settings' ) ) {
			return;
		}

		$fkwcsq_settings = get_option( 'fkwcsq_settings', array() );
		$sandbox_tokens  = get_option( 'fkwcsq_sandbox_tokens', array() );

		$updated = false;

		// Get settings for processing
		$settings = self::get_settings();

		// Handle checkbox fields from fkwcsq_settings array
		if ( isset( $_POST['fkwcsq_settings'] ) && is_array( $_POST['fkwcsq_settings'] ) ) {
			$posted_settings = array_map( 'sanitize_text_field', wp_unslash( $_POST['fkwcsq_settings'] ) );

			// Handle environment selection first
			if ( isset( $posted_settings['environment'] ) ) {
				$environment     = sanitize_text_field( $posted_settings['environment'] );
				$old_environment = isset( $fkwcsq_settings['environment'] ) ? $fkwcsq_settings['environment'] : 'production';

				// Only update if environment has changed
				if ( $old_environment !== $environment ) {
					$fkwcsq_settings['environment'] = $environment;
					$updated                        = true;

					update_option( 'fkwcsq_settings', $fkwcsq_settings );
				}
			}

			// Handle sandbox credentials
			if ( isset( $posted_settings['sandbox_application_id'] ) || isset( $posted_settings['sandbox_access_token'] ) ) {
				// Get the posted values or empty string if not set
				$new_app_id       = isset( $posted_settings['sandbox_application_id'] ) ? trim( $posted_settings['sandbox_application_id'] ) : '';
				$new_access_token = isset( $posted_settings['sandbox_access_token'] ) ? trim( $posted_settings['sandbox_access_token'] ) : '';

				// If either field is empty, clear both sandbox tokens
				if ( empty( $new_app_id ) || empty( $new_access_token ) ) {
					delete_option( 'fkwcsq_sandbox_tokens' );
					delete_option( 'fkwcsq_sandbox_locations' );
					unset( $fkwcsq_settings['sandbox_connection_status'] );
					unset( $fkwcsq_settings['sandbox_location_id'] );
				} elseif ( $new_app_id !== ( $sandbox_tokens['application_id'] ?? '' ) || $new_access_token !== ( $sandbox_tokens['access_token'] ?? '' ) ) {
					$sandbox_tokens = array(
						'application_id' => $new_app_id,
						'access_token'   => $new_access_token,
						'expires_at'     => time() + ( 30 * DAY_IN_SECONDS ),
					);
					update_option( 'fkwcsq_sandbox_tokens', $sandbox_tokens );

					// Initialize API client with new token
					$api = \FKWCSQ\Includes\API::get_instance();

					// Get and save location ID
					$locations = $api->get_locations();

					if ( ! ( $locations instanceof \WP_Error ) && ! empty( $locations ) ) {
						$fkwcsq_settings['sandbox_location_id'] = $locations[0]['id'];
					}

					$fkwcsq_settings['sandbox_connection_status'] = 'connected';
					update_option( 'fkwcsq_settings', $fkwcsq_settings );

					// Save connection timestamp for version tracking
					update_option( 'fkwcsq_connection_timestamp', time(), false );

					// Trigger action for gateway management
					do_action( 'fkwcsq_after_connection' );
				}
			}

			// Handle other fields
			foreach ( $settings as $setting ) {
				if ( isset( $setting['id'] ) && strpos( $setting['id'], 'fkwcsq_settings[' ) === 0 ) {
					$key = str_replace( array( 'fkwcsq_settings[', ']' ), '', $setting['id'] );

					// Skip sandbox fields as they're handled separately
					if ( in_array( $key, array( 'sandbox_application_id', 'sandbox_access_token' ) ) ) {
						continue;
					}

					// For checkboxes
					if ( $setting['type'] === 'checkbox' ) {
						$new_value = isset( $posted_settings[ $key ] ) ? 'yes' : 'no';
						if ( ! isset( $fkwcsq_settings[ $key ] ) || $fkwcsq_settings[ $key ] !== $new_value ) {
							$fkwcsq_settings[ $key ] = $new_value;
							$updated                 = true;
						}
					} elseif ( isset( $posted_settings[ $key ] ) ) {
						$new_value = sanitize_text_field( $posted_settings[ $key ] );
						if ( ! isset( $fkwcsq_settings[ $key ] ) || $fkwcsq_settings[ $key ] !== $new_value ) {
							$fkwcsq_settings[ $key ] = $new_value;
							$updated                 = true;
						}
					}
				}
			}

			// Handle location fields separately from posted data
			$current_environment = isset( $posted_settings['environment'] ) ? $posted_settings['environment'] : ( $fkwcsq_settings['environment'] ?? 'production' );

			// Handle production location_id
			if ( $current_environment === 'production' && isset( $posted_settings['location_id'] ) ) {
				if ( $posted_settings['location_id'] !== ( $fkwcsq_settings['location_id'] ?? null ) ) {
					$fkwcsq_settings['location_id'] = $posted_settings['location_id'];
					$updated                        = true;
				}
			}

			// Handle sandbox location_id
			if ( ( $current_environment === 'sandbox' || $current_environment === 'sandbox_admin_only' ) && isset( $posted_settings['sandbox_location_id'] ) ) {
				if ( $posted_settings['sandbox_location_id'] !== ( $fkwcsq_settings['sandbox_location_id'] ?? null ) ) {
					$fkwcsq_settings['sandbox_location_id'] = $posted_settings['sandbox_location_id'];
					$updated                                = true;
				}
			}
		}

		// Only update if changes were made
		if ( $updated ) {
			update_option( 'fkwcsq_settings', $fkwcsq_settings );
			do_action( 'fkwcsq_settings_saved', $fkwcsq_settings );
		}
	}

	/**
	 * Enqueue admin scripts
	 *
	 * @param string $hook Current admin page.
	 */
	public static function enqueue_scripts( $hook ) {
		if ( 'woocommerce_page_wc-settings' !== $hook ) {
			return;
		}

		// Get current tab and section
		$current_tab     = isset( $_GET['tab'] ) ? sanitize_text_field( wp_unslash( $_GET['tab'] ) ) : ''; //phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$current_section = isset( $_GET['section'] ) ? sanitize_text_field( wp_unslash( $_GET['section'] ) ) : ''; //phpcs:ignore WordPress.Security.NonceVerification.Recommended

		// Check if we're on a Square-related tab or section
		$is_square_settings = ( $current_tab === 'fkwcsq_square_api' && empty( $current_section ) );
		$is_credit_cards    = ( $current_tab === 'checkout' && $current_section === 'fkwcsq_square' );
		$is_google_pay      = ( $current_tab === 'checkout' && $current_section === 'fkwcsq_google_pay' );
		$is_apple_pay       = ( $current_tab === 'checkout' && $current_section === 'fkwcsq_apple_pay' );

		// Only load Square admin assets if we're on a Square-related page
		if ( ! $is_square_settings && ! $is_credit_cards && ! $is_google_pay && ! $is_apple_pay ) {
			return;
		}

		// Core styles
		\wp_enqueue_style( 'woocommerce' );
		\wp_enqueue_style( 'select2' );
		\wp_enqueue_style( 'dashicons' );

		// Plugin styles
		\wp_enqueue_style( 'fkwcsq-admin', FKWCSQ_PLUGIN_URL . 'assets/css/admin' . \FKWCSQ\Includes\API::get_instance()->is_min_suffix() . '.css', array(), FKWCSQ_VERSION );

		// Scripts
		\wp_enqueue_script( 'selectWoo' );
		\wp_enqueue_script( 'jquery-blockui' );
		\wp_enqueue_script( 'fkwcsq-admin', FKWCSQ_PLUGIN_URL . 'admin/js/admin' . \FKWCSQ\Includes\API::get_instance()->is_min_suffix() . '.js', array( 'jquery', 'selectWoo', 'jquery-blockui' ), FKWCSQ_VERSION, true );

		$settings     = get_option( 'fkwcsq_settings', array() );
		$sandbox_mode = \FKWCSQ\Square::is_sandbox_mode();

		// Get location data for both environments
		$production_locations = get_option( 'fkwcsq_locations', array() );
		$sandbox_locations    = get_option( 'fkwcsq_sandbox_locations', array() );

		$production_options = array();
		$sandbox_options    = array();

		if ( ! empty( $production_locations ) ) {
			foreach ( $production_locations as $loc ) {
				$production_options[ $loc['id'] ] = $loc['name'] . ( isset( $loc['address']['locality'] ) ? ' (' . $loc['address']['locality'] . ')' : '' );
			}
		}

		if ( ! empty( $sandbox_locations ) ) {
			foreach ( $sandbox_locations as $loc ) {
				$sandbox_options[ $loc['id'] ] = $loc['name'] . ( isset( $loc['address']['locality'] ) ? ' (' . $loc['address']['locality'] . ')' : '' );
			}
		}

		wp_localize_script(
			'fkwcsq-admin',
			'fkwcsq_params',
			array(
				'ajax_url'        => admin_url( 'admin-ajax.php' ),
				'nonce'           => wp_create_nonce( 'fkwcsq-admin' ),
				'application_id'  => isset( $settings['application_id'] ) ? $settings['application_id'] : '',
				'redirect_uri'    => admin_url( 'admin.php?page=wc-settings&tab=fkwcsq_square_api&fkwcsq-callback=1' ),
				'sandbox_mode'    => $sandbox_mode,
				'connect_url'     => $sandbox_mode ? 'https://app.squareup.com/oauth2/authorize' : 'https://app.squareup.com/oauth2/authorize',
				'locations'       => array(
					'production' => $production_options,
					'sandbox'    => $sandbox_options,
				),
				'saved_locations' => array(
					'production' => isset( $settings['location_id'] ) ? $settings['location_id'] : '',
					'sandbox'    => isset( $settings['sandbox_location_id'] ) ? $settings['sandbox_location_id'] : '',
				),
				'i18n'            => array(
					'connect_confirm'    => __( 'You are about to connect to Square. Continue?', 'funnelkit-payment-gateway-square-for-woocommerce' ),
					'disconnect_confirm' => __( 'You are about to disconnect from Square. All payment functionality will stop working. Continue?', 'funnelkit-payment-gateway-square-for-woocommerce' ),
					'success'            => __( 'Success!', 'funnelkit-payment-gateway-square-for-woocommerce' ),
					'error'              => __( 'Error:', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				),
				'apple_pay'       => array(
					'nonce'                    => wp_create_nonce( 'fkwcsq_reverify_apple_pay_domain' ),
					'verifying_text'           => __( 'Verifying...', 'funnelkit-payment-gateway-square-for-woocommerce' ),
					'reverify_text'            => __( 'Reverify Domain', 'funnelkit-payment-gateway-square-for-woocommerce' ),
					'verifying_domain_text'    => __( 'Verifying domain...', 'funnelkit-payment-gateway-square-for-woocommerce' ),
					'verification_failed_text' => __( 'Verification failed. Please try again.', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				),
			)
		);

		wp_localize_script(
			'fkwcsq-admin',
			'fkwcsq_test_connection',
			array(
				'ajax_url' => admin_url( 'admin-ajax.php' ),
				'nonce'    => wp_create_nonce( 'fkwcsq-test-connection' ),
			)
		);

		wp_localize_script(
			'fkwcsq-admin',
			'fkwcsq_import_square_products',
			array(
				'nonce'   => wp_create_nonce( 'fkwcsq_import_square_products' ),
				'ajaxurl' => admin_url( 'admin-ajax.php' ),
			)
		);

		wp_localize_script(
			'fkwcsq-admin',
			'fkwcsq_manual_sync',
			array(
				'nonce'   => wp_create_nonce( 'fkwcsq_manual_sync' ),
				'ajaxurl' => admin_url( 'admin-ajax.php' ),
			)
		);
	}

	/**
	 * Register AJAX handler for test connection
	 */
	public static function ajax_test_square_connection() {
		check_ajax_referer( 'fkwcsq-test-connection', 'nonce' );

		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( __( 'Unauthorized', 'funnelkit-payment-gateway-square-for-woocommerce' ) );
		}

		$api       = \FKWCSQ\Includes\API::get_instance();
		$locations = $api->get_locations();

		if ( is_wp_error( $locations ) || empty( $locations ) ) {
			$error = is_wp_error( $locations ) ? $locations->get_error_message() : __( 'Connection failed.', 'funnelkit-payment-gateway-square-for-woocommerce' );
			wp_send_json_error( $error );
		}

		wp_send_json_success( __( 'Square Successfully Connected ', 'funnelkit-payment-gateway-square-for-woocommerce' ) );
	}

	/**
	 * AJAX handler for importing products from Square
	 */
	public static function ajax_import_square_products() {
		check_ajax_referer( 'fkwcsq_import_square_products' );
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( __( 'Unauthorized', 'funnelkit-payment-gateway-square-for-woocommerce' ) );
		}

		// Check if Square is properly configured
		if ( ! \FKWCSQ\Square::is_configured() ) {
			wp_send_json_error( __( 'Square integration is not configured. Please connect your Square account first.', 'funnelkit-payment-gateway-square-for-woocommerce' ) );
		}

		$count = \FKWCSQ\Includes\Sync\Product::get_instance()->import_all_from_square();
		if ( is_wp_error( $count ) ) {
			wp_send_json_error( $count->get_error_message() );
		}
		wp_send_json_success( sprintf( ( 'Imported %d products from Square.' ), $count ) );
	}

	/**
	 * AJAX handler for manual sync
	 */
	public static function ajax_manual_sync() {
		check_ajax_referer( 'fkwcsq_manual_sync' );
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( __( 'Unauthorized', 'funnelkit-payment-gateway-square-for-woocommerce' ) );
		}

		// Check if Square is properly configured
		if ( ! \FKWCSQ\Square::is_configured() ) {
			wp_send_json_error( __( 'Square integration is not configured. Please connect your Square account first.', 'funnelkit-payment-gateway-square-for-woocommerce' ) );
		}

		// Run all sync functions from cron.php
		\FKWCSQ\Includes\Cron::fkwcsq_sync_products();
		\FKWCSQ\Includes\Cron::fkwcsq_sync_inventory();
		\FKWCSQ\Includes\Cron::fkwcsq_sync_categories();
		\FKWCSQ\Includes\Cron::fkwcsq_sync_customers();

		wp_send_json_success( __( 'Manual sync completed successfully!', 'funnelkit-payment-gateway-square-for-woocommerce' ) );
	}

	/**
	 * Render the webhook simulation field
	 */
	public static function render_webhook_simulation_field( $value ) {
		?>
		<table class="form-table">
			<tr valign="top">
				<th scope="row" class="titledesc">
					<label for="<?php echo esc_attr( $value['id'] ); ?>"><?php echo esc_html( $value['title'] ); ?></label>
				</th>
				<td class="forminp">
					<button type="button" class="button fkwcsq-simulate-webhook">
						<?php esc_html_e( 'Simulate Webhook', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?>
					</button>
					<p class="description"><?php echo esc_html( $value['desc'] ); ?></p>
				</td>
			</tr>
		</table>

		<?php
	}
}
