<?php

/**
 * AI Magic Admin Bar and Slide Panel
 *
 * @link       https://insya.com/ai-magic
 * @since      1.0.7
 *
 * @package    Ai_Magic
 * @subpackage Ai_Magic/admin
 */
class AI_Magic_Admin_Bar
{
    public function __construct()
    {
        add_action('admin_bar_menu', array($this, 'add_admin_bar_item'), 100);
        add_action('admin_footer', array($this, 'render_slide_panel'));
        add_action('wp_footer', array($this, 'render_slide_panel'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_assets'));
        add_action('wp_enqueue_scripts', array($this, 'enqueue_assets'));

        // AJAX handlers
        add_action('wp_ajax_ai_magic_chat_message', array($this, 'handle_chat_message'));
        add_action('wp_ajax_ai_magic_generate_meta', array($this, 'handle_generate_meta'));
        add_action('wp_ajax_ai_magic_extract_keywords', array($this, 'handle_extract_keywords'));
    }

    /**
     * Add AI Magic icon to admin bar (top right)
     */
    public function add_admin_bar_item($admin_bar)
    {
        if (!current_user_can('edit_posts')) {
            return;
        }

        $admin_bar->add_menu(array(
            'id' => 'ai-magic-chat',
            'parent' => 'top-secondary', // This places it on the right side
            'title' => '<span class="dashicons dashicons-admin-comments"></span>',
            'href' => '#',
            'meta' => array(
                'title' => 'AI Magic Assistant',
                'class' => 'ai-magic-admin-bar-item',
            ),
        ));
    }

    /**
     * Render slide panel
     */
    public function render_slide_panel()
    {
        if (!current_user_can('edit_posts')) {
            return;
        }

        // Load required classes
        require_once plugin_dir_path(dirname(__FILE__)) . 'admin/class-ai-magic-templates.php';
        require_once plugin_dir_path(dirname(__FILE__)) . 'admin/class-ai-magic-seo.php';
        require_once plugin_dir_path(dirname(__FILE__)) . 'admin/class-ai-magic-history.php';

        // Get data
        $templates = Ai_Magic_Templates::get_templates();
        $seo_plugin = Ai_Magic_SEO::get_seo_plugin_name();
        $history_count = Ai_Magic_History::get_count(get_current_user_id());

        ?>
        <!-- AI Magic Slide Panel -->
        <div id="ai-magic-slide-panel" class="ai-magic-slide-panel">
            <div class="ai-magic-panel-overlay"></div>
            <div class="ai-magic-panel-content">
                <!-- Panel Header -->
                <div class="ai-magic-panel-header">
                    <div class="ai-magic-panel-title">
                        <span class="dashicons dashicons-admin-comments"></span>
                        <h2>AI Magic Assistant</h2>
                    </div>
                    <button type="button" class="ai-magic-panel-close">
                        <span class="dashicons dashicons-no-alt"></span>
                    </button>
                </div>

                <!-- Provider Selector -->
                <?php
                $active_providers = [];
                $providers = ['openai', 'anthropic', 'google', 'openrouter'];
                foreach ($providers as $provider) {
                    if (get_option("ai_magic_{$provider}_active", $provider === 'openai' ? 'yes' : 'no') === 'yes') {
                        $active_providers[] = $provider;
                    }
                }

                // Default to OpenAI if no active providers
                if (empty($active_providers)) {
                    $active_providers[] = 'openai';
                }

                $current_provider = isset($active_providers[0]) ? $active_providers[0] : 'openai';
                ?>
                <div class="ai-magic-chat-toolbar">
                    <select id="ai-magic-chat-provider" class="ai-magic-provider-select">
                        <?php foreach ($active_providers as $provider):
                            $name = '';
                            switch ($provider) {
                                case 'openai':
                                    $name = 'OpenAI (GPT)';
                                    break;
                                case 'anthropic':
                                    $name = 'Anthropic (Claude)';
                                    break;
                                case 'google':
                                    $name = 'Google (Gemini)';
                                    break;
                                case 'openrouter':
                                    $name = 'OpenRouter';
                                    break;
                            }
                            ?>
                            <option value="<?php echo esc_attr($provider); ?>"><?php echo esc_html($name); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- Chat Messages -->
                <div class="ai-magic-chat-messages" id="ai-magic-messages">
                    <!-- Welcome Message -->
                    <div class="ai-magic-message ai">
                        <div class="ai-magic-message-avatar">
                            <span class="dashicons dashicons-admin-comments"></span>
                        </div>
                        <div class="ai-magic-message-content">
                            <div class="ai-magic-message-text">
                                <strong>Hello!</strong> 👋 How can I help you?
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Input Area -->
                <div class="ai-magic-chat-input">
                    <div class="ai-magic-input-wrapper">
                        <textarea id="ai-magic-chat-input" class="ai-magic-textarea" placeholder="Type your message..."
                            rows="1"></textarea>

                        <button type="button" id="ai-magic-send-btn" class="ai-magic-send-btn">
                            <span class="dashicons dashicons-arrow-right-alt2"></span>
                        </button>
                    </div>
                </div>

                <!-- Footer Stats -->
                <div class="ai-magic-chat-footer">
                    <div class="ai-magic-footer-stat">
                        <span class="dashicons dashicons-chart-bar"></span>
                        <span>Total: <strong><?php echo number_format($history_count); ?></strong></span>
                    </div>
                    <div class="ai-magic-footer-stat">
                        <span class="dashicons dashicons-admin-plugins"></span>
                        <span>SEO: <strong><?php echo esc_html($seo_plugin); ?></strong></span>
                    </div>
                </div>
            </div>
        </div>

        <style>
            /* Slide Panel Styles */
            .ai-magic-slide-panel {
                position: fixed !important;
                top: 0 !important;
                right: -100%;
                width: 100%;
                height: 100vh !important;
                z-index: 999999999 !important;
                transition: right 0.3s ease-in-out;
                pointer-events: none;
            }

            .ai-magic-slide-panel.active {
                right: 0;
                pointer-events: all;
            }

            .ai-magic-panel-overlay {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.5);
                opacity: 0;
                transition: opacity 0.3s ease-in-out;
                z-index: 1;
            }

            .ai-magic-slide-panel.active .ai-magic-panel-overlay {
                opacity: 1;
            }

            .ai-magic-panel-content {
                position: absolute;
                top: 0;
                right: 0;
                width: 420px;
                max-width: 90%;
                height: 100%;
                background: #fff;
                box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
                display: flex;
                flex-direction: column;
                transform: translateX(100%);
                transition: transform 0.3s ease-in-out;
                z-index: 2;
            }

            .ai-magic-slide-panel.active .ai-magic-panel-content {
                transform: translateX(0);
            }

            /* Panel Header */
            .ai-magic-panel-header {
                background: #c8ff2a;
                color: #000;
                padding: 16px 20px;
                display: flex;
                align-items: center;
                justify-content: space-between;
                border-bottom: 1px solid #a8d922;
            }

            .ai-magic-panel-title {
                display: flex;
                align-items: center;
                gap: 10px;
            }

            .ai-magic-panel-title h2 {
                margin: 0;
                font-size: 16px;
                font-weight: 600;
                color: #000;
            }

            .ai-magic-panel-title .dashicons {
                font-size: 24px;
                width: 24px;
                height: 24px;
            }

            .ai-magic-panel-close {
                background: transparent;
                border: none;
                color: #000;
                cursor: pointer;
                padding: 4px;
                display: flex;
                align-items: center;
                justify-content: center;
                border-radius: 4px;
                transition: background 0.2s;
            }

            .ai-magic-panel-close:hover {
                background: rgba(0, 0, 0, 0.1);
            }

            .ai-magic-panel-close .dashicons {
                font-size: 20px;
                width: 20px;
                height: 20px;
            }

            /* Chat Messages */
            .ai-magic-chat-messages {
                flex: 1;
                overflow-y: auto;
                padding: 20px;
                background: #f0f0f1;
            }

            .ai-magic-message {
                margin-bottom: 16px;
                display: flex;
                gap: 12px;
                animation: slideIn 0.3s ease-out;
            }

            @keyframes slideIn {
                from {
                    opacity: 0;
                    transform: translateY(10px);
                }

                to {
                    opacity: 1;
                    transform: translateY(0);
                }
            }

            .ai-magic-message-avatar {
                width: 36px;
                height: 36px;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                flex-shrink: 0;
                background: #c8ff2a;
                color: #000;
            }

            .ai-magic-message.user .ai-magic-message-avatar {
                background: #dcdcde;
                color: #50575e;
            }

            .ai-magic-message-avatar .dashicons {
                font-size: 20px;
                width: 20px;
                height: 20px;
            }

            .ai-magic-message-content {
                flex: 1;
            }

            .ai-magic-message-text {
                background: #fff;
                padding: 12px 16px;
                border-radius: 8px;
                font-size: 14px;
                line-height: 1.5;
                border: 1px solid #dcdcde;
            }

            .ai-magic-message.ai .ai-magic-message-text {
                background: #f0f6fc;
                border-color: #c3e6ff;
            }

            .ai-magic-message-time {
                font-size: 11px;
                color: #787c82;
                margin-top: 4px;
                padding-left: 16px;
            }

            /* Collapsible Sections */
            .ai-magic-collapsible-section {
                border-bottom: 1px solid #dcdcde;
            }

            .ai-magic-section-toggle {
                width: 100%;
                background: #fff;
                border: none;
                padding: 12px 20px;
                display: flex;
                align-items: center;
                gap: 8px;
                cursor: pointer;
                font-size: 13px;
                font-weight: 600;
                color: #2c3338;
                transition: background 0.2s;
                text-align: left;
            }

            .ai-magic-section-toggle:hover {
                background: #f6f7f7;
            }

            .ai-magic-section-toggle .dashicons {
                font-size: 18px;
                width: 18px;
                height: 18px;
                transition: transform 0.2s;
            }

            .ai-magic-section-toggle.active .dashicons {
                transform: rotate(180deg);
            }

            .ai-magic-section-content {
                padding: 12px 20px;
                background: #f6f7f7;
            }

            .ai-magic-action-buttons {
                display: grid;
                grid-template-columns: repeat(2, 1fr);
                gap: 8px;
            }

            .ai-magic-action-btn {
                background: #fff;
                border: 1px solid #c3c4c7;
                padding: 8px 12px;
                border-radius: 4px;
                font-size: 12px;
                cursor: pointer;
                transition: all 0.2s;
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 6px;
                color: #2c3338;
            }

            .ai-magic-action-btn:hover {
                background: #f0f0f1;
                border-color: #c8ff2a;
                color: #000;
            }

            .ai-magic-action-btn .dashicons {
                font-size: 14px;
                width: 14px;
                height: 14px;
            }

            .ai-magic-template-select {
                width: 100%;
                padding: 8px 10px;
                border: 1px solid #8c8f94;
                border-radius: 4px;
                font-size: 13px;
                background: #fff;
            }

            /* Quick Actions */
            .ai-magic-quick-actions {
                background: #fff;
                padding: 16px 20px;
                border-top: 1px solid #dcdcde;
            }

            .ai-magic-quick-actions-title {
                font-size: 11px;
                font-weight: 600;
                color: #646970;
                margin-bottom: 10px;
                text-transform: uppercase;
                letter-spacing: 0.5px;
            }

            .ai-magic-action-buttons {
                display: flex;
                gap: 8px;
                flex-wrap: wrap;
            }

            .ai-magic-action-btn {
                background: #f0f0f1;
                border: 1px solid #c3c4c7;
                padding: 6px 12px;
                border-radius: 4px;
                font-size: 13px;
                cursor: pointer;
                transition: all 0.2s;
                display: inline-flex;
                align-items: center;
                gap: 6px;
                color: #2c3338;
            }

            .ai-magic-action-btn:hover {
                background: #fff;
                border-color: #c8ff2a;
                color: #000;
            }

            .ai-magic-action-btn .dashicons {
                font-size: 16px;
                width: 16px;
                height: 16px;
            }

            /* Input Area */
            .ai-magic-chat-input {
                background: #fff;
                padding: 12px 16px;
                border-top: 2px solid #dcdcde;
            }

            .ai-magic-input-wrapper {
                display: flex;
                gap: 8px;
                align-items: center;
            }

            .ai-magic-textarea {
                flex: 1;
                padding: 8px 12px;
                border: 1px solid #8c8f94;
                border-radius: 4px;
                font-size: 13px;
                resize: none;
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
                transition: border-color 0.2s;
                min-height: 36px;
                max-height: 100px;
            }

            .ai-magic-textarea:focus {
                outline: none;
                border-color: #c8ff2a;
                box-shadow: 0 0 0 1px #c8ff2a;
            }

            .ai-magic-send-btn {
                background: #c8ff2a;
                color: #000;
                border: none;
                padding: 8px;
                border-radius: 4px;
                cursor: pointer;
                transition: all 0.2s;
                display: flex;
                align-items: center;
                justify-content: center;
                min-width: 36px;
                height: 36px;
                flex-shrink: 0;
            }

            .ai-magic-send-btn:hover {
                background: #a8d922;
            }

            .ai-magic-send-btn:disabled {
                opacity: 0.6;
                cursor: not-allowed;
            }

            .ai-magic-send-btn .dashicons {
                font-size: 18px;
                width: 18px;
                height: 18px;
            }

            /* Footer Stats */
            .ai-magic-chat-footer {
                background: #f0f0f1;
                padding: 12px 20px;
                border-top: 1px solid #dcdcde;
                display: flex;
                justify-content: space-between;
                align-items: center;
                font-size: 12px;
                color: #646970;
            }

            .ai-magic-footer-stat {
                display: flex;
                align-items: center;
                gap: 6px;
            }

            .ai-magic-footer-stat .dashicons {
                font-size: 16px;
                width: 16px;
                height: 16px;
            }

            /* Typing Animation */
            .ai-magic-typing {
                display: none;
                padding: 12px 16px;
                background: #f0f6fc;
                border-radius: 8px;
                width: fit-content;
                border: 1px solid #c3e6ff;
            }

            .ai-magic-typing-dots {
                display: flex;
                gap: 4px;
            }

            .ai-magic-typing-dot {
                width: 8px;
                height: 8px;
                background: #c8ff2a;
                border-radius: 50%;
                animation: typing 1.4s infinite;
            }

            .ai-magic-typing-dot:nth-child(2) {
                animation-delay: 0.2s;
            }

            .ai-magic-typing-dot:nth-child(3) {
                animation-delay: 0.4s;
            }

            @keyframes typing {

                0%,
                60%,
                100% {
                    transform: translateY(0);
                }

                30% {
                    transform: translateY(-10px);
                }
            }

            /* Admin Bar Icon */
            #wpadminbar .ai-magic-admin-bar-item .ab-icon:before {
                content: "\f101";
                top: 2px;
            }

            #wpadminbar .ai-magic-admin-bar-item:hover .ab-icon:before {
                color: #72aee6;
            }

            /* Chat Toolbar */
            .ai-magic-chat-toolbar {
                padding: 10px 20px;
                background: #f6f7f7;
                border-bottom: 1px solid #dcdcde;
            }

            .ai-magic-provider-select {
                width: 100%;
                padding: 6px 10px;
                border: 1px solid #dcdcde;
                border-radius: 4px;
                font-size: 13px;
                color: #3c434a;
                background: #fff;
            }

            .ai-magic-provider-select:focus {
                border-color: #c8ff2a;
                box-shadow: 0 0 0 1px #c8ff2a;
                outline: none;
            }
        </style>
        <?php
    }

    /**
     * Enqueue assets
     */
    public function enqueue_assets()
    {
        wp_enqueue_script('ai-magic-slide-panel', plugin_dir_url(__FILE__) . 'js/ai-magic-slide-panel.js', array('jquery'), '1.0.7', true);

        wp_localize_script('ai-magic-slide-panel', 'aiMagicPanel', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('ai_magic_panel_nonce')
        ));
    }

    /**
     * Handle chat message AJAX
     */
    public function handle_chat_message()
    {
        check_ajax_referer('ai_magic_panel_nonce', 'nonce');

        if (!current_user_can('edit_posts')) {
            wp_send_json_error('Insufficient permissions');
        }

        $message = isset($_POST['message']) ? sanitize_text_field($_POST['message']) : '';
        $template_id = isset($_POST['template_id']) ? intval($_POST['template_id']) : 0;

        if (empty($message)) {
            wp_send_json_error('Message is required');
        }

        $provider = isset($_POST['provider']) ? sanitize_text_field($_POST['provider']) : 'openai';

        $ai = null;

        switch ($provider) {
            case 'anthropic':
                require_once plugin_dir_path(dirname(__FILE__)) . 'admin/class-ai-magic-anthropic.php';
                $ai = new AI_Magic_Anthropic();
                break;
            case 'google':
                require_once plugin_dir_path(dirname(__FILE__)) . 'admin/class-ai-magic-google.php';
                $ai = new AI_Magic_Google();
                break;
            case 'openai':
            default:
                require_once plugin_dir_path(dirname(__FILE__)) . 'admin/class-ai-magic-openai.php';
                $ai = new AI_Magic_OpenAI();
                break;
        }

        $response = $ai->generateText($message);

        if ($response['type'] === 'success') {
            wp_send_json_success($response);
        } else {
            wp_send_json_error($response['message']);
        }
    }

    /**
     * Handle meta description generation
     */
    public function handle_generate_meta()
    {
        check_ajax_referer('ai_magic_panel_nonce', 'nonce');

        if (!current_user_can('edit_posts')) {
            wp_send_json_error('Insufficient permissions');
        }

        $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
        $title = isset($_POST['title']) ? sanitize_text_field($_POST['title']) : '';
        $content = isset($_POST['content']) ? wp_kses_post($_POST['content']) : '';

        require_once plugin_dir_path(dirname(__FILE__)) . 'admin/class-ai-magic-openai.php';
        require_once plugin_dir_path(dirname(__FILE__)) . 'admin/class-ai-magic-seo.php';

        $openai = new AI_Magic_OpenAI();
        $response = $openai->generateMetaDescription($title, $content);

        if ($response['type'] === 'success' && $post_id > 0) {
            Ai_Magic_SEO::update_meta_description($post_id, $response['data']);
        }

        wp_send_json($response);
    }

    /**
     * Handle keyword extraction
     */
    public function handle_extract_keywords()
    {
        check_ajax_referer('ai_magic_panel_nonce', 'nonce');

        if (!current_user_can('edit_posts')) {
            wp_send_json_error('Insufficient permissions');
        }

        $content = isset($_POST['content']) ? wp_kses_post($_POST['content']) : '';

        require_once plugin_dir_path(dirname(__FILE__)) . 'admin/class-ai-magic-openai.php';

        $openai = new AI_Magic_OpenAI();
        $response = $openai->generateFocusKeywords($content, 5);

        wp_send_json($response);
    }
}

new AI_Magic_Admin_Bar();
