<?php

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

class AIEO_Session_Correlation_Helper {

    
    private static $instance = null;

    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    
    public function get_current_session_id() {
        return isset($_COOKIE['aieo_session_id']) ? sanitize_text_field(wp_unslash( $_COOKIE['aieo_session_id'] )) : null;
    }

    
    public function get_complete_session_context($session_id, $time_window = 30) {
        if (empty($session_id)) {
            return array(
                'error' => 'No session ID provided',
                'browsing' => array(),
                'chat' => array()
            );
        }

        
        $browsing_context = array();
        if (class_exists('AIEO_Session_Tracker')) {
            $tracker = AIEO_Session_Tracker::get_instance();
            $browsing_context = $tracker->parse_session_data($session_id, $time_window);
        }

        
        $chat_history = $this->get_chat_history_for_session($session_id, $time_window);

        return array(
            'session_id' => $session_id,
            'browsing' => $browsing_context,
            'chat' => $chat_history,
            'summary' => $this->generate_session_summary($browsing_context, $chat_history)
        );
    }

    
    public function get_chat_history_for_session($session_id, $time_window = 30) {
        global $wpdb;
        $table = $wpdb->prefix . 'aieo_chat_history';

        $cutoff_time = gmdate('Y-m-d H:i:s', strtotime("-{$time_window} minutes"));

        $messages = $wpdb->get_results($wpdb->prepare(
            "SELECT
                id,
                conversation_id,
                user_message,
                assistant_message,
                model_used,
                products_found,
                created_at
            FROM {$table}
            WHERE session_id = %s
            AND created_at > %s
            ORDER BY created_at DESC",
            $session_id,
            $cutoff_time
        ));

        
        foreach ($messages as $message) {
            if (!empty($message->products_found)) {
                $message->products_found = json_decode($message->products_found, true);
            }
        }

        return $messages;
    }

    
    public function user_used_chat($session_id) {
        global $wpdb;
        $table = $wpdb->prefix . 'aieo_chat_history';

        $count = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$table} WHERE session_id = %s",
            $session_id
        ));

        return (int)$count > 0;
    }

    
    public function get_products_viewed_before_chat($session_id, $conversation_id = null) {
        global $wpdb;
        $sessions_table = $wpdb->prefix . 'aieo_sessions';
        $chat_table = $wpdb->prefix . 'aieo_chat_history';

        
        
        
        $first_chat_time = $wpdb->get_var($wpdb->prepare(
            "SELECT MIN(created_at) FROM {$chat_table}
             WHERE session_id = %s" . ($conversation_id ? " AND conversation_id = %s" : ""),
            $conversation_id ? array($session_id, $conversation_id) : array($session_id)
        ));
        

        if (!$first_chat_time) {
            return array();
        }

        
        $products = $wpdb->get_results($wpdb->prepare(
            "SELECT
                event_data,
                page_url,
                created_at
            FROM {$sessions_table}
            WHERE session_id = %s
            AND event_type = 'product_view'
            AND created_at < %s
            ORDER BY created_at DESC",
            $session_id,
            $first_chat_time
        ));

        
        $parsed_products = array();
        foreach ($products as $product) {
            $data = json_decode($product->event_data, true);
            if ($data) {
                $parsed_products[] = array(
                    'product_id' => $data['product_id'] ?? null,
                    'product_name' => $data['product_name'] ?? '',
                    'page_url' => $product->page_url,
                    'viewed_at' => $product->created_at
                );
            }
        }

        return $parsed_products;
    }

    
    public function get_session_timeline($session_id, $time_window = 60) {
        global $wpdb;
        $sessions_table = $wpdb->prefix . 'aieo_sessions';
        $chat_table = $wpdb->prefix . 'aieo_chat_history';

        $cutoff_time = gmdate('Y-m-d H:i:s', strtotime("-{$time_window} minutes"));

        
        $browsing_events = $wpdb->get_results($wpdb->prepare(
            "SELECT
                'browsing' as event_category,
                event_type,
                event_data,
                page_url,
                created_at as timestamp
            FROM {$sessions_table}
            WHERE session_id = %s
            AND created_at > %s",
            $session_id,
            $cutoff_time
        ));

        
        
        $chat_events = $wpdb->get_results($wpdb->prepare(
            "SELECT
                'chat' as event_category,
                'chat_message' as event_type,
                CONCAT('{\"user\":\"', LEFT(user_message, 100), '\",\"assistant\":\"', LEFT(assistant_message, 100), '\"}') as event_data,
                NULL as page_url,
                created_at as timestamp
            FROM {$chat_table}
            WHERE session_id = %s
            AND created_at > %s",
            $session_id,
            $cutoff_time
        ));

        
        $timeline = array_merge($browsing_events, $chat_events);
        usort($timeline, function($a, $b) {
            return strtotime($a->timestamp) - strtotime($b->timestamp);
        });

        return $timeline;
    }

    
    public function get_chat_impact_analytics($days = 7) {
        global $wpdb;
        $sessions_table = $wpdb->prefix . 'aieo_sessions';
        $chat_table = $wpdb->prefix . 'aieo_chat_history';

        $cutoff_date = gmdate('Y-m-d H:i:s', strtotime("-{$days} days"));

        $results = $wpdb->get_results($wpdb->prepare(
            "SELECT
                CASE WHEN ch.session_id IS NOT NULL THEN 'with_chat' ELSE 'no_chat' END as session_type,
                COUNT(DISTINCT s.session_id) as total_sessions,
                COUNT(DISTINCT CASE WHEN s.event_type = 'product_view' THEN s.session_id END) as sessions_with_product_views,
                COUNT(DISTINCT CASE WHEN s.event_type = 'add_to_cart' THEN s.session_id END) as sessions_with_cart,
                COUNT(CASE WHEN s.event_type = 'add_to_cart' THEN 1 END) as total_cart_additions,
                AVG(CASE WHEN s.event_type = 'product_view' THEN 1 ELSE 0 END) as avg_product_views
            FROM {$sessions_table} s
            LEFT JOIN {$chat_table} ch ON s.session_id = ch.session_id
            WHERE s.created_at > %s
            GROUP BY session_type",
            $cutoff_date
        ));

        
        $analytics = array(
            'with_chat' => null,
            'no_chat' => null,
            'comparison' => array()
        );

        foreach ($results as $row) {
            $data = array(
                'total_sessions' => (int)$row->total_sessions,
                'sessions_with_product_views' => (int)$row->sessions_with_product_views,
                'sessions_with_cart' => (int)$row->sessions_with_cart,
                'total_cart_additions' => (int)$row->total_cart_additions,
                'cart_conversion_rate' => $row->total_sessions > 0 ? round(100 * $row->sessions_with_cart / $row->total_sessions, 2) : 0
            );

            $analytics[$row->session_type] = $data;
        }

        
        if ($analytics['with_chat'] && $analytics['no_chat']) {
            $analytics['comparison'] = array(
                'chat_sessions_convert_better_by' => round(
                    $analytics['with_chat']['cart_conversion_rate'] - $analytics['no_chat']['cart_conversion_rate'],
                    2
                ),
                'improvement_percentage' => $analytics['no_chat']['cart_conversion_rate'] > 0 ?
                    round(100 * ($analytics['with_chat']['cart_conversion_rate'] - $analytics['no_chat']['cart_conversion_rate']) / $analytics['no_chat']['cart_conversion_rate'], 2) : 0
            );
        }

        return $analytics;
    }

    
    private function generate_session_summary($browsing_context, $chat_history) {
        $summary = array();

        
        if (!empty($browsing_context['viewed_products'])) {
            $summary[] = sprintf(
                "Viewed %d products",
                count($browsing_context['viewed_products'])
            );
        }

        if (!empty($browsing_context['cart_additions'])) {
            $summary[] = sprintf(
                "Added %d items to cart",
                count($browsing_context['cart_additions'])
            );
        }

        if (!empty($browsing_context['engagement_score'])) {
            $summary[] = sprintf(
                "Engagement score: %d/100",
                $browsing_context['engagement_score']
            );
        }

        
        if (!empty($chat_history)) {
            $summary[] = sprintf(
                "Sent %d chat messages",
                count($chat_history)
            );
        }

        return implode(' | ', $summary);
    }

    
    public function get_session_id_from_conversation($conversation_id) {
        global $wpdb;
        $table = $wpdb->prefix . 'aieo_chat_history';

        return $wpdb->get_var($wpdb->prepare(
            "SELECT session_id FROM {$table} WHERE conversation_id = %s LIMIT 1",
            $conversation_id
        ));
    }

    
    public function debug_check_correlation() {
        $session_id = $this->get_current_session_id();

        $debug = array(
            'session_tracking_enabled' => get_option('aieo_session_tracking_enabled', '1') === '1',
            'current_session_id' => $session_id,
            'session_id_format_correct' => $session_id ? (strpos($session_id, 'session_') === 0) : false,
            'cookie_exists' => isset($_COOKIE['aieo_session_id']),
        );

        if ($session_id) {
            global $wpdb;

            
            $sessions_table = $wpdb->prefix . 'aieo_sessions';
            $chat_table = $wpdb->prefix . 'aieo_chat_history';

            $debug['exists_in_sessions_table'] = (bool)$wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM {$sessions_table} WHERE session_id = %s",
                $session_id
            ));

            $debug['exists_in_chat_table'] = (bool)$wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM {$chat_table} WHERE session_id = %s",
                $session_id
            ));

            $debug['correlation_working'] = $debug['exists_in_sessions_table'] && $debug['exists_in_chat_table'];
        }

        return $debug;
    }
}
