<?php
namespace AI_BotKit\Admin;

/**
 * Class Ajax_Handler
 * 
 * Handles all AJAX requests for the AI BotKit plugin.
 * This class manages API testing, chatbot operations, and fallback order management.
 */
class Ajax_Handler {

    /**
     * Constructor - Registers all AJAX hooks
     */
    public function __construct() {
        // API testing endpoint
        add_action('wp_ajax_ai_botkit_test_api_connection', array($this, 'handle_test_api'));
        
        // Chatbot management endpoints
        add_action('wp_ajax_ai_botkit_save_chatbot', array($this, 'handle_save_chatbot'));
        add_action('wp_ajax_ai_botkit_get_chatbot', array($this, 'handle_get_chatbot'));
        add_action('wp_ajax_ai_botkit_delete_chatbot', array($this, 'handle_delete_chatbot'));
        
        // Fallback order management endpoint
        add_action('wp_ajax_ai_botkit_update_fallback_order', array($this, 'handle_update_fallback_order'));

        // Rate limit management endpoints
        add_action('wp_ajax_ai_botkit_set_rate_limits', array($this, 'handle_set_rate_limits'));
        add_action('wp_ajax_ai_botkit_reset_rate_limits', array($this, 'handle_reset_rate_limits'));

        // Preview content endpoint
        add_action('wp_ajax_ai_botkit_preview_content', array($this, 'ai_botkit_preview_content'));

        // Document import endpoints
        add_action('wp_ajax_ai_botkit_upload_file', array($this, 'handle_file_upload'));
        add_action('wp_ajax_ai_botkit_import_url', array($this, 'handle_url_import'));
        add_action('wp_ajax_ai_botkit_import_wp_content', array($this, 'handle_wp_content_import'));
        add_action('wp_ajax_ai_botkit_delete_document', array($this, 'handle_delete_document'));

        // Chatbot document management endpoints
        add_action('wp_ajax_ai_botkit_add_chatbot_documents', array($this, 'handle_add_chatbot_documents'));
        add_action('wp_ajax_ai_botkit_remove_chatbot_document', array($this, 'handle_remove_chatbot_document'));
        add_action('wp_ajax_ai_botkit_get_chatbot_documents', array($this, 'handle_get_chatbot_documents'));

        // New endpoint for getting available documents for selection
        add_action('wp_ajax_ai_botkit_get_available_documents', array($this, 'handle_get_available_documents'));

        // Avatar upload endpoint
        add_action('wp_ajax_ai_botkit_upload_avatar', array($this, 'handle_upload_avatar'));
        add_action('wp_ajax_ai_botkit_upload_background_image', array($this, 'handle_upload_background_image'));

        // Enable chatbot sitewide endpoint
        add_action('wp_ajax_ai_botkit_enable_chatbot_sitewide', array($this, 'handle_enable_chatbot_sitewide'));
        add_action('wp_ajax_ai_botkit_enable_chatbot', array($this, 'handle_enable_chatbot'));
        add_action('wp_ajax_ai_botkit_get_pages', array($this, 'get_pages'));
        add_action('wp_ajax_ai_botkit_get_post_types', array($this, 'get_post_types'));
        add_action('wp_ajax_ai_botkit_enable_chatbot_post_type', array($this, 'handle_enable_chatbot_post_type'));

        // Conversations & Leads AJAX endpoints
        add_action('wp_ajax_ai_botkit_get_conversations', array($this, 'handle_get_conversations'));
        add_action('wp_ajax_ai_botkit_get_conversation_detail', array($this, 'handle_get_conversation_detail'));
        add_action('wp_ajax_ai_botkit_get_leads', array($this, 'handle_get_leads'));
    }

    /**
     * Search pages for chatbot placement
     */
    public function get_pages() {
        check_ajax_referer('ai_botkit_admin', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => esc_html__('Insufficient permissions.', 'ai-botkit-for-lead-generation')]);
        }

        $chatbot_id = isset($_POST['chatbot_id']) ? sanitize_text_field($_POST['chatbot_id']) : 0;

        $args = [
            'post_type' => 'page',
            'post_status' => 'publish',
            'posts_per_page' => -1,
        ];

        $query = new \WP_Query($args);
        $pages = [];

        if ($query->have_posts()) {
            while ($query->have_posts()) {
                $query->the_post();
                $pages[] = [
                    'ID' => get_the_ID(),
                    'post_title' => get_the_title()
                ];
            }
        }

        $enabled_pages = get_option('ai_botkit_chatbot_enabled_pages', []);
        $all_pages = array();
        foreach($pages as $page) {
            if( isset($enabled_pages[$page['ID']]) ){
                $enabled = in_array($chatbot_id, $enabled_pages[$page['ID']]) ? true : false;
            } else {
                $enabled = false;
            }
            $all_pages[] = array(
                'ID' => $page['ID'],
                'post_title' => $page['post_title'],
                'enabled' => $enabled
            );
        }
        

        wp_reset_postdata();
        wp_send_json_success($all_pages);
    }


    /**
     * Handle enabling chatbot sitewide
     */
    public function handle_enable_chatbot_sitewide() {
        check_ajax_referer('ai_botkit_admin', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => esc_html__('Insufficient permissions.', 'ai-botkit-for-lead-generation')]);
        }

        $chatbot_id = isset($_POST['chatbot_id']) ? sanitize_text_field($_POST['chatbot_id']) : 0;
        $enable_chatbot_sitewide = isset($_POST['enable_chatbot_sitewide']) ? intval($_POST['enable_chatbot_sitewide']) : 0;
        
        if( $chatbot_id <= 0 ) {
            wp_send_json_error(['message' => esc_html__('Invalid chatbot ID.', 'ai-botkit-for-lead-generation')]);
        }

        if( $enable_chatbot_sitewide ) {
            update_option('ai_botkit_chatbot_sitewide_enabled', $chatbot_id);
            wp_send_json_success(['message' => esc_html__('Chatbot enabled sitewide.', 'ai-botkit-for-lead-generation')]);
        } else {
            update_option('ai_botkit_chatbot_sitewide_enabled', 0);
            wp_send_json_success(['message' => esc_html__('Chatbot disabled sitewide.', 'ai-botkit-for-lead-generation')]);
        }
    }

    /**
     * Handle enabling chatbot on specific pages
     */
    public function handle_enable_chatbot() {
        check_ajax_referer('ai_botkit_admin', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => esc_html__('Insufficient permissions.', 'ai-botkit-for-lead-generation')]);
        }

        $chatbot_id = isset($_POST['chatbot_id']) ? sanitize_text_field($_POST['chatbot_id']) : 0;
        $enable_chatbot = isset($_POST['enable_chatbot']) ? intval($_POST['enable_chatbot']) : 0;
        $page_id = isset($_POST['page_id']) ? intval($_POST['page_id']) : 0;
        
        if( $chatbot_id === 0 ) {
            wp_send_json_error(['message' => esc_html__('Invalid chatbot ID.', 'ai-botkit-for-lead-generation')]);
        }

        $enabled_pages = get_option('ai_botkit_chatbot_enabled_pages', []);
        if( $enable_chatbot ) {
            if( !isset($enabled_pages[$page_id]) ){
                $enabled_pages[$page_id] = array($chatbot_id);
            } else {
                $enabled_pages[$page_id][] = $chatbot_id;
            }
            update_option('ai_botkit_chatbot_enabled_pages', $enabled_pages);
            wp_send_json_success(['message' => esc_html__('Chatbot enabled on page.', 'ai-botkit-for-lead-generation')]);
        } else {
            if( isset($enabled_pages[$page_id]) && in_array($chatbot_id, $enabled_pages[$page_id]) ){
                $enabled_pages[$page_id] = array_diff($enabled_pages[$page_id], [$chatbot_id]);
                if( empty($enabled_pages[$page_id]) ){
                    unset($enabled_pages[$page_id]);
                }
            }
            update_option('ai_botkit_chatbot_enabled_pages', $enabled_pages);
            wp_send_json_success(['message' => esc_html__('Chatbot disabled on page.', 'ai-botkit-for-lead-generation')]);
        }
    }

    /**
     * Handle AJAX request for fetching conversations list
     */
    public function handle_get_conversations() {
        check_ajax_referer('ai_botkit_admin', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => esc_html__('Insufficient permissions.', 'ai-botkit-for-lead-generation')]);
        }

        $bot_id = isset($_POST['bot_id']) ? intval($_POST['bot_id']) : 0;
        $page = isset($_POST['page']) ? max(1, intval($_POST['page'])) : 1;
        $limit = isset($_POST['limit']) ? intval($_POST['limit']) : 20;
        $search = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';

        if ($bot_id <= 0) {
            wp_send_json_error(['message' => esc_html__('Invalid chatbot ID.', 'ai-botkit-for-lead-generation')]);
        }

        $api_handler = new \AI_BotKit\Integration\API_Handler();
        $params = [
            'page' => $page,
            'limit' => $limit,
        ];
        if (!empty($search)) {
            $params['search'] = $search;
        }

        $response = $api_handler->send_get_request('chatbots/' . $bot_id . '/conversations', $params);
        wp_send_json($response);
    }

    /**
     * Handle AJAX request for fetching a single conversation's detail
     */
    public function handle_get_conversation_detail() {
        check_ajax_referer('ai_botkit_admin', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => esc_html__('Insufficient permissions.', 'ai-botkit-for-lead-generation')]);
        }

        $conversation_id = isset($_POST['conversation_id']) ? intval($_POST['conversation_id']) : 0;

        if ($conversation_id <= 0) {
            wp_send_json_error(['message' => esc_html__('Invalid conversation ID.', 'ai-botkit-for-lead-generation')]);
        }

        $api_handler = new \AI_BotKit\Integration\API_Handler();
        $response = $api_handler->send_get_request('conversations/' . $conversation_id);
        wp_send_json($response);
    }

    /**
     * Handle AJAX request for fetching leads
     */
    public function handle_get_leads() {
        check_ajax_referer('ai_botkit_admin', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => esc_html__('Insufficient permissions.', 'ai-botkit-for-lead-generation')]);
        }

        $bot_id = isset($_POST['bot_id']) ? intval($_POST['bot_id']) : 0;
        $page = isset($_POST['page']) ? max(1, intval($_POST['page'])) : 1;
        $limit = isset($_POST['limit']) ? intval($_POST['limit']) : 10;

        if ($bot_id <= 0) {
            wp_send_json_error(['message' => esc_html__('Invalid chatbot ID.', 'ai-botkit-for-lead-generation')]);
        }

        $api_handler = new \AI_BotKit\Integration\API_Handler();
        $response = $api_handler->send_get_request('chatbots/' . $bot_id . '/leads', [
            'page' => $page,
            'limit' => $limit,
        ]);
        wp_send_json($response);
    }

    /**
     * Get available public post types for chatbot placement
     */
    public function get_post_types() {
        check_ajax_referer('ai_botkit_admin', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => esc_html__('Insufficient permissions.', 'ai-botkit-for-lead-generation')]);
        }

        $chatbot_id = isset($_POST['chatbot_id']) ? sanitize_text_field($_POST['chatbot_id']) : 0;

        $post_types = get_post_types(['public' => true], 'objects');
        $exclude = ['attachment', 'revision', 'nav_menu_item', 'custom_css', 'customize_changeset', 'oembed_cache', 'user_request', 'wp_block', 'wp_template', 'wp_template_part', 'wp_global_styles', 'wp_navigation'];

        $enabled_post_types = get_option('ai_botkit_chatbot_enabled_post_types', []);

        $all_post_types = [];
        foreach ($post_types as $pt) {
            if (in_array($pt->name, $exclude, true)) {
                continue;
            }

            $enabled = false;
            if (isset($enabled_post_types[$pt->name]) && in_array($chatbot_id, $enabled_post_types[$pt->name], true)) {
                $enabled = true;
            }

            $all_post_types[] = [
                'name' => $pt->name,
                'label' => $pt->label,
                'enabled' => $enabled,
            ];
        }

        wp_send_json_success($all_post_types);
    }

    /**
     * Handle enabling chatbot on specific post types
     */
    public function handle_enable_chatbot_post_type() {
        check_ajax_referer('ai_botkit_admin', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => esc_html__('Insufficient permissions.', 'ai-botkit-for-lead-generation')]);
        }

        $chatbot_id = isset($_POST['chatbot_id']) ? sanitize_text_field($_POST['chatbot_id']) : 0;
        $enable_chatbot = isset($_POST['enable_chatbot']) ? intval($_POST['enable_chatbot']) : 0;
        $post_type = isset($_POST['post_type']) ? sanitize_text_field($_POST['post_type']) : '';

        if ($chatbot_id === 0) {
            wp_send_json_error(['message' => esc_html__('Invalid chatbot ID.', 'ai-botkit-for-lead-generation')]);
        }

        if (empty($post_type)) {
            wp_send_json_error(['message' => esc_html__('Invalid post type.', 'ai-botkit-for-lead-generation')]);
        }

        $enabled_post_types = get_option('ai_botkit_chatbot_enabled_post_types', []);

        if ($enable_chatbot) {
            if (!isset($enabled_post_types[$post_type])) {
                $enabled_post_types[$post_type] = [$chatbot_id];
            } elseif (!in_array($chatbot_id, $enabled_post_types[$post_type], true)) {
                $enabled_post_types[$post_type][] = $chatbot_id;
            }
            update_option('ai_botkit_chatbot_enabled_post_types', $enabled_post_types);
            wp_send_json_success(['message' => esc_html__('Chatbot enabled on post type.', 'ai-botkit-for-lead-generation')]);
        } else {
            if (isset($enabled_post_types[$post_type]) && in_array($chatbot_id, $enabled_post_types[$post_type], true)) {
                $enabled_post_types[$post_type] = array_diff($enabled_post_types[$post_type], [$chatbot_id]);
                if (empty($enabled_post_types[$post_type])) {
                    unset($enabled_post_types[$post_type]);
                }
            }
            update_option('ai_botkit_chatbot_enabled_post_types', $enabled_post_types);
            wp_send_json_success(['message' => esc_html__('Chatbot disabled on post type.', 'ai-botkit-for-lead-generation')]);
        }
    }
} 