<?php
/**
 * Admin page class
 */
class Nietos_AI_Admin_Page {

    /**
     * Settings instance
     */
    private $settings;

    /**
     * Constructor
     */
    public function __construct($settings) {
        $this->settings = $settings;
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
    }

    /**
     * Enqueue admin scripts and styles
     */
    public function enqueue_admin_scripts($hook) {
        // Load on both our pages
        if (strpos($hook, 'nietos-ai') === false) {
            return;
        }

        // Enqueue modern admin styles
        wp_enqueue_style(
            'nietos-ai-admin',
            plugin_dir_url(__FILE__) . 'css/nietos-admin.css',
            array(),
            '1.0.0'
        );

        // Only load settings JS on settings page
        if ($hook === 'nietos-ai_page_nietos-ai-settings') {
            wp_enqueue_script(
                'nietos-ai-settings',
                plugin_dir_url(__FILE__) . 'js/settings.js',
                array('jquery'),
                '1.0.0',
                true
            );

            // Pass PHP data to JavaScript
            wp_localize_script('nietos-ai-settings', 'nietosAiSettings', array(
                'availableModels' => $this->settings->get_available_models(),
                'hasApiKey' => $this->settings->is_configured()
            ));
        }
    }

    /**
     * Add admin menu
     */
    public function add_admin_menu() {
        // Custom SVG icon - base64 encoded for WordPress menu
        // viewBox cropped to icon bounds (86,90 to 176,178) with small padding
        $icon_svg = 'data:image/svg+xml;base64,' . base64_encode('
            <svg width="20" height="20" viewBox="82 86 98 98" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M86 168V100C86 94 90 90 96 90H106C112 90 116 94 116 100V138C116 142 120 144 123 141L150 108C152 105 155 104 159 104H166C172 104 176 108 176 114V168C176 174 172 178 166 178H156C150 178 146 174 146 168V130C146 126 142 124 139 127L112 160C110 163 107 164 103 164H96C90 164 86 160 86 154Z" fill="black"/>
            </svg>
        ');

        add_menu_page(
            __('Nietos AI', 'nietos-ai'),
            __('Nietos AI', 'nietos-ai'),
            'edit_posts',
            'nietos-ai',
            array($this, 'render_chat_page'),
            $icon_svg,
            30
        );

        add_submenu_page(
            'nietos-ai',
            __('Chat', 'nietos-ai'),
            __('Chat', 'nietos-ai'),
            'edit_posts',
            'nietos-ai',
            array($this, 'render_chat_page')
        );

        add_submenu_page(
            'nietos-ai',
            __('Settings', 'nietos-ai'),
            __('Settings', 'nietos-ai'),
            'manage_options',
            'nietos-ai-settings',
            array($this, 'render_settings_page')
        );
    }

    /**
     * Render chat page
     */
    public function render_chat_page() {
        if (!$this->settings->is_configured()) {
            $this->render_setup_required();
            return;
        }

        $premium = new Nietos_AI_Premium();
        $has_premium = $premium->has_premium_license();
        $remaining = $premium->get_remaining_messages();

        ?>
        <div class="nietos-ai-admin-page">
            <div class="nietos-ai-page-header">
                <svg width="96" height="96" viewBox="0 0 256 256" fill="none" xmlns="http://www.w3.org/2000/svg" style="border-radius: 24px; overflow: hidden;">
                    <defs>
                        <linearGradient id="nietosGradientChat" gradientTransform="rotate(135)">
                            <stop offset="0%" stop-color="#4433A6" />
                            <stop offset="100%" stop-color="#5644BC" />
                        </linearGradient>
                    </defs>
                    <rect width="256" height="256" rx="56" fill="url(#nietosGradientChat)" />
                    <path d="M86 168V100C86 94 90 90 96 90H106C112 90 116 94 116 100V138C116 142 120 144 123 141L150 108C152 105 155 104 159 104H166C172 104 176 108 176 114V168C176 174 172 178 166 178H156C150 178 146 174 146 168V130C146 126 142 124 139 127L112 160C110 163 107 164 103 164H96C90 164 86 160 86 154Z" fill="#79F3B1"/>
                </svg>
                <div>
                    <h1><?php echo esc_html__('Nietos AI', 'nietos-ai'); ?></h1>
                    <p><?php echo esc_html__('Manage content with natural language', 'nietos-ai'); ?></p>
                </div>
            </div>

            <?php if (!$has_premium): ?>
            <div class="nietos-ai-premium-banner">
                <div class="nietos-ai-premium-content">
                    <div class="nietos-ai-premium-icon">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <circle cx="12" cy="12" r="10"></circle>
                            <path d="M12 16v-4"></path>
                            <path d="M12 8h.01"></path>
                        </svg>
                    </div>
                    <div class="nietos-ai-premium-text">
                        <strong><?php esc_html_e('Free Version', 'nietos-ai'); ?></strong>
                        <span><?php
                            // translators: %1$d: remaining messages, %2$d: total free message limit
                            printf(esc_html__('%1$d of %2$d messages remaining today', 'nietos-ai'), esc_html($remaining), esc_html(Nietos_AI_Premium::FREE_MESSAGE_LIMIT));
                        ?></span>
                    </div>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=nietos-ai-settings#premium')); ?>" class="nietos-ai-premium-button">
                        <?php esc_html_e('Upgrade to Premium', 'nietos-ai'); ?>
                    </a>
                </div>
            </div>
            <?php endif; ?>

            <div class="nietos-ai-card">
                <div id="nietos-ai-chat-root"></div>
            </div>
        </div>
        <?php
    }

    /**
     * Render settings page
     */
    public function render_settings_page() {
        $settings = $this->settings->get_settings();

        // Handle license activation
        if (isset($_POST['nietos_ai_save_license']) && check_admin_referer('nietos_ai_license')) {
            $license_key = sanitize_text_field($_POST['license_key'] ?? '');
            if (!empty($license_key)) {
                $premium = new Nietos_AI_Premium();
                $result = $premium->save_license($license_key);

                if ($result) {
                    echo '<div class="notice notice-success"><p>' . esc_html__('License activated successfully!', 'nietos-ai') . '</p></div>';
                } else {
                    echo '<div class="notice notice-error"><p>' . esc_html__('Invalid license key. Please check and try again.', 'nietos-ai') . '</p></div>';
                }
            } else {
                echo '<div class="notice notice-error"><p>' . esc_html__('Please enter a license key.', 'nietos-ai') . '</p></div>';
            }
        }

        // Handle license removal
        if (isset($_POST['nietos_ai_remove_license']) && check_admin_referer('nietos_ai_license')) {
            $premium = new Nietos_AI_Premium();
            $premium->remove_license();
            echo '<div class="notice notice-success"><p>' . esc_html__('License removed successfully.', 'nietos-ai') . '</p></div>';
        }

        // Handle cache clearing
        if (isset($_POST['nietos_ai_clear_cache']) && check_admin_referer('nietos_ai_clear_cache')) {
            $this->settings->clear_models_cache();
            echo '<div class="notice notice-success"><p>' . esc_html__('Models cache cleared successfully!', 'nietos-ai') . '</p></div>';
        }

        // Handle form submission
        if (isset($_POST['nietos_ai_save_settings']) && check_admin_referer('nietos_ai_settings')) {
            $new_settings = array(
                'model' => sanitize_text_field($_POST['model'] ?? ''),
                'max_tokens' => absint($_POST['max_tokens'] ?? 4096),
                'temperature' => floatval($_POST['temperature'] ?? 0.7)
            );

            // Only update API key if a new one is provided
            $api_key_changed = false;
            if (!empty($_POST['api_key'])) {
                $new_settings['api_key'] = $_POST['api_key'];
                $api_key_changed = true;
            }

            $this->settings->update_settings($new_settings);

            // Test and validate API key automatically when changed
            if ($api_key_changed) {
                $this->settings->clear_models_cache();

                // Try to validate the new API key
                require_once NIETOS_AI_PLUGIN_DIR . 'includes/class-api-handler.php';
                $security = new Nietos_AI_Security();
                $api_handler = new Nietos_AI_API_Handler($security);

                $encrypted_key = $security->encrypt_api_key($_POST['api_key']);
                $test_result = $api_handler->test_connection($encrypted_key, $new_settings['model']);

                if (isset($test_result['success']) && $test_result['success'] === true) {
                    $this->settings->mark_api_key_validated();
                    echo '<div class="notice notice-success"><p>' . esc_html__('Settings saved and API key validated successfully!', 'nietos-ai') . '</p></div>';
                } else {
                    echo '<div class="notice notice-warning"><p>' . esc_html__('Settings saved, but API key validation failed. Please check your API key.', 'nietos-ai') . '</p></div>';
                }
            } else {
                echo '<div class="notice notice-success"><p>' . esc_html__('Settings saved successfully!', 'nietos-ai') . '</p></div>';
            }

            // Refresh settings
            $settings = $this->settings->get_settings();
        }

        $has_api_key = $this->settings->is_configured();
        $is_api_key_valid = $this->settings->is_api_key_valid();
        $available_models = $this->settings->get_available_models();

        ?>
        <div class="nietos-ai-admin-page">
            <div class="nietos-ai-page-header">
                <svg width="96" height="96" viewBox="0 0 256 256" fill="none" xmlns="http://www.w3.org/2000/svg" style="border-radius: 24px; overflow: hidden;">
                    <defs>
                        <linearGradient id="nietosGradientSettings" gradientTransform="rotate(135)">
                            <stop offset="0%" stop-color="#4433A6" />
                            <stop offset="100%" stop-color="#5644BC" />
                        </linearGradient>
                    </defs>
                    <rect width="256" height="256" rx="56" fill="url(#nietosGradientSettings)" />
                    <path d="M86 168V100C86 94 90 90 96 90H106C112 90 116 94 116 100V138C116 142 120 144 123 141L150 108C152 105 155 104 159 104H166C172 104 176 108 176 114V168C176 174 172 178 166 178H156C150 178 146 174 146 168V130C146 126 142 124 139 127L112 160C110 163 107 164 103 164H96C90 164 86 160 86 154Z" fill="#79F3B1"/>
                </svg>
                <div>
                    <h1><?php echo esc_html__('Settings', 'nietos-ai'); ?></h1>
                    <p><?php echo esc_html__('Configure your API connection and preferences', 'nietos-ai'); ?></p>
                </div>
            </div>

            <div class="nietos-ai-card">
                <h2><?php esc_html_e('API Configuration', 'nietos-ai'); ?></h2>
                <form method="post" action="">
                    <?php wp_nonce_field('nietos_ai_settings'); ?>

                    <table class="nietos-ai-form-table">
                        <tr>
                            <th scope="row">
                                <label for="api_key"><?php esc_html_e('OpenAI API Key', 'nietos-ai'); ?></label>
                            </th>
                            <td>
                                <input type="password" name="api_key" id="api_key" class="nietos-ai-input"
                                       placeholder="<?php echo $is_api_key_valid ? '••••••••••••••••' : esc_attr__('Enter your OpenAI API key', 'nietos-ai'); ?>">
                                <p class="description">
                                    <?php esc_html_e('Get your API key from ', 'nietos-ai'); ?>
                                    <a href="https://platform.openai.com/api-keys" target="_blank">OpenAI</a>.
                                </p>
                            </td>
                        </tr>

                        <tr>
                            <th scope="row">
                                <label for="model"><?php esc_html_e('Model', 'nietos-ai'); ?></label>
                            </th>
                            <td>
                                <select name="model" id="model" class="nietos-ai-input">
                                    <?php foreach ($available_models as $model_id => $model_name): ?>
                                        <option value="<?php echo esc_attr($model_id); ?>"
                                                <?php selected($settings['model'], $model_id); ?>>
                                            <?php echo esc_html($model_name); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <p class="description">
                                    <?php esc_html_e('Select which model to use', 'nietos-ai'); ?>
                                </p>
                            </td>
                        </tr>

                        <tr>
                            <th scope="row">
                                <label for="max_tokens"><?php esc_html_e('Max Tokens', 'nietos-ai'); ?></label>
                            </th>
                            <td>
                                <input type="number" name="max_tokens" id="max_tokens" class="nietos-ai-input"
                                       value="<?php echo esc_attr($settings['max_tokens']); ?>"
                                       min="100" max="8192" step="100">
                                <p class="description">
                                    <?php esc_html_e('Maximum response length in tokens', 'nietos-ai'); ?>
                                </p>
                            </td>
                        </tr>

                        <tr>
                            <th scope="row">
                                <label for="temperature"><?php esc_html_e('Temperature', 'nietos-ai'); ?></label>
                            </th>
                            <td>
                                <input type="number" name="temperature" id="temperature" class="nietos-ai-input"
                                       value="<?php echo esc_attr($settings['temperature']); ?>"
                                       min="0" max="1" step="0.1">
                                <p class="description">
                                    <?php esc_html_e('Controls response creativity (0-2)', 'nietos-ai'); ?>
                                </p>
                            </td>
                        </tr>
                    </table>

                    <p class="submit">
                        <button type="submit" name="nietos_ai_save_settings" class="nietos-ai-button nietos-ai-button-primary">
                            <?php esc_html_e('Save Settings', 'nietos-ai'); ?>
                        </button>
                    </p>
                </form>
            </div>

            <div class="nietos-ai-card">
                <h2><?php esc_html_e('Advanced', 'nietos-ai'); ?></h2>
                <form method="post" action="">
                    <?php wp_nonce_field('nietos_ai_clear_cache'); ?>
                    <p>
                        <?php esc_html_e('Clear cache to fetch latest models from API', 'nietos-ai'); ?>
                    </p>
                    <p>
                        <button type="submit" name="nietos_ai_clear_cache" class="nietos-ai-button nietos-ai-button-secondary">
                            <?php esc_html_e('Clear Models Cache', 'nietos-ai'); ?>
                        </button>
                    </p>
                </form>
            </div>

            <div class="nietos-ai-card" id="premium">
                <h2><?php esc_html_e('Premium License', 'nietos-ai'); ?></h2>
                <?php
                $premium = new Nietos_AI_Premium();
                $has_premium = $premium->has_premium_license();
                $license_key = $premium->get_license_key();
                ?>

                <?php if ($has_premium): ?>
                    <div class="nietos-ai-notice nietos-ai-notice-success">
                        <div>
                            <strong><?php esc_html_e('Premium Active', 'nietos-ai'); ?></strong>
                            <p style="margin: 8px 0 0;"><?php esc_html_e('You have unlimited messages!', 'nietos-ai'); ?></p>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="nietos-ai-notice nietos-ai-notice-info">
                        <div>
                            <strong><?php esc_html_e('Free Version', 'nietos-ai'); ?></strong>
                            <p style="margin: 8px 0 0;">
                                <?php
                                /* translators: %d: free message limit per day */
                                printf(esc_html__('Limited to %d messages per day. Upgrade for unlimited access.', 'nietos-ai'), esc_html(Nietos_AI_Premium::FREE_MESSAGE_LIMIT));
                                ?>
                            </p>
                        </div>
                    </div>
                <?php endif; ?>

                <form method="post" action="" style="margin-top: var(--spacing-lg);">
                    <?php wp_nonce_field('nietos_ai_license'); ?>

                    <table class="nietos-ai-form-table">
                        <tr>
                            <th scope="row">
                                <label for="license_key"><?php esc_html_e('License Key', 'nietos-ai'); ?></label>
                            </th>
                            <td>
                                <input type="text" name="license_key" id="license_key" class="nietos-ai-input"
                                       value="<?php echo esc_attr($license_key); ?>"
                                       placeholder="<?php esc_attr_e('Enter your license key', 'nietos-ai'); ?>">
                                <p class="description">
                                    <?php esc_html_e('Enter your license key for unlimited access', 'nietos-ai'); ?>
                                    <?php if (!$has_premium): ?>
                                        <br>
                                        <a href="https://nietos-ai.com/product/nietos-ai-premium-license/" target="_blank"><?php esc_html_e('Get a license', 'nietos-ai'); ?></a>
                                    <?php endif; ?>
                                </p>
                            </td>
                        </tr>
                    </table>

                    <p>
                        <?php if ($has_premium): ?>
                            <button type="submit" name="nietos_ai_remove_license" class="nietos-ai-button nietos-ai-button-danger">
                                <?php esc_html_e('Remove License', 'nietos-ai'); ?>
                            </button>
                        <?php else: ?>
                            <button type="submit" name="nietos_ai_save_license" class="nietos-ai-button nietos-ai-button-primary">
                                <?php esc_html_e('Activate License', 'nietos-ai'); ?>
                            </button>
                        <?php endif; ?>
                    </p>
                </form>

                <?php if (!$has_premium): ?>
                <div class="nietos-ai-premium-features-box">
                    <div class="nietos-ai-premium-features-header">
                        <div class="nietos-ai-premium-features-icon">
                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
                            </svg>
                        </div>
                        <h3><?php esc_html_e('Premium Features', 'nietos-ai'); ?></h3>
                    </div>
                    <ul class="nietos-ai-premium-features-list">
                        <li>
                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <polyline points="20 6 9 17 4 12"></polyline>
                            </svg>
                            <span><?php esc_html_e('Unlimited messages per day', 'nietos-ai'); ?></span>
                        </li>
                        <li>
                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <polyline points="20 6 9 17 4 12"></polyline>
                            </svg>
                            <span><?php esc_html_e('Priority support', 'nietos-ai'); ?></span>
                        </li>
                        <li>
                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <polyline points="20 6 9 17 4 12"></polyline>
                            </svg>
                            <span><?php esc_html_e('Early access to new features', 'nietos-ai'); ?></span>
                        </li>
                    </ul>
                    <a href="https://nietos-ai.com/product/nietos-ai-premium-license/" target="_blank" class="nietos-ai-button nietos-ai-button-primary">
                        <?php esc_html_e('Get Premium', 'nietos-ai'); ?>
                    </a>
                </div>
                <?php endif; ?>
            </div>

            <div class="nietos-ai-card nietos-ai-getting-started">
                <h2><?php esc_html_e('Getting Started', 'nietos-ai'); ?></h2>
                <ol>
                    <li><?php esc_html_e('Get an API key from OpenAI', 'nietos-ai'); ?></li>
                    <li><?php esc_html_e('Enter API key and save settings', 'nietos-ai'); ?></li>
                    <li><?php esc_html_e('Select your preferred model', 'nietos-ai'); ?></li>
                    <li><?php esc_html_e('Start managing your site', 'nietos-ai'); ?></li>
                </ol>

                <h3><?php esc_html_e('Get API Key', 'nietos-ai'); ?></h3>
                <p><a href="https://platform.openai.com/api-keys" target="_blank" class="nietos-ai-button nietos-ai-button-secondary">
                    <?php esc_html_e('OpenAI Platform', 'nietos-ai'); ?>
                </a></p>
            </div>
        </div>
        <?php
    }

    /**
     * Render setup required message
     */
    private function render_setup_required() {
        ?>
        <div class="nietos-ai-admin-page">
            <div class="nietos-ai-page-header">
                <svg width="96" height="96" viewBox="0 0 256 256" fill="none" xmlns="http://www.w3.org/2000/svg" style="border-radius: 24px; overflow: hidden;">
                    <defs>
                        <linearGradient id="nietosGradientSetup" gradientTransform="rotate(135)">
                            <stop offset="0%" stop-color="#4433A6" />
                            <stop offset="100%" stop-color="#5644BC" />
                        </linearGradient>
                    </defs>
                    <rect width="256" height="256" rx="56" fill="url(#nietosGradientSetup)" />
                    <path d="M86 168V100C86 94 90 90 96 90H106C112 90 116 94 116 100V138C116 142 120 144 123 141L150 108C152 105 155 104 159 104H166C172 104 176 108 176 114V168C176 174 172 178 166 178H156C150 178 146 174 146 168V130C146 126 142 124 139 127L112 160C110 163 107 164 103 164H96C90 164 86 160 86 154Z" fill="#79F3B1"/>
                </svg>
                <div>
                    <h1><?php echo esc_html__('Nietos AI', 'nietos-ai'); ?></h1>
                    <p><?php echo esc_html__('Manage content with natural language', 'nietos-ai'); ?></p>
                </div>
            </div>
            <div class="nietos-ai-setup-required">
                <div class="nietos-ai-notice nietos-ai-notice-warning">
                    <div>
                        <strong><?php esc_html_e('Setup Required', 'nietos-ai'); ?></strong>
                        <p style="margin: 8px 0 16px;">
                            <?php esc_html_e('Configure your API key in settings to begin', 'nietos-ai'); ?>
                        </p>
                        <a href="<?php echo esc_url(admin_url('admin.php?page=nietos-ai-settings')); ?>" class="nietos-ai-button nietos-ai-button-primary">
                            <?php esc_html_e('Configure Settings', 'nietos-ai'); ?>
                        </a>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }
}
