<?php
namespace AI_BotKit\Admin;

use AI_BotKit\Core\RAG_Engine;
use AI_BotKit\Models\Chatbot;
use AI_BotKit\Utils\Cache_Manager;
use AI_BotKit\Admin\Ajax_Handler;
use AI_BotKit\Models\Conversation;
/**
 * The admin-specific functionality of the plugin.
 *
 * @package AI_BotKit
 * @subpackage AI_BotKit/admin
 */

class Admin {
    /**
     * The ID of this plugin.
     * @var string
     */
    private $plugin_name;

    /**
     * The version of this plugin.
     * @var string
     */
    private $version;

    /**
     * Cache manager instance
     * @var Cache_Manager
     */
    private $cache_manager;

    /**
     * RAG engine instance
     * @var RAG_Engine
     */
    private $rag_engine;

    /**
     * AJAX Handler instance
     */
    private $ajax_handler;

    /**
     * Plugin settings pages
     */
    private static $admin_pages;

    /**
     * Current tab
     */
    private $tab;

    /**
     * Initialize the class and set its properties.
     *
     * @param string $plugin_name The name of this plugin.
     * @param string $version The version of this plugin.
     * @param Cache_Manager|null $cache_manager Optional. Cache manager instance.
     * @param RAG_Engine|null $rag_engine Optional. RAG engine instance.
     */
    public function __construct($plugin_name, $version, Cache_Manager $cache_manager = null, RAG_Engine $rag_engine = null) {
        $this->plugin_name = $plugin_name;
        $this->version = $version;
        $this->cache_manager = $cache_manager;
        $this->rag_engine = $rag_engine;
        $this->ajax_handler = new Ajax_Handler();

        // Initialize admin hooks
        $this->init_hooks();

        self::$admin_pages = [
            'ai-botkit' => [
                'title' =>  __('AI BotKit Dashboard', 'ai-botkit-for-lead-generation'), /* translators: Main plugin admin page title */
                'menu_title' => __('AI BotKit', 'ai-botkit-for-lead-generation'),
                'capability' => 'manage_options',
                'icon' => 'dashicons-format-chat',
                'position' => 30,
                'callback' => 'display_dashboard_page'
            ],
            'ai-botkit-knowledge' => [
                'title' => __('Knowledge Base Management', 'ai-botkit-for-lead-generation'), /* translators: Knowledge base page title */
                'menu_title' => __('Knowledge Base', 'ai-botkit-for-lead-generation'),
                'parent' => 'ai-botkit',
                'capability' => 'manage_options',
                'callback' => 'display_knowledge_base_page'
            ],
            'ai-botkit-settings' => [
                'title' => __('Plugin Settings', 'ai-botkit-for-lead-generation'), /* translators: Settings page title */
                'menu_title' => __('Settings', 'ai-botkit-for-lead-generation'),
                'parent' => 'ai-botkit',
                'capability' => 'manage_options',
                'callback' => 'display_settings_page'
            ],
            'ai-botkit-analytics' => [
                'title' => __('Usage Analytics', 'ai-botkit-for-lead-generation'), /* translators: Analytics page title */
                'menu_title' => __('Analytics', 'ai-botkit-for-lead-generation'),
                'parent' => 'ai-botkit',
                'capability' => 'manage_options',
                'callback' => 'display_analytics_page'
            ]
        ];
    }

    /**
     * Initialize all admin hooks
     */
    private function init_hooks() {
        // Admin menu and pages
        add_action('admin_menu', array($this, 'add_plugin_admin_menu'));
        add_action('admin_init', array($this, 'handle_activation_redirect'));
        add_action('admin_footer', array($this, 'add_deactivate_modal'));
        

        // Admin assets
        add_action('admin_enqueue_scripts', array($this, 'enqueue_styles'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));

        // Handle post sync settings form submission
        add_action('admin_init', array($this, 'handle_post_sync_settings'));

        // Handle PEP settings form submission
        add_action('admin_init', array($this, 'handle_pep_settings'));

        // add_action('admin_notices', array($this, 'add_bfcm_banner'));

    }

    public function add_bfcm_banner() {
        $page = isset($_GET['page']) ? sanitize_text_field($_GET['page']) : '';
        if ($page === 'ai-botkit' && isset($_GET['tab']) && $_GET['tab'] === 'dashboard') {
            return;
        }
        ?>
        <style>
              .ai-botkit-bfcm-banner-image-container{
                width: 100%;
                display: flex;
                align-items: center;
                justify-content: center;
                border-radius: 12px;
            }
            .ai-botkit-bfcm-banner-image{
                width: 100%;
                object-fit: cover;
                border-radius: 12px;
                max-width: 1200px;
            }
        </style>
        <?php
        require_once AI_BOTKIT_PLUGIN_DIR . 'admin/views/bfcm-banner.php';
        return;
    }

    /**
     * Handle the activation redirect
     */
    public function handle_activation_redirect() {
        $saas_connect_token = get_option('ai_botkit_saas_connect_token');
        if (get_transient('_ai_botkit_activation_redirect')) {
            delete_transient('_ai_botkit_activation_redirect');
            if ($saas_connect_token) {
                wp_safe_redirect(admin_url('admin.php?page=ai-botkit&tab=chatbots'));
                exit;
            } else {
                wp_safe_redirect(admin_url('admin.php?page=ai-botkit&tab=dashboard'));
                exit;
            }
        }

        $saas_connect_token = get_option('ai_botkit_saas_connect_token');
        $tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'chatbots';
        $page = isset($_GET['page']) ? sanitize_text_field($_GET['page']) : '';
        if (!$saas_connect_token && $page === 'ai-botkit' && $tab !== 'dashboard' && $tab !== 'onboarding') {
            wp_safe_redirect(admin_url('admin.php?page=ai-botkit&tab=dashboard'));
            exit;
        }
    }

    /**
     * Add the deactivate modal
     */
    public function add_deactivate_modal() {
        if (get_current_screen()->id !== 'plugins') {
            return;
        }
        require_once AI_BOTKIT_PLUGIN_DIR . 'admin/views/deactivate-modal.php';
    }

    /**
     * Register the admin menu items
     */
    public function add_plugin_admin_menu() {
        // Main menu
        add_menu_page(
            __('AI BotKit', 'ai-botkit-for-lead-generation'),
            __('AI BotKit', 'ai-botkit-for-lead-generation'),
            'manage_options',
            'ai-botkit',
            array($this, 'display_dashboard_page'),
            'dashicons-format-chat',
            30
        );
    }

    /**
     * Enqueue admin-specific styles
     */
    public function enqueue_styles($hook) {
        // Always load Tabler icons
        wp_enqueue_style(
            'tabler-icons',
            AI_BOTKIT_PLUGIN_URL . 'admin/css/tabler-icons.css',
            array(),
            $this->version
        );

        // Only load help widget styles on AI BotKit pages
        if ($this->is_plugin_page($hook)) {
            wp_enqueue_style(
                'ai-botkit-admin-help-widget-css',
                AI_BOTKIT_PLUGIN_URL . 'admin/css/admin-help-widget.css',
                array('tabler-icons'),
                $this->version
            );
        }

        if ( 'plugins.php' === $hook ) {
            wp_enqueue_style(
                $this->plugin_name . '-admin-deactivate',
                AI_BOTKIT_PLUGIN_URL . 'admin/css/admin-deactivate.css',
                array(),
                $this->version
            );
            return;
        } else if (!$this->is_plugin_page($hook)) {
            return;
        }

        if (isset($_GET['page']) && $_GET['page'] === 'ai-botkit' && (isset($_GET['tab']) && ($_GET['tab'] === 'dashboard' || $_GET['tab'] === 'onboarding'))) {
            wp_enqueue_style(
                $this->plugin_name . '-saas-admin',
                AI_BOTKIT_PLUGIN_URL . 'admin/css/saas-admin.css',
                array(),
                $this->version
            );
        } else {
            wp_enqueue_style(
                $this->plugin_name . '-admin',
                AI_BOTKIT_PLUGIN_URL . 'admin/css/admin.css',
                array(),
                $this->version
            );
        }

        $css = "
            #wpcontent{
                padding-left: 0 !important;
                background-color:#F5FBF9 !important;
            }
            #wpbody-content .notice{
                display: none !important;
            }";
        wp_add_inline_style( $this->plugin_name . '-saas-admin', wp_kses_post($css) );
        wp_add_inline_style( $this->plugin_name . '-admin', wp_kses_post($css) );

        // Page specific styles
        // $page = $this->get_current_page();
        // if ($page) {
        //     wp_enqueue_style(
        //         $this->plugin_name . '-' . $page,
        //         AI_BOTKIT_PLUGIN_URL . 'admin/css/' . $page . '.css',
        //         array($this->plugin_name . '-admin'),
        //         $this->version
        //     );
        // }
    }

    /**
     * Register and enqueue admin-specific scripts
     */
    public function enqueue_scripts($hook) {
        // Only load help widget scripts on AI BotKit pages
        if ($this->is_plugin_page($hook)) {
            wp_enqueue_script(
                'ai-botkit-admin-help-widget-js',
                AI_BOTKIT_PLUGIN_URL . 'admin/js/admin-help-widget.js',
                array('jquery'),
                $this->version,
                true
            );
            
            // Localize script with REST API endpoint and bot ID
            wp_localize_script('ai-botkit-admin-help-widget-js', 'aiBotKitAdminHelp', array(
                'restApiEndpoint' => 'https://aibotkit.io/wp-json/ai-botkit/v1/chat/message',
                'botId' => 1, // Documentation bot ID
                'isExternalEndpoint' => true
            ));
        }

        // Only load on plugin pages
        if ( 'plugins.php' === $hook ) {
            wp_enqueue_script(
                $this->plugin_name . '-admin-deactivate',
                AI_BOTKIT_PLUGIN_URL . 'admin/js/admin-deactivate.js',
                array(),
                $this->version,
                true
            );
            return;
        } else if (!$this->is_plugin_page($hook)) {
            return;
        }
        
        wp_enqueue_script(
            'ai-botkit-admin',
            AI_BOTKIT_PLUGIN_URL . 'admin/js/admin.js',
            array('jquery', 'wp-color-picker'),
            $this->version,
            false
        );

        // Enqueue Color Picker
        wp_enqueue_style('wp-color-picker');
        wp_enqueue_script('jquery-ui-sortable');

        if( !get_transient('ai_botkit_onboarding_nonce') ) {
            // generate a random string for the nonce
            $nonce = md5(wp_rand(100000, 999999));
            set_transient('ai_botkit_onboarding_nonce', $nonce, 60 * 30);
        } else {
            $nonce = get_transient('ai_botkit_onboarding_nonce');
        }
        global $ai_botkit_url;

        // Localize script with plugin data
        wp_localize_script('ai-botkit-admin', 'ai_botkitAdmin', array(
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('ai_botkit_admin'),
            'i18n' => $this->get_js_translations(),
            'page' => $this->get_current_page(),
            'site_wide_chatbot_id' => get_option('ai_botkit_chatbot_sitewide_enabled'),
            'saas_url' => $ai_botkit_url,
            'saas_nonce' => $nonce,
            'site_url' => home_url(),
        ));
    }

    /**
     * Display dashboard page
     */
    public function display_dashboard_page() {
        $this->tab = isset($_GET['tab']) ? sanitize_key($_GET['tab']) : 'chatbots';

        // helper chatbot
        echo '<div id="ai-bot-kit-chatbot" data-chatbot-id="1d2b0d42-b319-4b"></div>
        <script src="https://app.aibotkit.io/embed.js" async></script>';

        if ($this->tab === 'dashboard') {
            require_once AI_BOTKIT_PLUGIN_DIR . 'admin/views/dashboard.php';
            return;
        }
        if ($this->tab === 'onboarding') {
            require_once AI_BOTKIT_PLUGIN_DIR . 'admin/views/onboarding.php';
            return;
        }

        $this->before_main_content();
        $tabs = array(
            'dashboard' => __('Dashboard', 'ai-botkit-for-lead-generation'),
            'chatbots' => __('My Bots', 'ai-botkit-for-lead-generation'),
            'analytics' => __('Analytics', 'ai-botkit-for-lead-generation'),
            'content-sync' => __('Content Sync', 'ai-botkit-for-lead-generation'),
            'pep-integration' => __('PEP Integration', 'ai-botkit-for-lead-generation'),
        );

        // Get current tab
        $this->tab = isset($_GET['tab']) ? sanitize_key($_GET['tab']) : 'chatbots';
        
        // Verify nonce if provided
        if (isset($_GET['nonce'])) {
            $nonce = sanitize_key($_GET['nonce']);
            if (!wp_verify_nonce($nonce, 'ai_botkit_chatbots')) {
                wp_die(__('Security check failed. Please refresh the page and try again.', 'ai-botkit-for-lead-generation'));
            }
        }

        switch ($this->tab) {
            case 'dashboard':
                require_once AI_BOTKIT_PLUGIN_DIR . 'admin/views/dashboard.php';
                break;
            case 'onboarding':
                require_once AI_BOTKIT_PLUGIN_DIR . 'admin/views/onboarding.php';
                break;
            case 'chatbots':
                // nonce check. only check if bot_id is set else request from wp-admin menu item
                if ( isset($_GET['bot_id']) && ( !isset($_GET['nonce']) || !wp_verify_nonce( sanitize_text_field( wp_unslash ( $_GET['nonce'] ) ), 'ai_botkit_chatbots' ) ) ) {
                    wp_die(__('Invalid request', 'ai-botkit-for-lead-generation'));
                }
                $bot_id = isset($_GET['bot_id']) ? sanitize_text_field($_GET['bot_id']) : null;
                $chat_session_id = isset($_GET['chat_session_id']) ? sanitize_text_field($_GET['chat_session_id']) : null;
                if ($bot_id && empty($chat_session_id)) {
                    require_once AI_BOTKIT_PLUGIN_DIR . 'admin/views/chatbot-sessions.php';
                } elseif ($chat_session_id) {
                    require_once AI_BOTKIT_PLUGIN_DIR . 'admin/views/chat-session.php';
                } else {
                    require_once AI_BOTKIT_PLUGIN_DIR . 'admin/views/chatbots.php';
                }
                break;
            case 'analytics':
                require_once AI_BOTKIT_PLUGIN_DIR . 'admin/views/analytics.php';
                break;
            case 'content-sync':
                require_once AI_BOTKIT_PLUGIN_DIR . 'admin/views/content-sync.php';
                break;
            case 'pep-integration':
                require_once AI_BOTKIT_PLUGIN_DIR . 'admin/views/pep-integration.php';
                break;
            default:
                require_once AI_BOTKIT_PLUGIN_DIR . 'admin/views/chatbots.php';
                break;
        }
        $this->after_main_content();

    }

    /**
     * Helper methods
     */
    private function is_plugin_page($hook) {
        return strpos($hook, 'ai-botkit') !== false;
    }

    private function get_current_page() {
        $screen = get_current_screen();
        if (!$screen) {
            return false;
        }
        return str_replace('ai-botkit-', '', $screen->id);
    }

    private function get_js_translations() {
        return array(
            'confirmDelete' => __('Are you sure you want to delete this item?', 'ai-botkit-for-lead-generation'),
            'confirmBulk' => __('Are you sure you want to perform this action?', 'ai-botkit-for-lead-generation'),
            'success' => __('Operation completed successfully.', 'ai-botkit-for-lead-generation'),
            'error' => __('An error occurred.', 'ai-botkit-for-lead-generation'),
            'loading' => __('Loading...', 'ai-botkit-for-lead-generation'),
            'saving' => __('Saving...', 'ai-botkit-for-lead-generation'),
            'deleting' => __('Deleting...', 'ai-botkit-for-lead-generation'),
            'processing' => __('Processing...', 'ai-botkit-for-lead-generation'),
            'addNewChatbot' => __('Add New Chatbot', 'ai-botkit-for-lead-generation'),
            'editChatbot' => __('Edit Chatbot', 'ai-botkit-for-lead-generation'),
            'confirmDeleteChatbot' => __('Are you sure you want to delete this chatbot?', 'ai-botkit-for-lead-generation'),
            'noDocumentsSelected' => __('No documents selected.', 'ai-botkit-for-lead-generation'),
            'noDocuments' => __('No documents found.', 'ai-botkit-for-lead-generation'),
            'remove' => __('Remove', 'ai-botkit-for-lead-generation'),
            'noApiKey' => __('API key is required.', 'ai-botkit-for-lead-generation'),
            'confirmReprocess' => __('Are you sure you want to reprocess this document?', 'ai-botkit-for-lead-generation'),
            'noSelection' => __('No selection made.', 'ai-botkit-for-lead-generation'),
            'invalidDateRange' => __('Invalid date range.', 'ai-botkit-for-lead-generation'),
            'confirmRemoveDocument' => __('Are you sure you want to remove this document?', 'ai-botkit-for-lead-generation'),
            'successChatbotSaved' => __('Chatbot saved successfully.', 'ai-botkit-for-lead-generation'),
            'errorChatbotSaved' => __('Error saving chatbot.', 'ai-botkit-for-lead-generation'),
            'showPreview' => __('Show Preview', 'ai-botkit-for-lead-generation'),
            'hidePreview' => __('Hide Preview', 'ai-botkit-for-lead-generation'),
        );
    }

    /**
     * Summary of before_main_content
     * @return void
     */
    private function before_main_content() {
        ?>
          <div class="ai-botkit-layout">
            <!-- Sidebar -->
            <div id="ai-botkit-sidebar" class="ai-botkit-sidebar-wrapper">
                <?php include_once AI_BOTKIT_PLUGIN_DIR . 'admin/views/sidebar.php'; ?>
            </div>
            <!-- Right section: topbar + main -->
            <div class="ai-botkit-main-content">
                <!-- Topbar -->
                <div class="ai-botkit-topbar">
                    <!-- Hamburger menu -->
                    <div class="ai-botkit-topbar-left">
                        <button id="ai-botkit-hamburger-menu" class="ai-botkit-hamburger-menu">
                            <i class="ti ti-menu-2"></i>
                        </button>
                    </div>
                    <!-- Title -->
                    <div class="ai-botkit-topbar-left">
                        <h1 class="ai-botkit-topbar-title"><?php esc_html_e('AI BotKit', 'ai-botkit-for-lead-generation'); ?></h1>
                    </div>
                </div>
                <!-- Main Content -->
                <main class="ai-botkit-main">
            <?php
    }

    /**
     * Summary of after_main_content
     * @return void
     */
    private function after_main_content() {
        ?>
                </main>
            </div>
        </div>
        <?php
    }

    /**
     * Handle post sync settings form submission
     */
    public function handle_post_sync_settings(): void {
        if (!isset($_POST['ai_botkit_post_sync_settings']) || !wp_verify_nonce($_POST['ai_botkit_post_sync_nonce'], 'ai_botkit_post_sync_settings')) {
            return;
        }

        if (!current_user_can('manage_options')) {
            return;
        }

        $enabled_post_types = isset($_POST['enabled_post_types']) ? array_map('sanitize_text_field', $_POST['enabled_post_types']) : [];
        $sync_settings = [
            'enabled_post_types' => $enabled_post_types,
            'auto_sync' => isset($_POST['auto_sync']) ? 1 : 0
        ];

        \AI_BotKit\Integration\API_Handler::save_sync_settings($sync_settings);

        add_action('admin_notices', function() {
            echo '<div class="notice notice-success is-dismissible"><p>' .
                 __('Post sync settings saved successfully!', 'ai-botkit-for-lead-generation') .
                 '</p></div>';
        });
    }

    /**
     * Handle PEP settings form submission
     */
    public function handle_pep_settings(): void {
        if (!isset($_POST['ai_botkit_pep_settings']) || !wp_verify_nonce($_POST['ai_botkit_pep_nonce'], 'ai_botkit_pep_settings')) {
            return;
        }

        if (!current_user_can('manage_options')) {
            return;
        }

        $pep_settings = [
            'enabled' => isset($_POST['pep_enabled']) ? true : false,
            'button_mode' => isset($_POST['pep_button_mode']) ? sanitize_text_field($_POST['pep_button_mode']) : 'new',
            'button_label' => isset($_POST['pep_button_label']) ? sanitize_text_field($_POST['pep_button_label']) : __('Get Quote', 'ai-botkit-for-lead-generation'),
            'button_position' => isset($_POST['pep_button_position']) ? sanitize_text_field($_POST['pep_button_position']) : 'after_add_to_cart',
            'chatbot_id' => isset($_POST['pep_chatbot_id']) ? sanitize_text_field($_POST['pep_chatbot_id']) : '',
        ];

        update_option('ai_botkit_pep_settings', $pep_settings);

        // Cache the selected chatbot's primary color for frontend button styling
        $this->cache_pep_chatbot_style($pep_settings['chatbot_id'] ?? '');

        add_action('admin_notices', function() {
            echo '<div class="notice notice-success is-dismissible"><p>' .
                 __('PEP settings saved successfully!', 'ai-botkit-for-lead-generation') .
                 '</p></div>';
        });
    }

    /**
     * Fetch and cache the selected chatbot's style (primary color) for PEP button theming.
     *
     * @param string $chatbot_namespace The chatbot namespace selected in PEP settings.
     */
    private function cache_pep_chatbot_style(string $chatbot_namespace): void {
        if (empty($chatbot_namespace)) {
            delete_option('ai_botkit_pep_chatbot_style');
            return;
        }

        $api_handler = new \AI_BotKit\Integration\API_Handler();
        $chatbots_data = $api_handler->send_get_request('chatbots');
        $chatbots = isset($chatbots_data['data']) ? $chatbots_data['data'] : [];

        foreach ($chatbots as $chatbot) {
            $ns = isset($chatbot['messagesTemplate']['namespace']) ? $chatbot['messagesTemplate']['namespace'] : '';
            if ($ns === $chatbot_namespace) {
                $style = isset($chatbot['style']) && is_array($chatbot['style']) ? $chatbot['style'] : [];
                update_option('ai_botkit_pep_chatbot_style', $style);
                return;
            }
        }

        delete_option('ai_botkit_pep_chatbot_style');
    }

}