<?php
/**
 * Session Management Trait for Apple Pay Gateway
 * Handles order locking, session validation, and duplicate prevention
 */

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

trait TotalProcessingApplePaySessionManagerTrait {
    /**
     * Store checkout ID with order
     */
    private function storeCheckoutIdWithOrder($order_id, $checkout_id) {
        try {
            // Check if HPOS is enabled
            if (class_exists('\Automattic\WooCommerce\Utilities\OrderUtil') &&
                \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled()) {
                $order = wc_get_order($order_id);
                
                if (!$order) {
                    $this->writeLog('Order not found when storing checkout ID: ' . $order_id, '', 'error');
                    return false;
                }
                
                // Use WooCommerce order meta methods (HPOS compatible)
                $order->update_meta_data('_applepay_checkout_id', $checkout_id);
                $order->update_meta_data('_applepay_checkout_timestamp', time());
                $order->save();
                
                $this->writeLog('Checkout ID stored with order: ' . $order_id . ' -> ' . $checkout_id, '', 'debug');
            } else {
                update_post_meta($order_id, '_applepay_checkout_id', $checkout_id);
                update_post_meta($order_id, '_applepay_checkout_timestamp', time());
            }
            
            return true;
            
        } catch (Exception $e) {
            $this->writeLog('Error storing checkout ID: ' . $e->getMessage(), '', 'error');
            return false;
        }
    }
    
    /**
     * Get customer IP address safely
     * @return string
     */
    private function getCustomerIP() {
        $ip_keys = ['HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'HTTP_CLIENT_IP', 'REMOTE_ADDR'];
        
        foreach ($ip_keys as $key) {
            if (!empty($_SERVER[$key])) {
                $ip = $_SERVER[$key];
                // Handle comma-separated IPs (proxies)
                if (strpos($ip, ',') !== false) {
                    $ip = trim(explode(',', $ip)[0]);
                }
                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                    return $ip;
                }
            }
        }
        
        // Fallback to local IP
        return $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    }

    /**
     * FIXED: Add automated cleanup scheduled task
     */
    public function scheduleCleanupTask() {
        if (!wp_next_scheduled('tp_applepay_cleanup_stale_data')) {
            wp_schedule_event(time(), 'hourly', 'tp_applepay_cleanup_stale_data');
        }
    }
    
    /**
     * CRITICAL FIX: Enhanced cleanup task to remove stale cart data
     */
    public function cleanupStaleData() {
        global $wpdb;
        
        try {
            // Clean up old cart preservation transients
            $wpdb->query("
                DELETE FROM {$wpdb->options}
                WHERE option_name LIKE '_transient_applepay_cart_%'
                AND CAST(SUBSTRING_INDEX(option_value, 's:9:\"timestamp\";i:', -1) AS UNSIGNED) < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 2 HOUR))
            ");
            
            // Clean up old checkout transients
            $wpdb->query("
                DELETE FROM {$wpdb->options}
                WHERE option_name LIKE '_transient_checkout_%'
                AND CAST(option_value AS UNSIGNED) < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 2 HOUR))
            ");
            
            // Clean up old processing locks
            $wpdb->query("
                DELETE FROM {$wpdb->options}
                WHERE option_name LIKE '_transient_applepay_processing_%'
                AND CAST(option_value AS UNSIGNED) < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 HOUR))
            ");
            
            // Clean up atomic locks
            $wpdb->query("
                DELETE FROM {$wpdb->options}
                WHERE option_name LIKE 'applepay_atomic_%'
                AND CAST(option_value AS UNSIGNED) < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 HOUR))
            ");
            
            $this->writeLog('Enhanced cleanup completed', '', 'debug');
            
        } catch (Exception $e) {
            $this->writeLog('Error during enhanced cleanup: ' . $e->getMessage(), '', 'error');
        }
    }

    /**
     * Reset Apple Pay session data when starting a new order attempt
     */
    public function resetApplePaySession() {
        if (!WC()->session) {
            return;
        }
        
        try {
            // Clear page-specific session data
            WC()->session->set('applepay_page_load_time', time());
            WC()->session->set('applepay_checkout_id', null);
            WC()->session->set('applepay_cart_hash', null);
            WC()->session->set('applepay_checkout_timestamp', null);
            
            // Clear any stale order references
            $existing_order_id = WC()->session->get('order_awaiting_payment');
            if ($existing_order_id) {
                $order = wc_get_order($existing_order_id);
                if ($order) {
                    $order_age = time() - $order->get_date_created()->getTimestamp();
                    if ($order_age > 1800) { // 30 minutes old
                        WC()->session->set('order_awaiting_payment', null);
                        WC()->session->set('store_api_draft_order', null);
                    }
                }
            }
            
            $this->writeLog('Apple Pay session reset completed', '', 'debug');
            
        } catch (Exception $e) {
            $this->writeLog('Error resetting Apple Pay session: ' . $e->getMessage(), '', 'error');
        }
    }

    /**
     * Initialize Apple Pay session for new page load
     */
    public function initializeApplePaySession() {
        if (!WC()->session) {
            return;
        }
        
        try {
            // Check if this is a new page load
            $last_page_load = WC()->session->get('applepay_page_load_time');
            $current_time = time();
            
            // If more than 5 minutes since last page load, reset session
            if (!$last_page_load || ($current_time - $last_page_load) > 300) {
                $this->resetApplePaySession();
            }
            
            // Set current page load time
            WC()->session->set('applepay_page_load_time', $current_time);
            
            // Generate new page session ID
            $page_session_id = hash('md5', $current_time . wp_generate_password(12, false));
            WC()->session->set('applepay_page_session_id', $page_session_id);
            
            $this->writeLog('Apple Pay session initialized', [
                'page_session_id' => $page_session_id,
                'page_load_time' => $current_time
            ], 'debug');
            
        } catch (Exception $e) {
            $this->writeLog('Error initializing Apple Pay session: ' . $e->getMessage(), '', 'error');
        }
    }
}
