<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: modules/ai-grok.php
// Last Edited: 2026-04-12
// Description: Grok provider module — real prefix placeholder — NUCLEAR+++
// ==================================================

namespace AutoMarketerAI\Modules;

use AutoMarketerAI\ModuleInterface;

if (!defined('ABSPATH')) {
    exit('No direct script access allowed.');
}

final class Grok implements ModuleInterface
{
    private const PREFIX   = 'xai-';
    private const MODAL_ID = 'grok-activate-modal';

    public function get_id(): string
    {
        return 'ai-grok';
    }

    public function get_name(): string
    {
        return 'Grok';
    }

    public function get_description(): string
    {
        return 'Integrate Grok (xAI) for intelligent content generation, analysis, and automation.';
    }

    public function get_logo_url(): string
    {
        return '';
    }

    public function get_category(): string
    {
        return 'AI';
    }

    public function get_model_count(): int
    {
        return 2;
    }

    public function get_available_models(): array
    {
        return [
            'grok-4.3'  => 'Grok 4.3 — Recommended',
            'grok-4.20' => 'Grok 4.20 — Most capable',
        ];
    }

    public function get_single_model_notice(): string
    {
        return '';
    }

    public function get_default_model(): string
    {
        return 'grok-4.3';
    }

    public function get_model_descriptions(): array
    {
        return [
            'grok-4.3'  => 'Recommended general-purpose model. Best balance of speed, quality, and cost for content generation.',
            'grok-4.20' => 'Most capable xAI model. Best for complex reasoning and demanding tasks. Higher cost per token.',
        ];
    }

    public function validate_api_key(string $key): bool
    {
        return str_starts_with($key, 'xai-');
    }

    public function generate_raw(string $prompt, string $api_key, string $model, int $max_tokens = 64): string
    {
        if ($prompt === '' || $api_key === '' || $model === '') {
            return '';
        }

        // xAI Grok uses an OpenAI-compatible chat completions endpoint
        $response = wp_remote_post('https://api.x.ai/v1/chat/completions', [
            'headers' => [
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type'  => 'application/json',
            ],
            'body'    => (string) json_encode([
                'model'      => $model,
                'max_tokens' => $max_tokens,
                'messages'   => [['role' => 'user', 'content' => $prompt]],
            ]),
            'timeout' => 15,
        ]);

        if (is_wp_error($response)) {
            return '';
        }

        $http_code = (int) wp_remote_retrieve_response_code($response);
        if ($http_code !== 200) {
            if ($http_code === 401 || $http_code === 429) {
                set_transient('amai_provider_credit_warning', $this->get_id(), HOUR_IN_SECONDS);
            }
            return '';
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        return trim((string) ($body['choices'][0]['message']['content'] ?? ''));
    }

    public function register(): void
    {
        add_action('admin_footer', [$this, 'render_activation_popup']);
    }

    public function get_api_key_prefix(): string
    {
        return self::PREFIX;
    }

    public function render_activation_popup(): void
    {
        $nonce          = wp_create_nonce('amai_provider_actions');
        $active_modules = (array) get_option('amai_active_modules', []);
        $is_active      = in_array($this->get_id(), $active_modules);
        $saved_model    = $is_active ? get_option('amai_' . $this->get_id() . '_model', 'grok-4.3') : '';
        $prefix         = $this->get_api_key_prefix();
        ?>
        <script type="text/javascript">
            jQuery(document).ready(function($) {
                $(document).on('click', '[data-module-id="<?php echo esc_js($this->get_id()); ?>"] .amai-activate-btn', function(e) {
                    e.preventDefault();
                    e.stopPropagation();

                    const modalId = '<?php echo esc_js(self::MODAL_ID); ?>';
                    $('#' + modalId).remove();

                    const popupHtml = `
                        <div id="${modalId}" style="display:none; position:fixed; inset:0; width:100%; height:100%; background:rgba(0,0,0,0.65); z-index:99999; display:flex; align-items:center; justify-content:center;">
                            <div style="background:#ffffff; padding:28px; width:480px; max-width:92%; max-height:90vh; overflow-y:auto; box-shadow:0 20px 70px rgba(0,0,0,0.45); position:relative;">
                                <button id="${modalId}-close" style="position:absolute; top:12px; right:16px; background:none; border:none; font-size:32px; color:#555; cursor:pointer; line-height:1; padding:0;">×</button>
                                <h3 style="margin:0 0 24px; text-align:center; font-size:24px; color:#111; font-weight:600;">Activate <?php echo esc_html($this->get_name()); ?></h3>
                                <p style="margin-bottom:24px; text-align:center; color:#555; font-size:14px;">Very inexpensive — xAI requires only a $5 deposit to start (covers a lot of usage).</p>
                                <div id="${modalId}-error" style="display:none; margin:0 0 20px; padding:14px; background:#ffebee; border-left:5px solid #c62828; color:#b71c1c; font-size:14px; border-radius:4px;"></div>
                                <label for="${modalId}-key" style="display:block; margin-bottom:10px; font-weight:600; color:#222; font-size:15px;">Your Grok API Key:</label>
                                <input type="text" id="${modalId}-key" placeholder="<?php echo esc_attr($prefix . '...'); ?>" style="width:100%; padding:12px; margin-bottom:20px; border:1px solid #ccc; font-size:15px; box-sizing:border-box;">
                                <label for="${modalId}-model" style="display:block; margin-bottom:10px; font-weight:600; color:#222; font-size:15px;">Preferred Model:</label>
                                <select id="${modalId}-model" style="width:100%; padding:12px; margin-bottom:24px; border:1px solid #ccc; font-size:15px; box-sizing:border-box;">
                                    <option value="">Select model</option>
                                    <?php
                                    $models = $this->get_available_models();
                                    foreach ($models as $value => $label) {
                                        $selected = ($value === $saved_model) ? 'selected' : '';
                                        echo '<option value="' . esc_attr($value) . '" ' . $selected . '>' . esc_html($label) . '</option>';
                                    }
                                    ?>
                                </select>
                                <p style="margin-bottom:24px; text-align:center; color:#555; font-size:14px;">Don't have a key? <a href="https://x.ai/api" target="_blank" style="color:#2271b1; text-decoration:none;">Get one in 5 minutes</a>.</p>
                                <div style="text-align:center;">
                                    <button id="${modalId}-cancel" style="padding:12px 32px; margin-right:16px; background:#f5f5f5; border:1px solid #ccc; color:#333; font-size:15px; cursor:pointer; transition:background 0.2s;">Cancel</button>
                                    <button id="${modalId}-save" style="padding:12px 32px; background:#2271b1; color:white; border:none; font-size:15px; cursor:pointer; transition:background 0.2s;">Save & Activate</button>
                                </div>
                            </div>
                        </div>
                    `;

                    $('body').append(popupHtml);
                    const modal = $('#' + modalId);
                    modal.fadeIn(200);

                    <?php if ($is_active): ?>
                    modal.find('#' + modalId + '-save').text('Update & Save');
                    <?php endif; ?>

                    modal.find('#' + modalId + '-cancel').hover(function() { $(this).css('background', '#e0e0e0'); }, function() { $(this).css('background', '#f5f5f5'); });
                    modal.find('#' + modalId + '-save').hover(function() { $(this).css('background', '#1a5bb8'); }, function() { $(this).css('background', '#2271b1'); });

                    modal.find('#' + modalId + '-close, #' + modalId + '-cancel').on('click', function() {
                        modal.fadeOut(200, () => modal.remove());
                    });

                    modal.on('click', function(e) {
                        if (e.target === this) modal.fadeOut(200, () => modal.remove());
                    });

                    modal.find('#' + modalId + '-save').on('click', function() {
                        const apiKey = modal.find('#' + modalId + '-key').val().trim();
                        const model  = modal.find('#' + modalId + '-model').val() || 'grok-4.3';

                        if (!apiKey) {
                            modal.find('#' + modalId + '-error').text('Please enter your Grok API Key.').show();
                            return;
                        }

                        modal.find('#' + modalId + '-error').hide();

                        $.post(ajaxurl, {
                            action:      'amai_activate_provider',
                            provider_id: '<?php echo esc_js($this->get_id()); ?>',
                            api_key:     apiKey,
                            model:       model,
                            _ajax_nonce: '<?php echo esc_js($nonce); ?>'
                        }, function(response) {
                            console.log('Activation response:', response);
                            if (response.success) {
                                modal.fadeOut(200, () => {
                                    modal.remove();
                                    location.reload();
                                });
                            } else {
                                modal.find('#' + modalId + '-error').text(response.data?.message || 'Activation failed. Please try again.').show();
                            }
                        }).fail(function(jqXHR, textStatus) {
                            console.error('AJAX fail:', textStatus, jqXHR.responseText);
                            modal.find('#' + modalId + '-error').text('Connection error — please try again.').show();
                        });
                    });

                    modal.find('#' + modalId + '-key').on('input', function() {
                        modal.find('#' + modalId + '-error').hide();
                    });

                    modal.find('#' + modalId + '-key').focus();
                });
            });
        </script>
        <?php
    }
}