<?php
/**
 * TP Applepay Gateway.
 */
 
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

require_once dirname( __FILE__ ) . '/constants.php';
require_once dirname( __FILE__ ) . '/tp-applepay-gateway-helper-trait.php';
require_once dirname( __FILE__ ) . '/tp-applepay-session-manager-trait.php'; // Add this line

class WC_Totalprocessing_Applepay_Gateway extends WC_Payment_Gateway {
    use TotalProcessingGatewayDebugTrait, TotalProcessingApplePayGatewayHelperTrait, TotalProcessingApplePaySessionManagerTrait, TotalProcessingGatewayLoggerTrait;

    public function __construct() {
        $this->id                                = TP_APPLEPAY_GATEWAY_ID;
        $this->icon                              = '';
        $this->has_fields                        = false;
        $this->method_title                      = TP_APPLEPAY_GATEWAY_TITLE;
        $this->method_description                = TP_APPLEPAY_GATEWAY_DESCRIPTION;
        $this->supports                          = array(
            'products',
            'refunds'
        );
        $this->title                             = TP_APPLEPAY_GATEWAY_TITLE;
        $this->description                       = TP_APPLEPAY_GATEWAY_DESCRIPTION;
        $this->enabled                           = $this->get_option( 'enabled' );
        $this->onlyadmins                        = $this->get_option( 'onlyadmins' );
        $this->jsLogging                         = $this->get_option( 'jsLogging' );
        $this->serversidedebug                   = $this->get_option( 'serversidedebug' );
        $this->logLevels                         = $this->get_option( 'logLevels' );
        $this->onlyLoggedIn                      = $this->get_option( 'onlyLoggedIn' );
        $this->inheritcreds                      = $this->get_option( 'inheritcreds' );
        $this->inheritGatewayCrentialsFromCardProcessing();
        $this->enableTermCheckbox                = $this->get_option( 'enableTermCheckbox', 'yes' );
        $this->termCheckboxErrorText             = $this->get_option( 'termCheckboxErrorText', 'Please tick and conditions checkbox to proceed' );
        $this->enforceShipping                   = $this->get_option( 'enforceShipping', 'no' );
        $this->fastCheckoutOnCart                = false;//$this->get_option( 'fastCheckoutOnCart' );
        $this->platformBase                      = $this->get_option( 'platformBase' );
        $this->entityId_test                     = $this->get_option( 'entityId_test' );
        $this->accessToken_test                  = $this->get_option( 'accessToken_test' );
        $this->entityId                          = $this->get_option( 'entityId' );
        $this->accessToken                       = $this->get_option( 'accessToken' );
        $this->paymentType                       = $this->get_option( 'paymentType' );
        $this->domainsToVerify                   = $this->get_option( 'domainsToVerify' );
        $this->acceptedCards                     = $this->get_option( 'acceptedCards' );
        $this->billingAddressFields              = $this->get_option( 'billingAddressFields', [] );
        $this->shippingAddressFields             = $this->get_option( 'shippingAddressFields', [] );
        $this->applepaycountryCode               = $this->get_option( 'applepaycountryCode' );
        $this->merchantCapabilities              = $this->get_option( 'applepaymerchantCapabilities' );
        $this->supportedNetworks                 = $this->get_option( 'applepaysupportedNetworks' );
        $this->supportedCountries                = $this->get_option( 'applepaysupportedCountries' );
        $this->displayName                       = $this->get_option( 'applepaydisplayName' );
        $this->label                             = $this->get_option( 'applepaylabel' );
        $this->refreshPage                       = ($this->get_option( 'refreshPage' ) == 'yes' ? true : false);
        $this->forceCreateAcc                    = ($this->get_option( 'forceCreateAcc' ) == 'yes' ? true : false);
        $this->shipInclTax                       = ($this->get_option( 'shipInclTax' ) == 'yes' ? true : false);
        //custom css
        $this->customCss                         = $this->get_option( 'customCss' );
        //apple pay button styles
        $this->applepayapplepaystyle             = $this->get_option( 'applepayapplepaystyle' );
        $this->applepayapplepaytype              = $this->get_option( 'applepayapplepaytype' );
        $this->applepayapplepaylanguage          = $this->get_option( 'applepayapplepaylanguage' );
        //set file locations
        $this->domainVerificationFileName        = TP_APPLEPAY_GATEWAY_DOMAIN_VERIFY_FILENAME;

        $this->init_form_fields();
        $this->init_settings();

        // Initialise settings
        //Load funcs
        add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
    }
    
    public function settings_fields($merge=false) {
        $settings                  = include dirname( __FILE__ ) . '/payment-gateway-setting-fields.php';
        
        if( $merge === true ){
            $retArr = [];
            foreach( $settings as $subSettings ){
                if( count( $subSettings ) > 0 ){
                    if( isset( $subSettings['fields'] ) ){
                        if( count( $subSettings['fields'] ) > 0 ){
                            $retArr = array_merge( $retArr, $subSettings['fields'] );
                        }
                    }
                }
            }
            return $retArr;
        }
        return $settings;
    }

    public function init_form_fields(){
        $this->form_fields = $this->settings_fields(true);
    }
    
    public function admin_options() {
        require_once dirname( __FILE__ ) . '/admin/admin-options.php';
    }
    
    public function get_icon() {
        $icons_str = '';
        return apply_filters( 'woocommerce_gateway_icon', $icons_str, $this->id );
    }
    
    public function check_plugin(){
        if($this->enabled === 'yes'){
            if($this->onlyadmins === 'yes'){
                if( ! current_user_can( 'administrator' ) ) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }
    
    public function getPluginVer(){
        return TP_APPLEPAY_VERSION;
    }

    /**
     * FIXED: Enhanced run method with cleanup hooks
     */
    public function run( $plugin_basename ){
        //action hooks
        add_action( 'init', array( $this, '_init' ) );
        
        // FIXED: Add cleanup hooks
        add_action('tp_applepay_cleanup_stale_data', array($this, 'cleanupStaleData'));
        add_action('init', array($this, 'scheduleCleanupTask'));
    
        // **NEW**: Attach session reset hooks
        $this->attachSessionResetHooks();
        
        if(is_user_logged_in() === true){
            if( current_user_can( 'administrator' ) ) {
                add_action( 'wp_ajax_moveValidationFile', array( $this, 'moveValidationFile' ) );
                add_action( 'wp_ajax_nopriv_moveValidationFile', array( $this, 'moveValidationFile' ) );
                
                add_action( 'wp_ajax_sendDomainRegistrationRequest', array( $this, 'sendDomainRegistrationRequest' ) );
                add_action( 'wp_ajax_tpApplepaydomainRegistationSuccess', array( $this, 'domainRegistrationRequestThanks' ) );
            }
        }
        
        //check plugin
        if($this->check_plugin()){
            add_action( 'wp_enqueue_scripts', array( $this, 'payment_scripts_tpap' ) );
            if( $this->fastCheckoutOnCart == 'yes' ){
                add_action( 'woocommerce_proceed_to_checkout', array( $this, 'draw_express_applepay_tpap' ) );
            }
            add_action( 'cfw_before_payment_methods_block', array( $this, 'draw_express_applepay_tpap' ) );
            add_action( 'woocommerce_review_order_before_payment', array( $this, 'draw_express_applepay_tpap' ) );
            add_action( 'woocommerce_pay_order_before_payment', array( $this, 'draw_express_applepay_tpap' ) );
            
            // FIXED: Enhanced AJAX handlers with better error handling
            add_action( 'wp_ajax_tp_applepay_checkout_response', array( $this, 'requestCheckoutID' ) );
            add_action( 'wp_ajax_nopriv_tp_applepay_checkout_response', array( $this, 'requestCheckoutID' ) );
            add_action( 'wc_ajax_onPaymentAuthorized', array( $this, 'onPaymentAuthorized' ) );
            add_action( 'wc_ajax_nopriv_onPaymentAuthorized', array( $this, 'onPaymentAuthorized' ) );
            add_action( 'wp_ajax_tpapplepay_check_transaction_status', array( $this, 'validateTransactionStatus' ) );
            add_action( 'wp_ajax_nopriv_tpapplepay_check_transaction_status', array( $this, 'validateTransactionStatus' ) );

            add_filter( 'woocommerce_cart_needs_shipping_address', array( $this, 'enforce_shipping_address' ) );
        }
        
        //filter hooks
        add_filter( 'plugin_action_links_' . $plugin_basename, array( $this, 'plugin_action_links' ) );
        //add_filter( 'woocommerce_available_payment_gateways', array( $this, 'tpap_remove_method' ), 20, 1);
        if(!function_exists('is_plugin_active')) {
            include_once(ABSPATH . 'wp-admin/includes/plugin.php');
            if(is_plugin_active( 'woocommerce-multilingual/wpml-woocommerce.php' )){
                add_filter( 'wcml_multi_currency_ajax_actions', array( $this, 'tpap_support_ml_ajax' ), 10, 1 );
            }
        }
    }
    
    public function tpap_support_ml_ajax( $ajax_actions ){
        $ajax_actions[] = 'identChosenShipping';
        $ajax_actions[] = 'onPaymentAuthorized';
        
        return $ajax_actions;
    }
    
    public function plugin_action_links( $links ) {
        $plugin_links = array(
            '<a href="admin.php?page=wc-settings&tab=checkout&section='.$this->id.'">' . 'Settings' . '</a>',
        );
        return array_merge( $plugin_links, $links );
    }
    
    public function checkPageShouldRun(){
        if(is_checkout() === true || is_wc_endpoint_url( 'order-pay' ) === true){
            return true;
        }
        if($this->fastCheckoutOnCart == 'yes' && is_cart()){
            return true;
        }
        return false;
    }

    /**
     * Enhanced payment_scripts_tpap method to initialize session
     */
    public function payment_scripts_tpap() {
        if($this->checkPageShouldRun() === true){
            
            // **NEW**: Initialize Apple Pay session
            $this->initializeApplePaySession();
            
            $tp_pluginVer = $this->getPluginVer();

            $order_id     = WC()->session->get('order_awaiting_payment', 0);
            $order_id     = is_wc_endpoint_url( 'order-pay' ) === true ? absint( get_query_var('order-pay') ) : $order_id;
            
            // Add cache busting parameter
            $cache_buster = time();

            wp_register_script( 'tp_applepay_swal', 'https://cdn.jsdelivr.net/npm/sweetalert2@11', [] , null );
            wp_register_script( 'tp_applepay', plugin_dir_url( dirname( __FILE__ ) ).'assets/js/tpJsv2_logging.js?v='.$tp_pluginVer.'&cb='.$cache_buster , ['jquery','wp-util'] , null );
            wp_localize_script( 'tp_applepay', 'tpVars', [
                "subTotalAmount"                => (string)WC()->cart->get_total(null),
                "cartPage"                      => wc_get_cart_url(),
                "refreshPage"                   => $this->refreshPage,
                "isCheckout"                    => is_checkout(),
                "isCart"                        => is_cart(),
                "isOrderPay"                    => is_wc_endpoint_url( 'order-pay' ) === true ? 1 : 0,
                'orderpay_order_id'             => $order_id,
                "pluginId"                      => $this->id,
                "pluginVer"                     => $tp_pluginVer,
                "adminUrl"                      => get_admin_url().'admin-ajax.php',
                "applepayifrURL"                => site_url('tp-apple-pay-init?v='.$cache_buster) . ($order_id > 0 ? "&order_id=" . $order_id : ""),
                "debug_mode"                    => ($this->serversidedebug === 'yes'),
                "cache_buster"                  => $cache_buster,
                "page_session_id"               => WC()->session->get('applepay_page_session_id', ''), // **NEW**
                "page_load_time"                => WC()->session->get('applepay_page_load_time', time()) // **NEW**
            ]);
            wp_enqueue_style( 'tpap_style', TOTALPROCESSING_PAYMENTGATEWAY_APPLEPAY_BASEURL . 'assets/css/tpapv2-style.css?v=' . $tp_pluginVer . '&cb=' . $cache_buster , [] , null );
            wp_add_inline_style( 'tpap_style', $this->customCss );
            wp_enqueue_script('tp_applepay_swal');
            wp_enqueue_script('tp_applepay');
        }
    }

    /**
     * FIXED: Plugin deactivation cleanup
     */
    public static function plugin_deactivation_cleanup() {
        // Clear all scheduled events
        wp_clear_scheduled_hook('tp_applepay_cleanup_stale_data');
        
        // Clean up transients
        global $wpdb;
        $wpdb->query("
            DELETE FROM {$wpdb->options}
            WHERE option_name LIKE '_transient_applepay_%'
            OR option_name LIKE '_transient_timeout_applepay_%'
            OR option_name LIKE '_transient_checkout_%'
        ");
    }
    
    public function draw_express_applepay_tpap() {
        if (
            // "woocommerce_enable_signup_and_login_from_checkout" === no.
            false === filter_var( WC()->checkout()->is_registration_enabled(), FILTER_VALIDATE_BOOLEAN ) &&
            // "woocommerce_enable_guest_checkout" === no.
            true === filter_var( WC()->checkout()->is_registration_required(), FILTER_VALIDATE_BOOLEAN ) &&
            ! is_user_logged_in()
        ) {
            return;
        }
        if($this->checkPageShouldRun() === true){
            $ref_page            = 'checkout';
            if( is_cart() ){
                $ref_page        = 'cart';
            }
            if($this->onlyLoggedIn == 'yes'){
                if(is_user_logged_in() === true){
                    echo $this->applePayButtonsArray($ref_page);
                }
            } else {
                echo $this->applePayButtonsArray($ref_page);
            }
        }
    }
    
    public function tpap_remove_method( $available_gateways ){
        $gateway_id = $this->id;
        if(is_checkout()) {
            if(isset($available_gateways[$gateway_id])){
                unset($available_gateways[$gateway_id]);
            }
        }
        return $available_gateways;
    }
    
    public function identChosenShipping() {
        $chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
        $chosen_shipping = $chosen_methods[0];
        return $chosen_shipping;
    }
    
    public function validatePaymentTransactionID($transactionID){
        $headers                 = ['Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8','Authorization' => 'Bearer '.$this->getAccessToken()];
        $arg                     = [
            'method'         => 'GET',
            'timeout'        => 15,
            'redirection'    => 5,
            'httpversion'    => '1.0',
            'blocking'       => true,
            'headers'        => $headers
        ];

        $url                     = "https://".$this->getPlatformBase()."/v1/query";
        $url                    .= "?entityId=" . $this->getEntityID();
        $url                    .= "&merchantTransactionId=" . $transactionID;
        $response                = wp_remote_request( $url, $arg );
        $this->writeLog( '----- validatePaymentTransactionID [transactionID:'.$transactionID.'] -----', ['response' => $response['body'], 'url' => $url], 'debug' );
        if( is_wp_error( $response ) ) {
            $errorMessage        = $response->get_error_message();
            wc_add_otice( __('Uncertain Response. Please report this to the merchant before reattempting payment. They will need to verify if this transaction is successful. Ref:' . $resourcePath), 'error');
            $this->writeLog( '----- validatePaymentTransactionID [response error] -----', ['url' => $url, 'trans_id' => $transactionID], 'debug' );
            return false;
        }elseif( !isset( $response['body'] ) ) {
            wc_add_notice( __('Uncertain Response. Please report this to the merchant before reattempting payment. They will need to verify if this transaction is successful. Ref:' . $resourcePath), 'error');
            $this->writeLog( '----- validatePaymentTransactionID [response empty body] -----', ['url' => $url, 'trans_id' => $transactionID], 'debug' );
            return false;
        }
        $responseResult          = $response['body'];
        $responseData            = json_decode($responseResult);
        $this->writeLog( '----- validatePaymentTransactionID [response data] -----', ['response data' => $responseData, 'url' => $url, 'trans_id' => $transactionID], 'debug' );
        $responseData            = isset($responseData->payments[0]) ? $responseData->payments[ ( count( $responseData->payments ) - 1 ) ] : new stdClass;
        if(isset($responseData->id)){
            $transaction_id                 = (string)$responseData->id;
            $this->writeLog( '----- validatePaymentTransactionID [valid transaction id found:'.$transactionID.'] -----', ['response data' => $responseData, 'url' => $url], 'debug' );
            if(isset($responseData->result->code)){
                $code                       = (string)$responseData->result->code;
                $this->writeLog( '----- validatePaymentTransactionID [valid transaction code found:'.$code.'] -----', ['response data' => $responseData, 'url' => $url], 'debug' );
                if($code == '000.000.000' || $code == '000.100.110'){
                    $this->writeLog( '----- validatePaymentTransactionID [valid transaction found:'.$code.'] -----', ['response data' => $responseData, 'url' => $url], 'debug' );
                    return true;
                }
            }
        }

        wc_add_notice( __('Uncertain Response. Please report this to the merchant before reattempting payment. They will need to verify if this transaction is successful. Transaction ID:' . $transactionID), 'error' );

        return false;
    }

    /**
     * Clear Apple Pay session data to prevent order reuse
     */
    private function clearApplePaySessionData() {
        if (WC()->session) {
            WC()->session->set('order_awaiting_payment', null);
            WC()->session->set('store_api_draft_order', null);
            
            // Clear any cart-related session data
            WC()->session->set('chosen_shipping_methods', array());
            WC()->session->set('chosen_payment_method', '');
            
            $this->writeLog('Cleared Apple Pay session data after successful payment', '', 'debug');
        }
    }
    
    public function genAddrReq($countryCode = 'GB',$type = 'billing_'){
        $countries = new WC_Countries();
        $addrFields = $countries->get_address_fields($countryCode,$type);
        $reqArray = [];
        foreach($addrFields as $field => $req){
            if($req['required'] == 1){
                $reqArray[] = $field;
                continue;
            }
        }
        return $reqArray;
    }
    
    //end applePay sheet comms
    
    public function payment_fields() {

    }
    
    public function validate_fields(){
        return true;
    }
    
    public function process_refund( $order_id, $amount = null, $reason = '') {
        global $woocommerce;
        $order         = new WC_Order($order_id);
        $order_data    = $order->get_data();
        //$amount        = $order->get_total();
        if(!empty($amount)){
            $amount    = number_format($amount, 2, '.', '');
        } else {
            $amount    = number_format($order->get_total(), 2, '.', '');;
        }
        $id            = $order->get_transaction_id();
        $platformBase  = $this->getPlatformBase();
        $entityID      = $this->getEntityID();
        $accessToken   = $this->getAccessToken();
        $paymentType   = $order->get_meta('paymentType');
        if( in_array( $paymentType, ['DB', 'CP', 'RB' ] ) ){
            $payload   = [
                'paymentType' => 'RF',
                'currency'    => $order_data['currency'],
                'amount'      => $amount
            ];
        } else if( in_array( $paymentType,['PA'] ) ){
            $payload   = [
                'paymentType' => 'RV',
                'currency'    => $order_data['currency']
            ];
        } else {
            return new WP_Error( 'Error', 'Original paymentType not recognised.' );
        }
        $payload['entityId'] = $entityID;
        $array         = [
            'method'       => 'POST',
            'timeout'      => 45,
            'redirection'  => 5,
            'httpversion'  => '1.0',
            'blocking'     => true,
	    'headers'      => [
                'Content-Type'  => 'application/x-www-form-urlencoded; charset=UTF-8',
                'Authorization' => 'Bearer ' . $accessToken,
            ],
            'body' => $payload
        ];
        $url           = 'https://' . $platformBase . '/v1/payments/' . $id;
        $response      = wp_remote_request( $url, $array );
        if( is_wp_error( $response ) ) {
            $errorMessage        = $response->get_error_message();
            $this->logError(
                "process_refund -> Error validating due to http call failure:" . $errorMessage,
                [
                    'transaction' => $id,
                    'order_id'    => $order_id,
                    'reason'      => $reason,
                ],
                $order_id,
                $id,
                null
            );
            return new WP_Error( 'Error', $errorMessage );
        }
        $result        = json_decode($response['body']);
        if(!is_object($result)){
            return new WP_Error( 'Error', 'Transaction response error.' );
        }
        if($result->result->code == '000.000.000' || $result->result->code == '000.100.110'){
            return true;
        } else {
            return new WP_Error( 'Error', 'Transaction refused: '.$result->result->description );
        }
        return new WP_Error( 'Error', 'Transaction processing error' );
    }
    
    /**
     * FIXED: Enhanced _init method
     */
    public function _init(){
        $this->update_platformbase_init();
    }
    
    // this updates platformBase to latest endpoint to avoid deprecated enpoint
    public function update_platformbase_init(){
        $oldPlatformBase     = $this->get_option( 'platformBase' );
        if( $oldPlatformBase == 'test.oppwa.com' ){
            $this->update_option( 'platformBase', 'test' );
        }
        if( $oldPlatformBase == 'oppwa.com' ){
            $this->update_option( 'platformBase', 'live' );
        }
    }

    /**
     * Process Apple Pay payment authorization and complete checkout
     */
    public function onPaymentAuthorized() {
        global $woocommerce;
        
        wc_maybe_define_constant('WOOCOMMERCE_CHECKOUT', true);
        if (!WC()->session->has_session()) {
            WC()->session->set_customer_session_cookie(true);
        }
        
        // Parse the Apple Pay payment data
        $jsonData = file_get_contents('php://input');
        $postDataArr = json_decode($jsonData, true);
        $this->writeLog('----- onPaymentAuthorized START -----', $jsonData, 'debug');
        
        // Validate input data
        if (!$postDataArr || !isset($postDataArr['payment'])) {
            wp_send_json_error([
                'status' => false,
                'message' => 'Invalid payment data received'
            ], 400);
            return;
        }
 
        $paymentData = $postDataArr['payment'];
        $checkoutID  = $postDataArr['checkout_id'] ?? '';
        $SessionID   = $postDataArr['session_id'] ?? '';
        $RequestID   = $postDataArr['request_id'] ?? '';
        $formData    = $postDataArr['form_data'] ?? [];

        try {
            // Extract Apple Pay customer data
            $billing = $paymentData['billingContact'] ?? [];
            $shipping = $paymentData['shippingContact'] ?? [];
            
            // Prepare checkout data from Apple Pay information
            $checkoutData = [];

            foreach ($formData as $key => $value) {
                $checkoutData[$key] = sanitize_text_field($value);
            }

            // Set payment method
            $checkoutData['payment_method'] = $this->id;

            // Process billing data
            if (!empty($billing)) {
                if (isset($billing['givenName']) && empty($checkoutData['billing_first_name'])) {
                    $checkoutData['billing_first_name'] = sanitize_text_field($billing['givenName']);
                }

                if (isset($billing['familyName']) && empty($formData['billing_last_name'] )) {
                    $checkoutData['billing_last_name'] = sanitize_text_field($billing['familyName']);
                }

                if (isset($billing['addressLines'][0]) && empty($checkoutData['billing_address_1'])) {
                    $checkoutData['billing_address_1'] = sanitize_text_field($billing['addressLines'][0]);
                }

                if (isset($billing['addressLines'][1]) && empty($checkoutData['billing_address_2'])) {
                    $checkoutData['billing_address_2'] = sanitize_text_field($billing['addressLines'][1]);
                }

                if (isset($billing['locality']) && empty($checkoutData['billing_city'])) {
                    $checkoutData['billing_city'] = sanitize_text_field($billing['locality']);
                }

                if (isset($billing['administrativeArea']) && empty($checkoutData['billing_state'])) {
                    $checkoutData['billing_state'] = sanitize_text_field($billing['administrativeArea']);
                }

                if (isset($billing['postalCode']) && empty($checkoutData['billing_postcode'])) {
                    $checkoutData['billing_postcode'] = sanitize_text_field($billing['postalCode']);
                }

                if (isset($billing['countryCode']) && empty($checkoutData['billing_country'])) {
                    $checkoutData['billing_country'] = strtoupper(sanitize_text_field($billing['countryCode']));
                }

                if (isset($billing['phoneNumber']) && empty($checkoutData['billing_phone'])) {
                    $checkoutData['billing_phone'] = sanitize_text_field($billing['phoneNumber']);
                }
            }

            // Process shipping data
            if (!empty($shipping)) {
                if (isset($shipping['emailAddress']) && empty($checkoutData['billing_email'])) {
                    $checkoutData['billing_email'] = sanitize_email($shipping['emailAddress']);
                }
                if (isset($shipping['phoneNumber']) && empty($checkoutData['shipping_phone'])) {
                    $checkoutData['shipping_phone'] = sanitize_text_field($shipping['phoneNumber']);
                }
                if (isset($shipping['givenName']) && empty($checkoutData['shipping_first_name'])) {
                    $checkoutData['shipping_first_name'] = sanitize_text_field($shipping['givenName']);
                }
                if (isset($shipping['familyName']) && empty($checkoutData['shipping_last_name'])) {
                    $checkoutData['shipping_last_name'] = sanitize_text_field($shipping['familyName']);
                }
                if (isset($shipping['addressLines'][0]) && empty($checkoutData['shipping_address_1'])) {
                    $checkoutData['shipping_address_1'] = sanitize_text_field($shipping['addressLines'][0]);
                }
                if (isset($shipping['addressLines'][1]) && empty($checkoutData['shipping_address_2'])) {
                    $checkoutData['shipping_address_2'] = sanitize_text_field($shipping['addressLines'][1]);
                }
                if (isset($shipping['locality']) && empty($checkoutData['shipping_city'])) {
                    $checkoutData['shipping_city'] = sanitize_text_field($shipping['locality']);
                }
                if (isset($shipping['administrativeArea']) && empty($checkoutData['shipping_state'])) {
                    $checkoutData['shipping_state'] = sanitize_text_field($shipping['administrativeArea']);
                }
                if (isset($shipping['postalCode']) && empty($checkoutData['shipping_postcode'])) {
                    $checkoutData['shipping_postcode'] = sanitize_text_field($shipping['postalCode']);
                }
                if (isset($shipping['countryCode']) && empty($checkoutData['shipping_country'])) {
                    $checkoutData['shipping_country'] = strtoupper(sanitize_text_field($shipping['countryCode']));
                }
            }

            // Use billing phone if available
            if (empty($checkoutData['billing_phone']) && isset($shipping['phoneNumber'])) {
                $checkoutData['billing_phone'] = sanitize_text_field($shipping['phoneNumber']);
            }

            if(
             \Automattic\WooCommerce\Blocks\Utils\CartCheckoutUtils::is_checkout_block_default() &&
             ( !isset( $checkoutData['woocommerce-process-checkout-nonce'] ) || empty( $checkoutData['woocommerce-process-checkout-nonce'] ) )
            ){
                $nonce    = wp_create_nonce( 'woocommerce-process_checkout' );
                $checkoutData['woocommerce-process-checkout-nonce']  = $nonce;
	    }

            if( $this->enforceShipping == 'yes' ){
	        $checkoutData['ship_to_different_address'] = 1;

                // Process shipping data
                if (!empty($shipping)) {
                    if (isset($shipping['emailAddress'])) {
                        $checkoutData['billing_email'] = sanitize_email($shipping['emailAddress']);
                    }
                    if (isset($shipping['phoneNumber'])) {
                        $checkoutData['shipping_phone'] = sanitize_text_field($shipping['phoneNumber']);
                    }
                    if (isset($shipping['givenName'])) {
                        $checkoutData['shipping_first_name'] = sanitize_text_field($shipping['givenName']);
                    }
                    if (isset($shipping['familyName'])) {
                        $checkoutData['shipping_last_name'] = sanitize_text_field($shipping['familyName']);
                    }
                    if (isset($shipping['addressLines'][0])) {
                        $checkoutData['shipping_address_1'] = sanitize_text_field($shipping['addressLines'][0]);
                    }
                    if (isset($shipping['addressLines'][1])) {
                        $checkoutData['shipping_address_2'] = sanitize_text_field($shipping['addressLines'][1]);
                    }
                    if (isset($shipping['locality'])) {
                        $checkoutData['shipping_city'] = sanitize_text_field($shipping['locality']);
                    }
                    if (isset($shipping['administrativeArea'])) {
                        $checkoutData['shipping_state'] = sanitize_text_field($shipping['administrativeArea']);
                    }
                    if (isset($shipping['postalCode'])) {
                        $checkoutData['shipping_postcode'] = sanitize_text_field($shipping['postalCode']);
                    }
                    if (isset($shipping['countryCode'])) {
                        $checkoutData['shipping_country'] = strtoupper(sanitize_text_field($shipping['countryCode']));
                    }
                }
            }

            // Set POST data for checkout process
            $_POST = $checkoutData;
            $_REQUEST = $checkoutData;
            
            // Store Apple Pay metadata in session for order creation
            WC()->session->set('applepay_checkout_id', $checkoutID);
            WC()->session->set('applepay_payment_data', $paymentData);
            
            $this->writeLog('Processing checkout with Apple Pay data', [
                'checkout_id' => $checkoutID,
                'billing_email' => $checkoutData['billing_email'] ?? 'none',
                'billing_name' => ($checkoutData['billing_first_name'] ?? '') . ' ' . ($checkoutData['billing_last_name'] ?? '')
            ], 'debug');

            //Add metabox log here
            $this->logInfo(
                "process_checkout -> Apple pay sheet data for checkoutid " . $checkoutID,
                [
                    'action' => 'capture apple pay sheet data',
                    'apple_pay_sheet_data' => $paymentData,
                    'checkout_process_data_final' => $checkoutData,
                ],
                null,
                null,
                $checkoutID
            );

            // Process the checkout
            $checkout = WC()->checkout();

            try {
                $checkout->process_checkout();
            } catch (Exception $checkout_exception) {
                //Add metabox log here
                $this->logError(
                    "process_checkouti catch 1 -> Apple pay sheet process_checkout failed for checkoutid " . $checkoutID,
                    [
                        'action' => 'capture process_checkout exception',
                        'exception' => $checkout_exception->getMessage(),
                    ],
                    null,
                    null,
                    $checkoutID
                );
                throw $checkout_exception;
            }
            
        } catch (Exception $e) {
            $this->writeLog('Apple Pay checkout processing failed: ' . $e->getMessage(), [
                'checkout_id' => $checkoutID,
                'error' => $e->getMessage()
            ], 'error');
            
            // Clear session data on error
            WC()->session->set('applepay_checkout_id', null);
            WC()->session->set('applepay_payment_data', null);

            //Add metabox log here
            $this->logError(
                "process_checkout catch 2 -> Apple pay process_checkout failed for checkoutid " . $checkoutID,
                [
                    'action' => 'capture apple pay exception',
                    'apple_pay_sheet_data' => $e->getMessage(),
                ],
                null,
                null,
                $checkoutID
            );
            
            wp_send_json_error([
                'status' => false,
                'message' => 'Checkout processing failed: ' . $e->getMessage(),
                'checkout_id' => $checkoutID
            ], 500);
        }
    }

    public function process_payment($order_id){
        WC()->session->set('np_order_merchant_id', $order_id);
        $checkoutID         = WC()->session->get('applepay_checkout_id', null);
        $order              = wc_get_order( $order_id );
        $order->add_order_note( sprintf( "Order created with checkoutid: %s, and merchant transaction id: %s", $checkoutID, $order_id ) );
        $order->update_meta_data('_applepay_checkout_id', $checkoutID);
        $order->update_meta_data('_applepay_payment_timestamp', time());
        $order->update_meta_data('_applepay_processed', 'yes');
        $order->save();

        //Add metabox log here
        $this->logInfo(
            "process_payment -> Order created with checkoutID: " . $checkoutID,
            [
                'action' => 'updating order meta',
                'checkout_id' => $checkoutID,
            ],
            $order_id,
            null,
            $checkoutID
        );

	$order_data     = $order->get_data();
	$additionalParams = [];
	$payload        = $this->prepareOrderDataForPayload( $order_data, $additionalParams );
	$responseUpdate = $this->updateTransactionData( $checkoutID, $payload );

        //Add metabox log here
        $this->logInfo(
            "process_payment -> Updated transaction data for checkoutID: " . $checkoutID,
	    [
                'action' => 'updateTransactionData',
                'payload' => $payload,
		'checkout_id' => $checkoutID,
		'response' => $responseUpdate,
            ],
            $order_id,
            null,
            $checkoutID
        );

        // CRITICAL FIX: Mark checkout ID as used BEFORE processing payment
        $this->markCheckoutIdAsUsed($checkoutID, $order->get_id());
        $order->save();

        $this->writeLog('Apple Pay checkout saved successfully', [
            'order_id' => $order->get_id(),
            'checkout_id' => $checkoutID,
        ], 'debug');

        // Return success response
        return [
            'result' => "success",
            'status' => true,
            'order_id' => $order->get_id(),
            'checkout_id' => $checkoutID,
            'message' => 'Payment processing successfully'
        ];
    }

    public function enforce_shipping_address( $enforceShippingAddress ){
        if( $this->enforceShipping == 'yes' ){
            return true;
        }

        return $enforceShippingAddress;
    }

    public function validateTransactionStatus(){
        $resourcePath    = $_REQUEST['resourcePath'] ?? null;
        $checkoutID      = WC()->session->get('applepay_checkout_id', null);
        $order_id        = WC()->session->get('np_order_merchant_id', ($_REQUEST['order_id'] ?? null));
        $this->logInfo(
            "validateTransactionStatus -> Validating Order with resource path with order_id: " . $order_id, 
            [
                'resource_path' => $resourcePath,
                'order_id' => $order_id,
            ],
            $order_id,
            null,
            $checkoutID
        );
        if( empty( $resourcePath ) ){
            wc_add_notice( __('Uncertain Response. Please report this to the merchant before reattempting payment. They will need to verify if this transaction is successful. Ref:' . $resourcePath), 'error');        
            $this->writeLog( '----- validateTransactionStatus [empty resource path] -----', ['data' => $_REQUEST], 'debug' );
            $order_id        = WC()->session->get('np_order_merchant_id', ($_REQUEST['order_id'] ?? 0));
            $this->logError(
                "validateTransactionStatus -> Empty resource path for order_id: " . $order_id,
                [
                    'resource_path' => $resourcePath,
                    'order_id' => $order_id,
                ],
                $order_id,
                null,
                $checkoutID
            );
            wp_send_json_error(['message' => 'failed'], 403);exit;
        }
        if( empty( $order_id ) ){
            wc_add_notice( __('Uncertain Response. Please report this to the merchant before reattempting payment. They will need to verify if this transaction is successful. Ref:' . $resourcePath), 'error');        
            $this->logError(
                "validateTransactionStatus -> Empty order_id",
                [
                    'resource_path' => $resourcePath,
                    'order_id' => $order_id,
                ],
                $order_id,
                null,
                $checkoutID
            );
            $this->writeLog( '----- validateTransactionStatus [order_id missing] -----', ['data' => $_REQUEST], 'debug' );;
        }
        $executionTime           = [];
        $url                     = $resourcePath;
        if( strpos( $resourcePath, 'https' ) === false ){
            $url                 = "https://" . $this->getPlatformBase() . $resourcePath;
        }
        if( strpos( $url, 'entityId' ) === false ){
            $url                .= "?entityId=".$this->getEntityID();
        }

        $headers                 = ['Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8','Authorization' => 'Bearer '.$this->getAccessToken()];
        $arg                     = [
            'method'         => 'GET',
            'timeout'        => 15,
            'redirection'    => 5,
            'httpversion'    => '1.0',
            'blocking'       => true,
            'headers'        => $headers
        ];

        $response                = wp_remote_request( $url, $arg );
        $this->writeLog( '----- validateTransactionStatus -----', ['response' => $response['body'], 'url' => $url], 'debug' );
        $secondaryCall           = false;
        $campturesResponseLog    = false;
        if( is_wp_error( $response ) ) {
            $errorMessage        = $response->get_error_message();
            $secondaryCall       = true;
            $this->logError(
                "validateTransactionStatus -> Error validating due to http call failure:" . $response->get_error_message(),
                [
                    'resource_path' => $resourcePath,
                    'order_id' => $order_id,
                ],
                $order_id,
                null,
                $checkoutID
            );

        }elseif( !isset( $response['body'] ) ) {
            $secondaryCall       = true;
            $this->logError(
                "validateTransactionStatus -> No rersponse body",
                [
                    'resource_path' => $resourcePath,
                    'order_id' => $order_id,
                    'response' => json_encode($response),
                ],
                $order_id,
                null,
                $checkoutID
            );
        }else{
            $campturesResponseLog    = true;
            $this->logInfo(
                "validateTransactionStatus -> Capturing response of validation call with resource path: " . $resourcePath,
                [
                    'resource_path' => $resourcePath,
                    'order_id' => $order_id,
                    'response' => $response['body'],
                ],
                $order_id,
                null,
                $checkoutID
            );
        }
        if( $secondaryCall === true && !empty( $order_id ) ){
            $url                 = "https://".$this->getPlatformBase()."/v1/query";
            $url                .= "?entityId=" . $this->getEntityID();
            $url                .= "&merchantTransactionId=" . $order_id;
            $response            = wp_remote_request( $url, $arg );
            $this->logInfo(
                "validateTransactionStatus -> Validating in  second attempt using /v1/query/ with oder_id:" . $order_id,
                [
                    'resource_path' => $resourcePath,
                    'order_id' => $order_id,
                ],
                $order_id,
                null,
                $checkoutID
            );
            $this->writeLog( '----- validateTransactionStatus [secondary] -----', ['response' => $response['body'], 'url' => $url, 'trans_id' => $transactionID], 'debug' );
            if( is_wp_error( $response ) ) {
                $errorMessage    = $response->get_error_message();
                $this->logError(
                    "validateTransactionStatus (secondary) -> Error validating secodary call due to http call failure:" . $response->get_error_message(),
                    [
                        'resource_path' => $resourcePath,
                        'order_id' => $order_id,
                        'secondaryCall' => $secondaryCall,
                    ],
                    $order_id,
                    null,
                    $checkoutID
                );
            }elseif( !isset( $response['body'] ) ) {
                $this->logError(
                    "validateTransactionStatus (secondary) -> No rersponse body",
                    [
                        'resource_path' => $resourcePath,
                        'order_id' => $order_id,
                        'response' => json_encode($response),
                        'secondaryCall' => $secondaryCall,
                    ],
                    $order_id,
                    null,
                    $checkoutID
                );
            }else{
                $campturesResponseLog    = true;
                $this->logInfo(
                    "validateTransactionStatus (secondary) -> Capturing response of validation call with resource path: " . $resourcePath,
                    [
                        'resource_path' => $resourcePath,
                        'order_id' => $order_id,
                        'secondaryCall' => $secondaryCall,
                        'response' => $response['body'],
                    ],
                    $order_id,
                    null,
                    $checkoutID
                );
            }
        }

        if( is_wp_error( $response ) ) {
            $errorMessage        = $response->get_error_message();
            $this->logError(
                "validateTransactionStatus (final response error check) -> Error validating due to http call failure:" . $response->get_error_message(),
                [
                    'resource_path' => $resourcePath,
                    'order_id' => $order_id,
                    'secondaryCall' => $secondaryCall,
                ],
                $order_id,
                null,
                $checkoutID
            );
            wc_add_notice( __('Uncertain Response. Please report this to the merchant before reattempting payment. They will need to verify if this transaction is successful. Ref:' . $resourcePath), 'error');
            $this->writeLog( '----- validateTransactionStatus [response error] -----', ['resourcePath' => $resourcePath, 'url' => $url, 'trans_id' => $transactionID], 'debug' );
            wp_send_json_error(['message' => 'failed'], 403);exit;
        }elseif( !isset( $response['body'] ) ) {
            $this->logError(
                "validateTransactionStatus (final response error check) -> Error validating due to http response body missing",
                [
                    'resource_path' => $resourcePath,
                    'order_id' => $order_id,
                    'response' => json_encode($response),
                    'secondaryCall' => $secondaryCall,
                ],
                $order_id,
                null,
                $checkoutID
            );
            wc_add_notice( __('Uncertain Response. Please report this to the merchant before reattempting payment. They will need to verify if this transaction is successful. Ref:' . $resourcePath), 'error');
            $this->writeLog( '----- validateTransactionStatus [response empty body] -----', ['resourcePath' => $resourcePath, 'url' => $url, 'trans_id' => $transactionID], 'debug' );
            wp_send_json_error(['message' => 'failed'], 403);exit;
        }elseif($campturesResponseLog === false){
            $this->logInfo(
                "validateTransactionStatus (final) -> Capturing response of validation call with resource path: " . $resourcePath,
                [
                    'resource_path' => $resourcePath,
                    'order_id' => $order_id,
                    'secondaryCall' => $secondaryCall,
                    'response' => $response['body'],
                ],
                $order_id,
                null,
                $checkoutID
            );
        }
        $responseResult          = $response['body'];
        $responseData            = json_decode($responseResult);
        $this->logInfo(
            "validateTransactionStatus (primary and secodary check might have passed) -> Validating response for order_id: " . $order_id,
            [
                'resource_path' => $resourcePath,
                'order_id' => $order_id,
            ],
            $order_id,
            null,
            $checkoutID
        );
        $this->writeLog( '----- validateTransactionStatus [response data1] -----', ['response data' => $responseData, 'url' => $url, 'trans_id' => $transactionID], 'debug' );
        $responseData            = ( $secondaryCall === true ) ?
                                       ( isset($responseData->payments[0]) ? $responseData->payments[ ( count( $responseData->payments ) - 1 ) ] : new stdClass) :
                                       $responseData;
        $responseData            = $this->parseResponseData($responseData);
        $this->writeLog( '----- validateTransactionStatus [response data2] -----', ['response data' => $responseData, 'url' => $url, 'trans_id' => $transactionID], 'debug' );
        wp_send_json_success($responseData);
    }

    public function parseResponseData($responseData){
        global $woocommerce;
        $checkoutID      = WC()->session->get('applepay_checkout_id', null);
        $sess_order_id   = WC()->session->get('np_order_merchant_id', null);
        $array                              = ['status' => false, 'notices'=>[]];
        $array['redirect']                  = wc_get_checkout_url();
        if(isset($responseData->id)){
            $paymentSuccess                 = false;
            $transaction_id                 = (string)$responseData->id;
            if(isset($responseData->result->code)){
                $code                       = (string)$responseData->result->code;
                if($code == '000.000.000' || $code == '000.100.110'){
                    $paymentSuccess         = true;
                }else{
                    $this->logError(
                        "parseResponseData -> Parsing response data code is not success code for order_id: " . $sess_order_id,
                        [
                            'order_id' => $sess_order_id,
                            'responsecode' => $code,
                            'responseDesc' => str_replace("'", "" , $responseData->result->description),
                        ],
                        $sess_order_id,
                        $transaction_id,
                        $checkoutID
                    );
                }
            }
            if(isset($responseData->result->description)){
                $description                = str_replace("'", "" , $responseData->result->description);
            }
            if(isset($responseData->merchantTransactionId)){
                $checks                     = true;
                $order_id                   = trim($responseData->merchantTransactionId);
                $this->logInfo(
                    "parseResponseData -> Parsing response recording real gateway mercahnt transaction id which should be order_id: " . $order_id,
                    [
                        'order_id' => $order_id,
                        'amount'   => $responseData->amount,
                        'timestamp' => $responseData->timestamp,
                    ],
                    $sess_order_id,
                    $transaction_id,
                    $checkoutID
                );
                $order                      = wc_get_order($order_id);
                if($order){
                    $amount                     = number_format($order->get_total(), 2, '.', '');
                    $order_data                 = $order->get_data();
                    if($paymentSuccess === true){
                        //good to go..
                        $order->payment_complete($transaction_id);
                        wc_reduce_stock_levels($order_id);
                        $order->add_order_note( 'Your order is paid! Thank you!', true );
                        $order->add_order_note( sprintf( 'Apple Pay payment completed successfully. Checkout ID: %s, Transaction ID: %s', $checkoutID, $transaction_id ) );
                        $order->add_order_note( $code, false );
                        $order->add_meta_data('platformBase', $this->platformBase);
                        $order->add_meta_data('paymentType', (string)$responseData->paymentType);
                        $order->save();
                        $woocommerce->cart->empty_cart();
                        
                        $this->logInfo(
                            "parseResponseData -> Parsing response recording order amount and gatway amount for order_id: " . $order_id,
                            [
                                'order_id' => $order_id,
                                'amount'   => $responseData->amount,
                                'orderAmount' => $order->get_total(),
                                'timestamp' => $responseData->timestamp,
                            ],
                            $sess_order_id,
                            $transaction_id,
                            $checkoutID
                        );

                        // Clear Apple Pay session data to prevent reuse
                        $this->clearApplePaySessionData();

                        $array['status']    = true;
                        $array['valid']     = true;
                        $array['redirect']  = $this->get_return_url( $order );
                    } else {
                        $order->add_order_note( $code, false );
                        $order->save();
                        //decline reason..
                        $array['notices'][] = 'Payment not completed: '.$description;
                        $array['error']     = $description;

                        $this->logError(
                            "parseResponseData -> Parsing response success failed for order_id: " . $order_id,
                            [
                                'order_id' => $order_id,
                                'code'     => $code,
                                'amount'   => $responseData->amount,
                                'orderAmount' => $order->get_total(),
                                'description' => $description,
                                'timestamp' => $responseData->timestamp,
                            ],
                            $sess_order_id,
                            $transaction_id,
                            $checkoutID
                        );
                    }
                }else{
                    $this->logError(
                        "parseResponseData -> Parsing response success failed for order_id: " . $sess_order_id,
                        [
                            'order_id' => $order_id,
                            'code'     => $code,
                            'description' => $description,
                            'timestamp' => $responseData->timestamp,
                        ],
                        $sess_order_id,
                        $transaction_id,
                        $checkoutID
                    );
                }
            } else {
                $this->logError(
                    "parseResponseData -> Parsing response data order not foundfor order_id: " . $sess_order_id,
                    [
                        'order_id' => $sess_order_id,
                        'responsecode' => $code,
                        'responseDesc' => str_replace("'", "" , $responseData->result->description),
                    ],
                    $sess_order_id,
                    $transaction_id,
                    $checkoutID
                );
                $array['notices'][]         = 'No order_id found, please retry payment.';
                //perform reversal on $paymentSuccess && $responseData->id
            }
        } else {
            $this->logError(
                "parseResponseData -> Parsing response data no transaction id for order_id: " . $sess_order_id,
                [
                    'order_id' => $sess_order_id,
                    'responsecode' => $code,
                ],
                $sess_order_id,
                $transaction_id,
                $checkoutID
            );
            $array['notices'][]             = 'No transaction id found, please retry payment.';
        }
        wc_clear_notices();
        foreach($array['notices'] as $notice){
            wc_add_notice( __($notice), 'error');
        }
        return $array;
    }

    /**
     * CRITICAL FIX: Mark checkout ID as permanently used
     */
    private function markCheckoutIdAsUsed($checkout_id, $order_id) {
        // Store in both transient and option for redundancy
        set_transient('checkout_used_' . $checkout_id, $order_id, 86400); // 24 hours
        update_option('checkout_used_' . $checkout_id, $order_id);
        
        $this->writeLog('Checkout ID marked as used', [
            'checkout_id' => $checkout_id,
            'order_id' => $order_id
        ], 'debug');
    }

    /**
     * NEW METHOD: Comprehensive cache clearing for same cart content
     */
    private function clearAllApplePayCachesForCart($cart_hash, $checkout_id, $order = null) {
        try {
            $this->writeLog('Clearing comprehensive Apple Pay caches for cart: ' . $cart_hash, '', 'debug');
            
            $user_id = get_current_user_id();
            $session_id = WC()->session ? WC()->session->get_customer_id() : '';
            $customer_ip = $this->getCustomerIP();
            
            // 1. Clear idempotency-based caches for current and future time windows
            $current_window = floor(time() / 120) * 120;
            for ($i = 0; $i <= 5; $i++) { // Clear current + 5 future windows (10 minutes)
                $window_time = $current_window + ($i * 120);
                $context = [
                    'cart_hash' => $cart_hash,
                    'user_id' => $user_id,
                    'session_id' => $session_id,
                    'ip' => $customer_ip,
                    'timestamp' => $window_time,
                    'currency' => get_woocommerce_currency(),
                    'platform' => $this->platformBase
                ];
                $cache_key = 'applepay_checkout_' . hash('md5', json_encode($context));
                delete_transient($cache_key);
            }
            
            // 2. Clear checkout ID specific transients
            delete_transient('tp_applepay_checkout_' . $checkout_id);
            delete_transient('checkout_' . $checkout_id);
            
            // 3. Clear cart-hash specific transients
            delete_transient('applepay_cart_' . $cart_hash);
            
            // 4. Clear order creation duplicate prevention keys
            $unique_contexts = $this->generateUniqueContextVariations($cart_hash, $user_id, $session_id, $customer_ip);
            foreach ($unique_contexts as $context) {
                $duplicate_key = 'applepay_order_' . hash('sha256', json_encode($context));
                delete_transient($duplicate_key);
            }
            
            // 5. Clear session-specific data
            if (WC()->session) {
                WC()->session->set('tp_applepay_checkout_id', null);
                WC()->session->set('tp_applepay_cart_hash', null);
                
                // Clear any other session keys that might interfere
                WC()->session->set('order_awaiting_payment', null);
                WC()->session->set('store_api_draft_order', null);
            }
            
            // 6. Mark checkout ID as permanently used if order exists
            if ($order) {
                $this->storeCheckoutIdWithOrder($order->get_id(), $checkout_id);
            }
            
            // 7. Clear request throttling keys
            $request_key = 'applepay_request_' . $session_id;
            delete_transient($request_key);
            
            $this->writeLog('Comprehensive Apple Pay cache clearing completed', [
                'cart_hash' => $cart_hash,
                'checkout_id' => $checkout_id,
                'order_id' => $order ? $order->get_id() : 'none'
            ], 'debug');
            
        } catch (Exception $e) {
            $this->writeLog('Error during comprehensive cache clearing: ' . $e->getMessage(), '', 'error');
        }
    }

    /**
     * Generate context variations for thorough cache clearing
     */
    private function generateUniqueContextVariations($cart_hash, $user_id, $session_id, $customer_ip) {
        $base_context = [
            'cart_hash' => $cart_hash,
            'user_id' => $user_id,
            'session_id' => $session_id,
            'ip' => $customer_ip,
            'currency' => get_woocommerce_currency(),
            'platform' => $this->platformBase
        ];
        
        $variations = [];
        
        // Current time and nearby time windows
        $current_time = time();
        $current_window = floor($current_time / 60) * 60;
        
        for ($i = 0; $i <= 10; $i++) { // Check 10 minutes worth
            $window_time = $current_window + ($i * 60);
            $context = array_merge($base_context, ['timestamp' => $window_time]);
            $variations[] = $context;
        }
        
        return $variations;
    }

    /**
     * Hook into WooCommerce events to reset session appropriately
     */
    public function attachSessionResetHooks() {
        // Reset on checkout page load
        add_action('woocommerce_before_checkout_form', array($this, 'initializeApplePaySession'));
        add_action('woocommerce_before_cart', array($this, 'initializeApplePaySession'));
        
        // Reset on order completion
        add_action('woocommerce_order_status_completed', array($this, 'onOrderCompleted'));
        add_action('woocommerce_order_status_processing', array($this, 'onOrderCompleted'));
        add_action('woocommerce_order_status_failed', array($this, 'onOrderCompleted'));
        add_action('woocommerce_order_status_cancelled', array($this, 'onOrderCompleted'));
    }
    
    /**
     * Handle order completion events
     */
    public function onOrderCompleted($order_id) {
        try {
            $order = wc_get_order($order_id);
            if (!$order) {
                return;
            }
            
            // Check if this was an Apple Pay order
            if ($order->get_payment_method() === $this->id) {
                $checkout_id = $order->get_meta('_applepay_checkout_id');
                $cart_hash = $order->get_meta('_applepay_cart_hash');
                
                if ($checkout_id) {
                    // Clear all caches for this completed order
                    $this->clearAllApplePayCachesForCart($cart_hash, $checkout_id, $order);
                    
                    $this->writeLog('Cleared Apple Pay caches for completed order: ' . $order_id, '', 'debug');
                }
            }
            
        } catch (Exception $e) {
            $this->writeLog('Error handling order completion: ' . $e->getMessage(), '', 'error');
        }
    }
} //end class
