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

require_once BOTAMI_PLUGIN_PATH . 'includes/class-api-config.php';

class Botami_Ajax_Handler {


    public static function chatbot_send_message() {
        check_ajax_referer('chatbot_nonce', 'nonce');

        // Check if the message was sent in the request
        if (!isset($_POST['message']) || empty($_POST['message'])) {
            wp_send_json_error(Botami_Language_Manager::get_text('no_message'));
        }

        // Sanitize the input
        $history = isset($_POST['history']) ? wp_unslash($_POST['history']) : [];
        if (!is_array($history)) {
            wp_send_json_error('Invalid history format');
            exit;
        }
        
        $history = array_map(function($item) {
            return array(
                'role' => sanitize_text_field(wp_unslash($item['role'] ?? '')),
                'content' => sanitize_text_field(wp_unslash($item['content'] ?? ''))
            );
        }, $history);

        // Check if this is a questionnaire summary
        $is_questionnaire_summary = isset($_POST['is_questionnaire_summary']) && $_POST['is_questionnaire_summary'] === 'true';

        $api_key = get_option('botami_api_key');
        
        if (empty($api_key)) {
            wp_send_json_error(Botami_Language_Manager::get_text('service_unavailable'));
        }

        // Prepare data for API call
        $data = array(
            'history' => $history,
            'is_questionnaire_summary' => $is_questionnaire_summary
        );

        $api_url = Botami_API_Config::get_message_endpoint();  
        
        try {
            $response = wp_remote_post($api_url, array(
                'body' => json_encode($data),
                'headers' => array(
                    'X-API-Key' => $api_key,
                    'Content-Type' => 'application/json'),
                'timeout' => 60,
            ));

            if (is_wp_error($response)) {
                wp_send_json_error(Botami_Language_Manager::get_text('communication_error'));
                return;
            } 
            
            $body = wp_remote_retrieve_body($response);
            if (empty($body)) {
                wp_send_json_error(Botami_Language_Manager::get_text('communication_error'));
                return;
            }

            $response_data = json_decode($body, true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                wp_send_json_error(Botami_Language_Manager::get_text('communication_error'));
                return;
            }

            if (isset($response_data['exceed'])) {
                if ($response_data['exceed'] == 1) {
                    update_option('botami_exceed_limit', 1);
                    wp_send_json_error(Botami_Language_Manager::get_text('limit_exceed'));
                } else {
                    update_option('botami_exceed_limit', null);
                }
            }

            if (isset($response_data['response'])) {
                $final_response = array(
                    'response' => $response_data['response'],
                    // For questionnaire summaries, we generally don't want feedback requests
                    'request_feedback' => $is_questionnaire_summary ? false : 
                        (isset($response_data['request_feedback']) ? $response_data['request_feedback'] : false)
                );
                wp_send_json_success($final_response);
            } else {
                wp_send_json_error(Botami_Language_Manager::get_text('try_again_later'));
            }
            
        } catch (Exception $e) {
            wp_send_json_error(Botami_Language_Manager::get_text('communication_error'));
        }
    }


    public static function chatbot_save_message() {
        check_ajax_referer('chatbot_nonce', 'nonce');

        try {
            // Check for the source and message
            if (!isset($_POST['message'], $_POST['source'])) {
                throw new Exception('No message or source provided');
            }

            // Use wp_kses_post to preserve safe HTML tags (strong, em, br, ul, ol, li, etc.)
            $message = wp_kses_post(wp_unslash($_POST['message']));
            $source = $_POST['source'] === 'assistant' ? 'assistant' : 'user';

                $chatMessages = Botami_Chat_Messages::getInstance();
                $chatMessages->save_chat_message($message, $source);
            

            wp_send_json_success(['message' => 'Message saved successfully']);
        } catch (Exception $e) {
            $error_message = sprintf(
                'Error in save_message: %s in %s on line %d',
                $e->getMessage(),
                $e->getFile(),
                $e->getLine()
            );
            wp_send_json_error(['error' => $error_message]);
        }
    }

    public static function get_messages() {
        check_ajax_referer('chatbot_nonce', 'nonce');
        $chatMessages = Botami_Chat_Messages::getInstance();
        $messages = $chatMessages->get_chat_messages();
       
        wp_send_json_success(['messages' => $messages]);
    }

    public static function check_has_messages() {
            check_ajax_referer('chatbot_nonce', 'nonce');
            $chatMessages = Botami_Chat_Messages::getInstance();
            $hasMessages = $chatMessages->has_messages();
            wp_send_json_success(['hasMessages' => $hasMessages]);
        
    }

    public static function save_feedback() {
        check_ajax_referer('chatbot_nonce', 'nonce');

        if (!isset($_POST['feedback']) || !in_array($_POST['feedback'], ['positive', 'negative'])) {
            wp_send_json_error('Invalid feedback type');
            exit;
        }
    
        $feedback = sanitize_text_field(wp_unslash($_POST['feedback']));
        
        $api_key = get_option('botami_api_key');
        if (empty($api_key)) {
            wp_send_json_error('API key not configured');
            exit;
        }
    
        // Call the FastAPI backend to save the feedback
        $api_url = Botami_API_Config::get_save_feedback_endpoint();
        
        try {
            $response = wp_remote_post($api_url, array(
                'body' => json_encode([
                    'feedback' => $feedback
                ]),
                'headers' => array(
                    'X-API-Key' => $api_key,
                    'Content-Type' => 'application/json'
                ),
                'timeout' => 15,
            ));
    
            if (is_wp_error($response)) {
                wp_send_json_error('Error saving feedback');
                return;
            }
    
            $body = wp_remote_retrieve_body($response);
            $data = json_decode($body, true);
    
            if (isset($data['success']) && $data['success']) {
                wp_send_json_success(['message' => 'Feedback saved successfully']);
            } else {
                wp_send_json_error('Failed to save feedback');
            }
        } catch (Exception $e) {
            wp_send_json_error('Error saving feedback');
        }
    }

    /**
     * Handles saving a new lead submission
     */
    public static function save_chatbot_lead() {
        try {
            // Verify nonce
            check_ajax_referer('chatbot_nonce', 'nonce');
            
            // Check for required fields
            if (!isset($_POST['name']) || !isset($_POST['email'])) {
                wp_send_json_error(['message' => 'Missing required fields']);
                return;
            }
            
            // Sanitize input
            $name = sanitize_text_field(wp_unslash($_POST['name']));
            $email = sanitize_email(wp_unslash($_POST['email']));
            $custom_field_label = isset($_POST['custom_field_label']) ? sanitize_text_field(wp_unslash($_POST['custom_field_label'])) : '';
            $custom_field_value = isset($_POST['custom_field_value']) ? sanitize_text_field(wp_unslash($_POST['custom_field_value'])) : '';
            
            // Validate email
            if (!is_email($email)) {
                wp_send_json_error(['message' => 'Invalid email address']);
                return;
            }
            
            // Get lead generator instance
            $lead_generator = Botami_Lead_Generator::getInstance();
            
            // Save the lead
            $result = $lead_generator->save_lead($name, $email, $custom_field_label, $custom_field_value);
            
            if ($result) {
                // Send email notification to admin using the dedicated email notifier
                $email_notifier = Botami_Lead_Email_Notifier::getInstance();
                $email_notifier->send_notification($name, $email, $custom_field_label, $custom_field_value);
                
                wp_send_json_success(['message' => 'Lead saved successfully']);
            } else {
                wp_send_json_error(['message' => 'Failed to save lead']);
            }
        } catch (Exception $e) {
            wp_send_json_error(['message' => 'Error: ' . $e->getMessage()]);
        }
    }
    
    /**
     * Checks if the current user/session has already submitted a lead
     */
    public static function check_chatbot_lead_submission() {
        try {
            // Verify nonce
            check_ajax_referer('chatbot_nonce', 'nonce');
            
            // Get lead generator instance
            $lead_generator = Botami_Lead_Generator::getInstance();
            
            // Check if current user or session has a lead
            $has_submitted = $lead_generator->has_submitted_lead();
            
            wp_send_json_success(['has_submitted' => $has_submitted]);
        } catch (Exception $e) {
            wp_send_json_error(['message' => 'Error: ' . $e->getMessage()]);
        }
    }
}

// Register the AJAX handler for logged-in and non-logged-in users
add_action('wp_ajax_botami_chatbot_send_message', array('Botami_Ajax_Handler', 'chatbot_send_message'));
add_action('wp_ajax_nopriv_botami_chatbot_send_message', array('Botami_Ajax_Handler', 'chatbot_send_message'));


add_action('wp_ajax_botami_save_feedback', array('Botami_Ajax_Handler', 'save_feedback'));
add_action('wp_ajax_nopriv_botami_save_feedback', array('Botami_Ajax_Handler', 'save_feedback'));

add_action('wp_ajax_botami_save_message', ['Botami_Ajax_Handler', 'chatbot_save_message']);
add_action('wp_ajax_nopriv_botami_save_message', ['Botami_Ajax_Handler', 'chatbot_save_message']);

add_action('wp_ajax_botami_get_messages', ['Botami_Ajax_Handler', 'get_messages']);
add_action('wp_ajax_nopriv_botami_get_messages', ['Botami_Ajax_Handler', 'get_messages']);

add_action('wp_ajax_botami_check_has_messages', ['Botami_Ajax_Handler', 'check_has_messages']);
add_action('wp_ajax_nopriv_botami_check_has_messages', ['Botami_Ajax_Handler', 'check_has_messages']);

add_action('wp_ajax_botami_save_chatbot_lead', ['Botami_Ajax_Handler', 'save_chatbot_lead']);
add_action('wp_ajax_nopriv_botami_save_chatbot_lead', ['Botami_Ajax_Handler', 'save_chatbot_lead']);

add_action('wp_ajax_botami_check_lead_submission', ['Botami_Ajax_Handler', 'check_chatbot_lead_submission']);
add_action('wp_ajax_nopriv_botami_check_lead_submission', ['Botami_Ajax_Handler', 'check_chatbot_lead_submission']);