<?php
/**
 * AI Auto Tool - Floating Robot Widget
 * 
 * Displays a floating robot that roams the admin area, analyzes elements,
 * and opens the bot assistant chat when clicked.
 * 
 * @package AI Auto Tool
 * @version 1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Thoát nếu truy cập trực tiếp

class AIautotool_Floating_Robot_Widget {
    
    private $enqueued = false;
    
    public function __construct() {
        // Ensure bot assistant is active by default (if not set)
        if (get_option('aiautotool_bot_assistant_active') === false) {
            update_option('aiautotool_bot_assistant_active', 'true');
        }
        
        // Add hooks with higher priority to ensure they run
        add_action('admin_footer', array($this, 'render_robot_widget'), 999);
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'), 999);
        
        // Also add CSS to admin head for better reliability
        add_action('admin_head', array($this, 'add_css_to_head'), 999);
        
        // AJAX handler to get bot name
        add_action('wp_ajax_get_bot_name', array($this, 'get_bot_name'));
        add_action('wp_ajax_get_standalone_chat_info', array($this, 'get_standalone_chat_info'));
    }
    
    /**
     * Enqueue scripts and styles for floating robot
     */
    public function enqueue_scripts($hook) {
        // Only load on admin pages
        if (!is_admin()) {
            return;
        }
        
        // Check if bot assistant is active - default is true
        $bot_active = get_option('aiautotool_bot_assistant_active', true);
        // Allow both string 'true' and boolean true
        if ($bot_active !== 'true' && $bot_active !== true && $bot_active !== '1') {
            return;
        }
        
        // Prevent duplicate enqueueing
        if ($this->enqueued) {
            return;
        }
        
        // Always enqueue styles and scripts for floating robot
        // (they are needed when modal opens)
        
        // Use correct path: files are in inc/bot-assistant/assets/
        $assets_url = plugin_dir_url(__FILE__) . 'assets/';
        $plugin_url = plugin_dir_url(dirname(dirname(__FILE__)));
        
        // Enqueue Font Awesome for icons
        wp_enqueue_style(
            'font-awesome',
            $plugin_url . 'js/fontawesome/css/all.min.css',
            array(),
            defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '7.1.0'
        );
        
        // Enqueue robot CSS with higher priority and force loading
        wp_enqueue_style(
            'floating-robot-style',
            $assets_url . 'css/floating-robot.css',
            array('font-awesome'),
            time()
        );
        
        // Add inline CSS as fallback to ensure styles are always available
        $this->add_inline_css_fallback();
        
        // Also enqueue bot assistant CSS for standalone chat
        wp_enqueue_style(
            'bot-assistant-style-modal',
            $assets_url . 'css/bot-assistant.css',
            array(),
            time()
        );
        
        wp_enqueue_style(
            'execute-plan-button-style-modal',
            $assets_url . 'css/execute-plan-button.css',
            array(),
            time()
        );
        
        wp_enqueue_style(
            'cursor-thinking-phases-style-modal',
            $assets_url . 'css/cursor-thinking-phases.css',
            array(),
            time()
        );
        
        // Cursor-style chat interface for standalone chat (load after bot-assistant for proper precedence)
        wp_enqueue_style(
            'cursor-style-chat-modal',
            $assets_url . 'css/cursor-style-chat.css',
            array('bot-assistant-style-modal'),
            time()
        );
        
        // Enqueue robot JS
        wp_enqueue_script(
            'floating-robot-script',
            $assets_url . 'js/floating-robot.js',
            array('jquery'),
            time(),
            true
        );
        
        // Also enqueue bot assistant JS for standalone chat
        wp_enqueue_script(
            'bot-assistant-script-modal',
            $assets_url . 'js/bot-assistant.js?v=' . time(),
            array('jquery'),
            time(),
            true
        );
        
        // Cursor-style chat JavaScript
        wp_enqueue_script(
            'cursor-style-chat-script-modal',
            $assets_url . 'js/cursor-style-chat.js',
            array('jquery'),
            time(),
            true
        );
        
        // Localize bot assistant data
        wp_localize_script('floating-robot-script', 'botAssistantData', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('bot_assistant_nonce'),
            'strings' => array(
                'askMe' => __('Ask me anything about your site...', 'ai-auto-tool'),
                'searching' => __('Searching...', 'ai-auto-tool'),
                'analyzing' => __('Analyzing...', 'ai-auto-tool'),
            )
        ));
        
        // Localize script with data - Correct image path
        wp_localize_script('floating-robot-script', 'floatingRobotData', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('floating_robot_nonce'),
            'robotImageUrl' => $assets_url . 'images/robotai.gif',
            'botAssistantPageUrl' => admin_url('admin.php?page=aiautotool-bot-assistant'),
        ));
        
        // Mark as enqueued
        $this->enqueued = true;
    }
    
    /**
     * Add inline CSS fallback to ensure styles are always available
     */
    private function add_inline_css_fallback() {
        $fallback_css = '
        <style id="floating-robot-fallback-css">
        #ai-floating-robot {
            position: fixed !important;
            width: 100px !important;
            height: 100px !important;
            z-index: 999998 !important;
            cursor: pointer !important;
            user-select: none !important;
            transition: transform 0.3s ease !important;
            pointer-events: all !important;
        }
        #ai-floating-robot:hover:not(.minimized) {
            transform: scale(1.1) !important;
        }
        .robot-hide-btn {
            position: absolute !important;
            top: -10px !important;
            right: -10px !important;
            width: 32px !important;
            height: 32px !important;
            background: rgba(255, 255, 255, 0.9) !important;
            border: 2px solid #667eea !important;
            border-radius: 50% !important;
            cursor: pointer !important;
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
            opacity: 0 !important;
            visibility: hidden !important;
            transition: all 0.3s ease !important;
            z-index: 999999 !important;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2) !important;
            padding: 0 !important;
        }
        #ai-floating-robot:hover:not(.minimized) .robot-hide-btn {
            opacity: 1 !important;
            visibility: visible !important;
        }
        .robot-hide-btn:hover {
            background: #667eea !important;
            color: white !important;
            transform: scale(1.1) !important;
        }
        .robot-hide-btn .dashicons {
            width: 18px !important;
            height: 18px !important;
            font-size: 18px !important;
            line-height: 1 !important;
            color: #667eea !important;
        }
        .robot-hide-btn:hover .dashicons {
            color: white !important;
        }
        #ai-floating-robot.minimized {
            width: 50px !important;
            height: 50px !important;
            transition: all 0.5s ease !important;
            top: 20px !important;
            right: 20px !important;
            left: auto !important;
        }
        #ai-floating-robot.minimized .robot-container {
            animation: none !important;
        }
        #ai-floating-robot.minimized .robot-glow,
        #ai-floating-robot.minimized .robot-tooltip,
        #ai-floating-robot.minimized .robot-hide-btn {
            display: none !important;
        }
        #ai-floating-robot.minimized:hover {
            transform: scale(1.15) !important;
        }
        .robot-ripple-container {
            position: absolute !important;
            top: 50% !important;
            left: 50% !important;
            transform: translate(-50%, -50%) !important;
            width: 50px !important;
            height: 50px !important;
            pointer-events: none !important;
            z-index: 1 !important;
        }
        .robot-ripple-pulse {
            position: absolute !important;
            top: 50% !important;
            left: 50% !important;
            transform: translate(-50%, -50%) !important;
            width: 50px !important;
            height: 50px !important;
            background: radial-gradient(circle, rgba(102, 126, 234, 0.8) 0%, rgba(118, 75, 162, 0.4) 50%, transparent 100%) !important;
            border-radius: 50% !important;
            animation: pulse-glow-center 2s ease-in-out infinite !important;
            pointer-events: none !important;
            z-index: 2 !important;
        }
        @keyframes pulse-glow-center {
            0%, 100% {
                transform: translate(-50%, -50%) scale(1) !important;
                opacity: 0.8 !important;
            }
            50% {
                transform: translate(-50%, -50%) scale(1.3) !important;
                opacity: 0.4 !important;
            }
        }
        .robot-ripple-wave {
            position: absolute !important;
            top: 50% !important;
            left: 50% !important;
            transform: translate(-50%, -50%) scale(1) !important;
            width: 50px !important;
            height: 50px !important;
            border-radius: 50% !important;
            pointer-events: none !important;
            z-index: 1 !important;
        }
        .robot-ripple-wave::before {
            content: \'\' !important;
            position: absolute !important;
            top: 0 !important;
            left: 0 !important;
            width: 100% !important;
            height: 100% !important;
            border: 3px solid transparent !important;
            border-radius: 50% !important;
            background: linear-gradient(135deg, rgba(102, 126, 234, 0.9) 0%, rgba(118, 75, 162, 0.7) 50%, rgba(102, 126, 234, 0.5) 100%) !important;
            -webkit-mask: radial-gradient(circle, transparent 48%, black 49%, black 51%, transparent 52%) !important;
            mask: radial-gradient(circle, transparent 48%, black 49%, black 51%, transparent 52%) !important;
            animation: ripple-expand-primary 2.5s cubic-bezier(0.4, 0, 0.2, 1) infinite !important;
            box-shadow: 0 0 20px rgba(102, 126, 234, 0.6), 0 0 40px rgba(118, 75, 162, 0.4), inset 0 0 20px rgba(102, 126, 234, 0.3) !important;
        }
        .robot-ripple-wave::after {
            content: \'\' !important;
            position: absolute !important;
            top: 0 !important;
            left: 0 !important;
            width: 100% !important;
            height: 100% !important;
            border: 2px solid rgba(102, 126, 234, 0.4) !important;
            border-radius: 50% !important;
            animation: ripple-expand-secondary 2.5s cubic-bezier(0.4, 0, 0.2, 1) infinite !important;
            box-shadow: 0 0 15px rgba(102, 126, 234, 0.5) !important;
        }
        @keyframes ripple-expand-primary {
            0% {
                transform: scale(1) !important;
                opacity: 1 !important;
                filter: blur(0px) !important;
            }
            30% {
                opacity: 0.9 !important;
                filter: blur(1px) !important;
            }
            70% {
                opacity: 0.5 !important;
                filter: blur(2px) !important;
            }
            100% {
                transform: scale(4.5) !important;
                opacity: 0 !important;
                filter: blur(4px) !important;
            }
        }
        @keyframes ripple-expand-secondary {
            0% {
                transform: scale(1) !important;
                opacity: 0.8 !important;
                filter: blur(0px) !important;
            }
            50% {
                opacity: 0.4 !important;
                filter: blur(1px) !important;
            }
            100% {
                transform: scale(5) !important;
                opacity: 0 !important;
                filter: blur(3px) !important;
            }
        }
        .robot-ripple-wave:nth-of-type(1)::before,
        .robot-ripple-wave:nth-of-type(1)::after {
            animation-delay: 0s !important;
        }
        .robot-ripple-wave:nth-of-type(2)::before,
        .robot-ripple-wave:nth-of-type(2)::after {
            animation-delay: 0.8s !important;
        }
        .robot-ripple-wave:nth-of-type(3)::before,
        .robot-ripple-wave:nth-of-type(3)::after {
            animation-delay: 1.6s !important;
        }
        .robot-container {
            position: relative !important;
            width: 100% !important;
            height: 100% !important;
            animation: float 3s ease-in-out infinite !important;
        }
        .robot-icon {
            width: 100% !important;
            height: 100% !important;
            object-fit: contain !important;
            filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.15)) !important;
        }
        @keyframes float {
            0%, 100% { transform: translateY(0px) !important; }
            50% { transform: translateY(-10px) !important; }
        }
        .robot-glow {
            position: absolute !important;
            top: 50% !important;
            left: 50% !important;
            transform: translate(-50%, -50%) !important;
            width: 80px !important;
            height: 80px !important;
            background: radial-gradient(circle, rgba(102, 126, 234, 0.3) 0%, transparent 70%) !important;
            border-radius: 50% !important;
            animation: pulse-glow 2s ease-in-out infinite !important;
            pointer-events: none !important;
        }
        @keyframes pulse-glow {
            0%, 100% {
                opacity: 0.5 !important;
                transform: translate(-50%, -50%) scale(1) !important;
            }
            50% {
                opacity: 0.8 !important;
                transform: translate(-50%, -50%) scale(1.2) !important;
            }
        }
        .robot-tooltip {
            position: absolute !important;
            bottom: 80px !important;
            left: 50% !important;
            transform: translateX(-50%) !important;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
            color: white !important;
            padding: 12px 16px !important;
            border-radius: 12px !important;
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3) !important;
            white-space: nowrap !important;
            opacity: 0 !important;
            visibility: hidden !important;
            pointer-events: none !important;
            transition: all 0.3s ease !important;
            font-size: 13px !important;
            min-width: 200px !important;
        }
        .robot-tooltip.visible {
            opacity: 1 !important;
            visibility: visible !important;
            bottom: 90px !important;
        }
        .robot-chat-modal {
            position: fixed !important;
            top: 0 !important;
            left: 0 !important;
            width: 100% !important;
            height: 100% !important;
            background: rgba(0, 0, 0, 0.7) !important;
            z-index: 999999 !important;
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
            opacity: 0 !important;
            visibility: hidden !important;
            transition: all 0.3s ease !important;
            backdrop-filter: blur(5px) !important;
        }
        .robot-chat-modal.active {
            opacity: 1 !important;
            visibility: visible !important;
        }
        </style>';
        
        echo $fallback_css;
    }
    
    /**
     * Add CSS directly to admin head for better reliability
     */
    public function add_css_to_head() {
        // Only add CSS to admin pages
        if (!is_admin()) {
            return;
        }
        
        // Check if bot assistant is active - default true
        $bot_active = get_option('aiautotool_bot_assistant_active', true);
        // Allow both string 'true' and boolean true
        if ($bot_active !== 'true' && $bot_active !== true && $bot_active !== '1') {
            return;
        }
        
        // Use correct path: files are in inc/bot-assistant/assets/
        $assets_url = plugin_dir_url(__FILE__) . 'assets/';
        $plugin_url = plugin_dir_url(dirname(dirname(__FILE__)));
        
        // Add Font Awesome CSS first
        echo '<link rel="stylesheet" id="font-awesome-head" href="' . esc_url($plugin_url . 'js/fontawesome/css/all.min.css?v=' . (defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '7.1.0')) . '" type="text/css" media="all" />';
        
        // Add CSS link to head
        echo '<link rel="stylesheet" id="floating-robot-style-head" href="' . esc_url($assets_url . 'css/floating-robot.css?v=' . time()) . '" type="text/css" media="all" />';
        
        // Also add inline CSS as backup
        $this->add_inline_css_fallback();
    }
    
    /**
     * Get bot name from settings
     */
    public function get_bot_name() {
        check_ajax_referer('floating_robot_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $bot_name = get_option('aiautotool_bot_assistant_name', 'AIAUTOTOOL');
        
        wp_send_json_success(array('bot_name' => $bot_name));
    }
    
    /**
     * Get standalone chat info (lightweight AJAX endpoint)
     */
    public function get_standalone_chat_info() {
        check_ajax_referer('floating_robot_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $assistant_name = get_option('aiautotool_bot_assistant_name', 'AIAUTOTOOL');
        $role_intro = get_option('aiautotool_bot_assistant_role_intro', '');
        $use_ai = get_option('aiautotool_bot_assistant_use_ai', true);
        $has_ai = false;
        $provider_info = '';
        
        if ($use_ai && class_exists('AIAutotool_AI_Helper')) {
            $has_ai = AIAutotool_AI_Helper::is_available();
            if ($has_ai) {
                $ai_info = AIAutotool_AI_Helper::get_active_info();
                if ($ai_info) {
                    $provider_info = $ai_info['provider_name'] . ' - ' . $ai_info['model'];
                }
            }
        }
        
        wp_send_json_success(array(
            'assistant_name' => $assistant_name,
            'role_intro' => $role_intro,
            'has_ai' => $has_ai,
            'provider_info' => $provider_info
        ));
    }
    
    /**
     * Render the floating robot widget
     */
    public function render_robot_widget() {
        // Check if bot assistant is active - default true
        $bot_active = get_option('aiautotool_bot_assistant_active', true);
        // Allow both string 'true' and boolean true
        if ($bot_active !== 'true' && $bot_active !== true && $bot_active !== '1') {
            return;
        }
        
        // Also check if we're on bot assistant page - hide widget there
        $current_screen = get_current_screen();
        if ($current_screen && strpos($current_screen->id, 'aiautotool-bot-assistant') !== false) {
            return;
        }
        
        // Ensure scripts are loaded even if admin_enqueue_scripts didn't fire
        // (some admin pages don't fire this hook)
        if (!$this->enqueued) {
            $this->enqueue_scripts_force();
        }
        
        // Get robot image URL - Correct path in assets folder
        $assets_url = plugin_dir_url(__FILE__) . 'assets/';
        $robot_image_url = $assets_url . 'images/robotai.gif';
        
        // Get bot assistant page URL
        $bot_assistant_url = admin_url('admin.php?page=aiautotool-bot-assistant');
        
        ?>
        <!-- Floating Robot Widget -->
        <div id="ai-floating-robot" class="ai-floating-robot" data-state="idle">
            <div class="robot-container">
                <img src="<?php echo esc_url($robot_image_url); ?>" alt="AI Bot" class="robot-icon" />
                <div class="robot-glow"></div>
            </div>
            
            <!-- Hide button - appears on hover -->
            <button class="robot-hide-btn" title="<?php _e('Hide Robot', 'ai-auto-tool'); ?>">
                <span class="dashicons dashicons-arrow-down-alt2"></span>
            </button>
            
            <!-- Tooltip with suggestions -->
            <div class="robot-tooltip">
                <div class="robot-tooltip-content">
                    <div class="robot-name">🤖 <span class="bot-name-display">AIAUTOTOOL</span></div>
                    <div class="robot-status">Đang phân tích giao diện...</div>
                </div>
            </div>
            
            <!-- Pulse effect when analyzing -->
            <div class="robot-pulse"></div>
        </div>
        
        <!-- Chat Modal Overlay -->
        <div id="robot-chat-modal" class="robot-chat-modal">
            <div class="robot-chat-modal-content">
                <div class="robot-chat-modal-header">
                    <div class="modal-header-content">
                        <h2>
                            <span class="robot-icon-small">🤖</span>
                            <span class="bot-name-header">AIAUTOTOOL</span> <?php _e('Assistant', 'ai-auto-tool'); ?>
                        </h2>
                        <p class="modal-description"><?php _e('How can I help you?', 'ai-auto-tool'); ?></p>
                    </div>
                    <button class="robot-chat-close" title="<?php _e('Close', 'ai-auto-tool'); ?>">
                        <span class="dashicons dashicons-no-alt"></span>
                    </button>
                </div>
                
                <div class="robot-chat-modal-body">
                    <div class="robot-chat-loading">
                        <div class="loading-spinner"></div>
                        <p><?php _e('Loading chat...', 'ai-auto-tool'); ?></p>
                    </div>
                    <div class="robot-chat-content" id="robot-chat-content" style="display: none;"></div>
                </div>
            </div>
        </div>
        <?php
    }
    
    /**
     * Force enqueue scripts directly in footer if not already enqueued
     * This ensures scripts load on all admin pages
     */
    private function enqueue_scripts_force() {
        if ($this->enqueued) {
            return;
        }
        
        $assets_url = plugin_dir_url(__FILE__) . 'assets/';
        $plugin_url = plugin_dir_url(dirname(dirname(__FILE__)));
        
        // Output Font Awesome CSS first
        echo '<link rel="stylesheet" href="' . esc_url($plugin_url . 'js/fontawesome/css/all.min.css?v=' . (defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '7.1.0')) . '" type="text/css" media="all" />';
        
        // Output CSS directly in footer
        echo '<link rel="stylesheet" href="' . esc_url($assets_url . 'css/floating-robot.css?v=' . time()) . '" type="text/css" media="all" />';
        echo '<link rel="stylesheet" href="' . esc_url($assets_url . 'css/bot-assistant.css?v=' . time()) . '" type="text/css" media="all" />';
        echo '<link rel="stylesheet" href="' . esc_url($assets_url . 'css/execute-plan-button.css?v=' . time()) . '" type="text/css" media="all" />';
        echo '<link rel="stylesheet" href="' . esc_url($assets_url . 'css/cursor-thinking-phases.css?v=' . time()) . '" type="text/css" media="all" />';
        echo '<link rel="stylesheet" href="' . esc_url($assets_url . 'css/cursor-style-chat.css?v=' . time()) . '" type="text/css" media="all" />';
        
        // Prepare JS data
        $floating_robot_data = array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('floating_robot_nonce'),
            'robotImageUrl' => $assets_url . 'images/robotai.gif',
            'botAssistantPageUrl' => admin_url('admin.php?page=aiautotool-bot-assistant'),
        );
        
        $bot_assistant_data = array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('bot_assistant_nonce'),
            'strings' => array(
                'askMe' => __('Ask me anything about your site...', 'ai-auto-tool'),
                'searching' => __('Searching...', 'ai-auto-tool'),
                'analyzing' => __('Analyzing...', 'ai-auto-tool'),
            )
        );
        
        // Output JS - ensure jQuery is loaded first
        echo '<script type="text/javascript">';
        echo '(function() {';
        echo 'if (typeof jQuery === "undefined") {';
        echo 'var script = document.createElement("script");';
        echo 'script.src = "' . esc_url(includes_url('js/jquery/jquery.min.js')) . '";';
        echo 'script.onload = function() { loadFloatingRobot(); };';
        echo 'document.head.appendChild(script);';
        echo '} else {';
        echo 'loadFloatingRobot();';
        echo '}';
        echo 'function loadFloatingRobot() {';
        echo 'if (typeof floatingRobotData === "undefined") {';
        echo 'window.floatingRobotData = ' . wp_json_encode($floating_robot_data) . ';';
        echo 'window.botAssistantData = ' . wp_json_encode($bot_assistant_data) . ';';
        echo '}';
        echo 'var script1 = document.createElement("script");';
        echo 'script1.src = "' . esc_url($assets_url . 'js/floating-robot.js?v=' . time()) . '";';
        echo 'document.body.appendChild(script1);';
        echo 'var script2 = document.createElement("script");';
        echo 'script2.src = "' . esc_url($assets_url . 'js/bot-assistant.js?v=' . time()) . '";';
        echo 'document.body.appendChild(script2);';
        echo 'var script3 = document.createElement("script");';
        echo 'script3.src = "' . esc_url($assets_url . 'js/cursor-style-chat.js?v=' . time()) . '";';
        echo 'document.body.appendChild(script3);';
        echo '}';
        echo '})();';
        echo '</script>';
        
        $this->enqueued = true;
    }
}

// Initialize the widget immediately when file is loaded
// This ensures hooks are registered before admin_enqueue_scripts fires
if (!class_exists('AIautotool_Floating_Robot_Widget_Instance')) {
    class AIautotool_Floating_Robot_Widget_Instance {
        private static $instance = null;
        
        public static function get_instance() {
            if (self::$instance === null) {
                self::$instance = new AIautotool_Floating_Robot_Widget();
            }
            return self::$instance;
        }
    }
    
    // Initialize immediately - this will register hooks
    AIautotool_Floating_Robot_Widget_Instance::get_instance();
}

