<?php

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

/**
 * Handles all AJAX requests for the plugin.
 *
 * @since      1.6.5
 */
class NewCodeByte_Chatbot_Ajax {

    /**
     * Sanitizes a string for CSV export to prevent formula injection.
     *
     * @param string $string The string to sanitize.
     * @return string The sanitized string.
     */
    private function sanitize_for_csv($string) {
        $string = (string) $string;
        $dangerous_chars = ['=', '+', '-', '@'];
        
        // If the string starts with a dangerous character, prepend a tab.
        if (in_array(substr(ltrim($string), 0, 1), $dangerous_chars, true)) {
            $string = "\t" . $string;
        }
        
        // Also, escape double quotes.
        return str_replace('"', '""', $string);
    }

    /**
     * Register the AJAX hooks.
     *
     * @since    1.6.5
     */
    public function add_hooks() {
        add_action('wp_ajax_newcodebyte_chatbot_send_message', [$this, 'send_message']);
        add_action('wp_ajax_nopriv_newcodebyte_chatbot_send_message', [$this, 'send_message']);
        add_action('wp_ajax_newcodebyte_chatbot_delete_messages', [$this, 'delete_messages']);
        add_action('wp_ajax_newcodebyte_chatbot_export_messages', [$this, 'export_messages']);
        add_action('wp_ajax_newcodebyte_chatbot_get_conversation_messages', [$this, 'get_conversation_messages']);
        add_action('wp_ajax_newcodebyte_chatbot_mark_as_read', [$this, 'mark_as_read']);
    }

    /**
     * Handle the user message submission.
     *
     * @since    1.6.5
     */
    public function send_message() {
        // Non abbiamo più bisogno di gestire la sessione PHP qui.

        if (!isset($_POST['newcodebyte_chatbot_message_nonce']) || !wp_verify_nonce(sanitize_text_field($_POST['newcodebyte_chatbot_message_nonce']), 'newcodebyte_chatbot_send_message')) {
            wp_send_json_error(['message' => __('Security check failed.', NCB_CHATBOT_TEXT_DOMAIN)], 403);
            return;
        }
        if (!isset($_POST['message']) || trim($_POST['message']) === '') {
            wp_send_json_error(['message' => 'Message is required.'], 400);
            return;
        }

        global $wpdb;
        $message = sanitize_text_field($_POST['message']);
        $conversation_id = isset($_POST['conversation_id']) ? absint($_POST['conversation_id']) : 0;

        // La logica per creare una nuova conversazione se l'ID è 0 rimane invariata.
        if (empty($conversation_id)) {
            $conversations_table = $wpdb->prefix . 'newcodebyte_chatbot_conversations';
            $insert_result = $wpdb->insert($conversations_table, ['start_date' => current_time('mysql')], ['%s']);
            if ($insert_result === false) {
                wp_send_json_error(['message' => 'Database Error: Could not create a new conversation.'], 500);
                return;
            }
            $conversation_id = $wpdb->insert_id;
        }

        // Recupera la cronologia inviata dal JavaScript.
        $history_json = isset($_POST['history']) ? stripslashes($_POST['history']) : '[]';
        $conversation_history = json_decode($history_json, true);

        // Controllo di sicurezza: se la decodifica fallisce o non è un array, lo resettiamo.
        if (!is_array($conversation_history)) {
            $conversation_history = [];
        }

        $user_name = isset($_POST['name']) ? sanitize_text_field($_POST['name']) : null;
        $user_email = isset($_POST['email']) ? sanitize_email($_POST['email']) : null;
        $is_first_message = isset($_POST['is_first_message']) && $_POST['is_first_message'] === '1';

        $ip = filter_var($_SERVER['REMOTE_ADDR'] ?? '0.0.0.0', FILTER_VALIDATE_IP) ?: '0.0.0.0';

        // La logica per salvare il messaggio dell'utente nel database rimane invariata.
        $save_messages = get_option('newcodebyte_chatbot_save_messages', '0');
        if ($save_messages === '1') {
            $messages_table = $wpdb->prefix . 'newcodebyte_chatbot_messages';
            $wpdb->insert($messages_table, [
                'ip' => $ip, 'date' => current_time('mysql'), 'sender' => 'User',
                'message' => $message, 'conversation_id' => $conversation_id,
                'user_name' => $is_first_message ? $user_name : null, 'user_email' => $is_first_message ? $user_email : null,
            ], ['%s', '%s', '%s', '%s', '%d', '%s', '%s']);
            delete_transient('newcodebyte_chatbot_unread_count');
        }

        // Chiama la classe API, passando la cronologia ricevuta dal client.
        $api = new NewCodeByte_Chatbot_Api();
        $bot_response = $api->generate_response($message, $conversation_history, $user_name);

        // La logica per salvare la risposta del bot nel database rimane invariata.
        if (strpos($bot_response, 'API Error:') === false) {
            if ($save_messages === '1') {
                $messages_table = $wpdb->prefix . 'newcodebyte_chatbot_messages';
                $wpdb->insert($messages_table, [
                    'date' => current_time('mysql'), 'sender' => 'Bot', 'message' => $bot_response, 'conversation_id' => $conversation_id
                ], ['%s', '%s', '%s', '%d']);
            }
        }

        // Invia la risposta al client. Non abbiamo più bisogno di gestire $_SESSION.
        wp_send_json_success(['message' => $bot_response, 'conversation_id' => $conversation_id]);
    }

    /**
     * Handle deleting all messages.
     *
     * @since    1.6.5
     */
    public function delete_messages() {
        if (!current_user_can('manage_options') || !check_ajax_referer('newcodebyte_chatbot_delete_messages', 'chatbot_delete_nonce', false)) {
            wp_send_json_error(['message' => __('Security check failed.', NCB_CHATBOT_TEXT_DOMAIN)]);
            return;
        }
        global $wpdb;
        $messages_table = $wpdb->prefix . 'newcodebyte_chatbot_messages';
        $conversations_table = $wpdb->prefix . 'newcodebyte_chatbot_conversations';
        $wpdb->query("TRUNCATE TABLE $messages_table");
        $wpdb->query("TRUNCATE TABLE $conversations_table");
        delete_transient('newcodebyte_chatbot_unread_count');
        wp_send_json_success(['message' => __('All messages have been deleted.', NCB_CHATBOT_TEXT_DOMAIN)]);
    }

    /**
     * Handle exporting messages.
     *
     * @since    1.6.5
     */
    public function export_messages() {
        if (!current_user_can('manage_options') || !check_ajax_referer('newcodebyte_chatbot_export_messages', 'chatbot_export_nonce', false)) {
            wp_die(__('Security check failed.', NCB_CHATBOT_TEXT_DOMAIN));
        }

        $format = isset($_POST['format']) ? sanitize_text_field($_POST['format']) : 'txt';
        $allowed_formats = ['txt', 'csv', 'md', 'html'];
        if (!in_array($format, $allowed_formats)) {
            $format = 'txt';
        }

        global $wpdb;
        $messages_table = $wpdb->prefix . 'newcodebyte_chatbot_messages';
        $conversations_table = $wpdb->prefix . 'newcodebyte_chatbot_conversations';

        $all_messages_query = "
            SELECT 
                conv.id as conversation_id, conv.start_date,
                msg.sender, msg.message, msg.date as message_date, msg.ip,
                (SELECT um.user_name FROM $messages_table um WHERE um.conversation_id = conv.id AND um.user_name IS NOT NULL AND um.user_name != '' ORDER BY um.id ASC LIMIT 1) as user_name,
                (SELECT ue.user_email FROM $messages_table ue WHERE ue.conversation_id = conv.id AND ue.user_email IS NOT NULL AND ue.user_email != '' ORDER BY ue.id ASC LIMIT 1) as user_email
            FROM $conversations_table as conv
            JOIN $messages_table as msg ON conv.id = msg.conversation_id
            ORDER BY conv.id ASC, msg.date ASC
        ";
        
        $all_messages = $wpdb->get_results($all_messages_query, ARRAY_A);

        $conversations = [];
        foreach ($all_messages as $msg) {
            $conv_id = $msg['conversation_id'];
            if (!isset($conversations[$conv_id])) {
                $conversations[$conv_id] = [
                    'id' => $conv_id,
                    'start_date' => $msg['start_date'],
                    'user_name' => $msg['user_name'] ?: 'Anonymous',
                    'user_email' => $msg['user_email'] ?: 'N/A',
                    'ip' => $msg['ip'],
                    'messages' => []
                ];
            }
            $conversations[$conv_id]['messages'][] = [
                'sender' => $msg['sender'],
                'date' => $msg['message_date'],
                'text' => $msg['message']
            ];
        }

        $filename = 'chatbot_messages-' . date('Y-m-d') . '.' . $format;
        $output = '';

        switch ($format) {
            case 'csv':
                header('Content-Type: text/csv; charset=utf-8');
                $output .= "\xEF\xBB\xBF"; // BOM for UTF-8
                $output .= '"Conversation ID","User Name","User Email","User IP","Message Date","Sender","Message"' . "\n";
                foreach ($conversations as $conv) {
                    foreach ($conv['messages'] as $msg) {
                        // Sanitize each field before imploding
                        $row = [
                            $this->sanitize_for_csv($conv['id']),
                            $this->sanitize_for_csv($conv['user_name']),
                            $this->sanitize_for_csv($conv['user_email']),
                            $this->sanitize_for_csv($conv['ip']),
                            $this->sanitize_for_csv($msg['date']),
                            $this->sanitize_for_csv($msg['sender']),
                            $this->sanitize_for_csv($msg['text'])
                        ];
                        $output .= '"' . implode('","', $row) . '"' . "\n";
                    }
                }
                break;

            case 'md':
                header('Content-Type: text/markdown; charset=utf-8');
                foreach ($conversations as $conv) {
                    $output .= "# Conversation: Chat_" . $conv['id'] . "\n\n";
                    $output .= "- **User:** " . $conv['user_name'] . "\n";
                    $output .= "- **Email:** " . $conv['user_email'] . "\n";
                    $output .= "- **IP:** " . $conv['ip'] . "\n";
                    $output .= "- **Date:** " . $conv['start_date'] . "\n\n";
                    $output .= "## Messages\n\n";
                    foreach ($conv['messages'] as $msg) {
                        $output .= "**" . $msg['sender'] . "** (*" . $msg['date'] . "*):\n";
                        $output .= "> " . str_replace("\n", "\n> ", $msg['text']) . "\n\n";
                    }
                    $output .= "---\n\n";
                }
                break;

            case 'html':
                header('Content-Type: text/html; charset=utf-8');
                $output = '<!DOCTYPE html>
                <html>
                <head>
                    <title>Chatbot Conversations</title>
                    <style>
                        body {
                            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
                            font-size: 14px;
                            line-height: 1.5;
                            background-color: #f5f5f5;
                            color: #333;
                            margin: 0;
                            padding: 20px;
                        }
                        .container {
                            max-width: 900px;
                            margin: 0 auto;
                        }
                        h1 {
                            margin-top: 0;
                            margin-bottom: 20px;
                            font-size: 24px;
                        }
                        .conv {
                            background-color: #ffffff;
                            border: 1px solid #e0e0e0;
                            padding: 20px;
                            margin-bottom: 20px;
                            border-radius: 8px;
                            box-shadow: 0 1px 3px rgba(0,0,0,0.04);
                        }
                        .conv h2 {
                            margin: 0 0 5px 0;
                            font-size: 18px;
                        }
                        .conv-meta {
                            font-size: 12px;
                            color: #666;
                            margin-bottom: 15px;
                            border-bottom: 1px solid #eee;
                            padding-bottom: 10px;
                        }
                        .msg {
                            margin-top: 10px;
                        }
                        .msg-meta {
                            font-size: 12px;
                            margin-bottom: 4px;
                        }
                        .msg-meta strong {
                            font-weight: 600;
                        }
                        .msg-meta small {
                            color: #888;
                            margin-left: 8px;
                        }
                        .msg-content {
                            padding: 10px 12px;
                            border-radius: 6px;
                            display: inline-block;
                            max-width: 90%;
                        }
                        .msg.user .msg-content {
                            background-color: #e1f5fe;
                        }
                        .msg.bot .msg-content {
                            background-color: #f1f1f1;
                        }
                    </style>
                </head>
                <body>
                    <div class="container">
                        <h1>Chatbot Conversations</h1>';
                
                foreach ($conversations as $conv) {
                    $output .= "<div class='conv'>";
                    $output .= "<h2>Conversation: Chat_" . esc_html($conv['id']) . "</h2>";
                    $output .= "<div class='conv-meta'><strong>User:</strong> " . esc_html($conv['user_name']) . " | <strong>Email:</strong> " . esc_html($conv['user_email']) . " | <strong>IP:</strong> " . esc_html($conv['ip']) . " | <strong>Date:</strong> " . esc_html($conv['start_date']) . "</div>";
                    
                    foreach ($conv['messages'] as $msg) {
                        $output .= "<div class='msg " . strtolower(esc_attr($msg['sender'])) . "'>";
                        $output .= "<div class='msg-meta'><strong>" . esc_html($msg['sender']) . "</strong> <small>(" . esc_html($msg['date']) . ")</small></div>";
                        $output .= "<div class='msg-content'>" . nl2br(esc_html($msg['text'])) . "</div>";
                        $output .= "</div>";
                    }
                    $output .= "</div>"; // close .conv
                }
                $output .= "</div></body></html>"; // close .container, body, html
                break;
            
            default: // txt
                header('Content-Type: text/plain; charset=utf-8');
                foreach ($conversations as $conv) {
                    $output .= "==================================================\n";
                    $output .= "CONVERSATION START\n";
                    $output .= "==================================================\n";
                    $output .= "ID: Chat_" . $conv['id'] . "\n";
                    $output .= "User: " . $conv['user_name'] . "\n";
                    $output .= "Email: " . $conv['user_email'] . "\n";
                    $output .= "IP: " . $conv['ip'] . "\n";
                    $output .= "Date: " . $conv['start_date'] . "\n";
                    $output .= "--------------------------------------------------\n\n";
                    foreach ($conv['messages'] as $msg) {
                        $output .= "[" . $msg['date'] . "] " . $msg['sender'] . ": " . $msg['text'] . "\n";
                    }
                    $output .= "\n\n";
                }
                break;
        }

        header('Content-Disposition: attachment; filename="' . sanitize_file_name($filename) . '"');
        header('Content-Length: ' . strlen($output));
        echo $output;
        exit;
    }

    /**
     * Handle fetching messages for a specific conversation.
     *
     * @since    1.6.5
     */
    public function get_conversation_messages() {
        if (!current_user_can('manage_options') || !check_ajax_referer('newcodebyte_chatbot_admin_nonce', 'nonce', false)) {
            wp_send_json_error(['message' => __('Security check failed.', NCB_CHATBOT_TEXT_DOMAIN)], 403);
            return;
        }

        $conversation_id = isset($_POST['conversation_id']) ? absint($_POST['conversation_id']) : 0;
        if (empty($conversation_id)) {
            wp_send_json_error(['message' => 'Conversation ID is required.'], 400);
            return;
        }

        global $wpdb;
        $table_name = $wpdb->prefix . 'newcodebyte_chatbot_messages';
        
        $user_info = $wpdb->get_row($wpdb->prepare("SELECT user_name, user_email FROM $table_name WHERE conversation_id = %d AND (user_name IS NOT NULL AND user_name != '') LIMIT 1", $conversation_id), ARRAY_A);
        $user_display_name = __('Anonymous User', NCB_CHATBOT_TEXT_DOMAIN);
        if ($user_info) {
            if (!empty($user_info['user_name'])) {
                $user_display_name = $user_info['user_name'];
            } elseif (!empty($user_info['user_email'])) {
                $user_display_name = $user_info['user_email'];
            }
        }

        $messages = $wpdb->get_results($wpdb->prepare("SELECT sender, message, date FROM $table_name WHERE conversation_id = %d ORDER BY date ASC", $conversation_id), ARRAY_A);
        
        $messages_html = '';
        if ($messages) {
            foreach ($messages as $row) {
                $sender_name = ($row['sender'] === 'User') ? $user_display_name : 'Bot';
                $sender_class = strtolower(esc_attr($row['sender']));

                $messages_html .= '<div class="admin-chat-message ' . $sender_class . '">';
                $messages_html .= '<div class="message-meta"><strong>' . esc_html($sender_name) . '</strong> - <small>' . esc_html($row['date']) . '</small></div>';
                $message_text = nl2br(esc_html(trim($row['message'])));
                $messages_html .= '<div class="message-content">' . $message_text . '</div>';
                $messages_html .= '</div>';
            }
        }
        
        wp_send_json_success(['html' => $messages_html]);
    }

    /**
     * Handle marking a conversation as read.
     *
     * @since    1.6.5
     */
    public function mark_as_read() {
        if (!current_user_can('manage_options') || !check_ajax_referer('newcodebyte_chatbot_admin_nonce', 'nonce', false)) {
            wp_send_json_error(['message' => __('Security check failed.', NCB_CHATBOT_TEXT_DOMAIN)], 403);
            return;
        }

        $conversation_id = isset($_POST['conversation_id']) ? absint($_POST['conversation_id']) : 0;
        if (empty($conversation_id)) {
            wp_send_json_error(['message' => 'Conversation ID is required.'], 400);
            return;
        }

        global $wpdb;
        $table_name = $wpdb->prefix . 'newcodebyte_chatbot_messages';

        $result = $wpdb->update(
            $table_name,
            ['is_read' => 1],
            ['conversation_id' => $conversation_id, 'is_read' => 0],
            ['%d'],
            ['%d', '%d']
        );

        if ($result !== false && $result > 0) {
            delete_transient('newcodebyte_chatbot_unread_count');
        }

        wp_send_json_success();
    }
}