<?php
if ( ! defined( 'ABSPATH' ) ) exit;

class Dori_Chatbot_WooCommerce_Session {

    public static function init() {
        add_action('wp_ajax_dori_store_thread_session', array(__CLASS__, 'store_thread_session'));
        add_action('wp_ajax_nopriv_dori_store_thread_session', array(__CLASS__, 'store_thread_session'));
    }

    public static function get_thread_from_session() {
        $session_data = Dori_Chatbot_Cache_Manager::get_woocommerce_session();

        if ($session_data && isset($session_data['session_data']['dori_thread_id'])) {
            $thread_id = $session_data['session_data']['dori_thread_id'];
            if ($thread_id) {
                return sanitize_text_field($thread_id);
            }
        }

        if (isset($_SERVER['HTTP_X_DORI_THREAD_ID'])) {
            return sanitize_text_field($_SERVER['HTTP_X_DORI_THREAD_ID']);
        }

        return null;
    }

    public static function get_session_key(): ?string {
        // Try cookie first (most reliable for Store API checkout)
        if (isset($_COOKIE['dori_session_key'])) {
            $cookie_session_key = $_COOKIE['dori_session_key'];
            if (strpos($cookie_session_key, 'dori_session_') === 0) {
                return sanitize_text_field($cookie_session_key);
            }
        }

        // Try WC session from cache
        $session_data = Dori_Chatbot_Cache_Manager::get_woocommerce_session();
        if ($session_data && isset($session_data['session_data']['dori_session_key'])) {
            $session_key = $session_data['session_data']['dori_session_key'];
            if ($session_key) {
                return sanitize_text_field($session_key);
            }
        }

        // Try direct WC session access
        if (function_exists('WC') && WC()->session) {
            $wc_session_key = WC()->session->get('dori_session_key');
            if ($wc_session_key) {
                return sanitize_text_field($wc_session_key);
            }
        }

        // Fallback: Try HTTP header
        if (isset($_SERVER['HTTP_X_DORI_SESSION_KEY'])) {
            return sanitize_text_field($_SERVER['HTTP_X_DORI_SESSION_KEY']);
        }

        return null;
    }

    public static function store_thread_session() {
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'dori_thread_session')) {
            wp_die('Security check failed', 'Error', array('response' => 403));
        }

        $thread_id = isset($_POST['thread_id']) ? sanitize_text_field($_POST['thread_id']) : '';
        $session_key = isset($_POST['session_key']) ? sanitize_text_field($_POST['session_key']) : '';

        $wc_exists = function_exists('WC');
        $wc_session_available = $wc_exists && WC()->session;

        if ($thread_id && $wc_exists && $wc_session_available) {
            WC()->session->set('dori_thread_id', $thread_id);

            if ($session_key) {
                WC()->session->set('dori_session_key', $session_key);
            }

            if (is_user_logged_in()) {
                $user_id = get_current_user_id();
                update_user_meta($user_id, 'dori_current_thread_id', $thread_id);
                if ($session_key) {
                    update_user_meta($user_id, 'dori_session_key', $session_key);
                }
            }

            wp_send_json_success('Thread ID and session key stored successfully');
        } else {
            $error_details = array();
            if (!$thread_id) $error_details[] = 'thread_id is empty';
            if (!$wc_exists) $error_details[] = 'WC() function not available';
            if (!$wc_session_available) $error_details[] = 'WC()->session is NULL';

            $error_msg = 'Failed to store thread ID: ' . implode(', ', $error_details);

            wp_send_json_error($error_msg);
        }
    }
}
