<?php

class REM_AI_Chat_Handler {
    public function __construct() {
        add_action('wp_ajax_rem_ai_chat', array($this, 'handle'));
        add_action('wp_ajax_nopriv_rem_ai_chat', array($this, 'handle'));
        add_action('wp_footer', array($this, 'render_front_template'));
        add_action('wp_enqueue_scripts', array($this, 'render_front_scripts'));

        add_action('wp_ajax_rem_ai_chat_history', array($this, 'rem_ai_chat_history'));
        add_action('wp_ajax_nopriv_rem_ai_chat_history', array($this, 'rem_ai_chat_history'));
    }

    public function handle() {
        global $rem_ob;

        //  Sanitize inputs
        $message = sanitize_text_field($_POST['message']);
        $session_id = isset($_COOKIE['rem_ai_chat_session']) ? sanitize_text_field($_COOKIE['rem_ai_chat_session']) : wp_generate_uuid4();
        setcookie('rem_ai_chat_session', $session_id, time() + 3600, "/"); // 1 hour session

        $api_key = rem_get_option('gemini_api');
        $all_fields = $rem_ob->single_property_fields();

        //  Load chat history (persistent per session)
        $history_key = 'rem_ai_chat_' . md5($session_id);
        $chat_history = get_transient($history_key);
        if (!is_array($chat_history)) $chat_history = [];

        // Limit stored turns (only last 2 exchanges)
        $max_turns = 2;
        if (count($chat_history) > $max_turns) {
            $chat_history = array_slice($chat_history, -$max_turns);
        }

        //  Collect available fields
        $fields = [];
        $skipKeys = [
            'before_price_text', 'after_price_text', 'property_video',
            'file_attachments', 'property_detail_cbs', 'property_featured'
        ];
        foreach ($all_fields as $f) {
            if (!in_array($f['key'], $skipKeys)) {
                $fields[$f['key']] = array(
                    'title' => $f['title'],
                );
                if (isset($f['options']) && !empty($f['options'])) {
                    $fields[$f['key']]['options'] = $f['options'];
                }
            }
        }

        //  Build system prompt
        $system_prompt = <<<PROMPT
        You are a helpful multilingual AI real-estate assistant for a WordPress property website.

        The system uses meta fields for properties. Below is a list of available fields and their meanings:
        FIELDS:
        {FIELDS_JSON}

        Your job:
        1. Understand the user's query and return a **single valid JSON object only** — no markdown, code blocks, or explanations.
        2. The JSON must contain:
           - "filters": object — key-value pairs of property filters.
           - "success_message": string — a short, natural response (in the same tone/language as the user) when listings are found.
           - "no_results_message": string — a short, polite message (in the same tone/language as the user) when no listings match, also suggesting to contact owner or support email.
        3. Use the meta keys exactly as shown.
        4. For price ranges like “between 50k and 100k”, use numeric keys "min_price" and "max_price".
        5. If the user doesn't specify filters, return an empty object for "filters".

        Example output:
        {
          "filters": {
            "property_type": "Office",
            "min_price": 50000,
            "max_price": 100000
          },
          "success_message": "Here are some listings that match your request!",
          "no_results_message": "I couldn’t find listings for your query. {CONTACT_INFO}"
        }
        PROMPT;

        $system_prompt = str_replace('{FIELDS_JSON}', json_encode($fields, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE), $system_prompt);

        $site_contact_info = rem_get_option('bot_cntct');

        $system_prompt = str_replace('{CONTACT_INFO}', $site_contact_info, $system_prompt);

        //  Build conversational context
        $conversation_context = "";
        foreach ($chat_history as $turn) {
            $conversation_context .= "User: {$turn['user']}\nAssistant: {$turn['ai']}\n\n";
        }

        // The final prompt Gemini receives
        $final_prompt = <<<PROMPT
    $system_prompt

    Previous conversation:
    $conversation_context

    Now continue the conversation:
    User: "$message"

    Please return ONLY the JSON object as instructed above.
    PROMPT;

        $response = wp_remote_post("https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent", [
            'headers' => [
                'x-goog-api-key' => $api_key,
                'Content-Type'   => 'application/json',
            ],
            'body' => json_encode([
                'contents' => [
                    ['parts' => [['text' => $final_prompt]]]
                ],
            ]),
            'timeout' => 30,
        ]);

        if (is_wp_error($response)) {
            echo "Network error. Please try again later.";
            wp_die();
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        $json_output = $body['candidates'][0]['content']['parts'][0]['text'] ?? '';

        // Extract only JSON portion (in case model wraps it accidentally)
        if (preg_match('/\{[\s\S]*\}/', $json_output, $matches)) {
            $json_output = $matches[0];
        }

        $intent = json_decode(trim($json_output), true);
        if (!is_array($intent)) $intent = [];
        
        // Separate filters and messages
        $filters = $intent['filters'] ?? [];
        $success_message = $intent['success_message'] ?? 'Here are some listings I found for you:';
        $no_results_message = $intent['no_results_message'] ?? 'I couldn’t find any listings for your query.';


        //  Build meta_query safely
        $meta_query = [];
        foreach ($all_fields as $f) {
            if (isset($filters[$f['key']])) {
                $meta_query[] = [
                    'key'     => 'rem_' . $f['key'],
                    'value'   => $filters[$f['key']],
                    'compare' => 'LIKE',
                ];
            }
        }

        if (!empty($filters['min_price']) || !empty($filters['max_price'])) {
            $range = [];
            if (!empty($filters['min_price'])) $range[] = (int)$filters['min_price'];
            if (!empty($filters['max_price'])) $range[] = (int)$filters['max_price'];

            $meta_query[] = [
                'key'     => 'rem_property_price',
                'value'   => $range,
                'compare' => count($range) === 2 ? 'BETWEEN' : (isset($filters['min_price']) ? '>=' : '<='),
                'type'    => 'NUMERIC'
            ];
        }

        //  Build query
        $query_args = [
            'post_type'      => 'rem_property',
            'posts_per_page' => 10,
            'post_status'    => array('publish'),
        ];

        if (!empty($meta_query)) {
            $query_args['meta_query'] = $meta_query;
        } else {
            $query_args['s'] = $message; // fallback keyword search
        }

        // : Run query
        $properties = get_posts($query_args);

        // : Build reply
        if (empty($properties)) {
            $reply = esc_html($no_results_message);
        } else {
            $reply = "<strong>" . esc_html($success_message) . "</strong>";
            foreach ($properties as $p) {
                $reply .= "<div class='ai-property-result'>
                    <a href='" . get_permalink($p->ID) . "' target='_blank'>"
                    . $this->get_featured_image($p->ID) . '<span>' . esc_html($p->post_title) . "</span></a>
                </div>";
            }
        }

        // : Save chat history
        $chat_history[] = [
            'user' => $message,
            'ai'   => wp_strip_all_tags($reply),
        ];
        set_transient($history_key, $chat_history, HOUR_IN_SECONDS);

        // : Output
        echo wp_kses_post($reply);
        wp_die();
    }

    function rem_ai_chat_history() {
        $session_id = isset($_COOKIE['rem_ai_chat_session'])
            ? sanitize_text_field($_COOKIE['rem_ai_chat_session'])
            : '';

        if (empty($session_id)) {
            wp_send_json_success([]); // no session yet
        }

        $history_key = 'rem_ai_chat_' . md5($session_id);
        $chat_history = get_transient($history_key);

        if (!is_array($chat_history)) $chat_history = [];

        wp_send_json_success($chat_history);
    }

    function render_front_scripts(){
        $ai_chat = rem_get_option('ai_chat', 'disable');
        if($ai_chat == 'enable'){
            wp_enqueue_style('rem-ai-chat-style', REM_URL . '/assets/front/css/chat.css');
            wp_enqueue_script('rem-ai-chat-script', REM_URL . '/assets/front/js/chat.js', array('jquery'), null, true);
            wp_localize_script('rem-ai-chat-script', 'remAIChat', array(
                'ajaxurl' => admin_url('admin-ajax.php')
            ));
        }
    }

    function render_front_template(){
        $ai_chat = rem_get_option('ai_chat', 'disable');
        if($ai_chat == 'enable'){
            include REM_PATH . '/templates/chat.php';
        }
    }

    function get_featured_image($id){
        if( has_post_thumbnail($id) ){
            return get_the_post_thumbnail( $id, 'thumbnail' );
        } elseif (rem_get_option('placeholder_image', '') != '') {
            return '<img src="'.rem_get_option('placeholder_image').'">';
        } else {
        // Use the first gallery picture
        $property_images = get_post_meta( $id, 'rem_property_images', true );
            if (is_array($property_images)) {
                foreach ($property_images as $image_id) {
                    return wp_get_attachment_image( $image_id, 'thumbnail', false );
                    break;
                }
            }
        }
    }
}

new REM_AI_Chat_Handler();
