<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: wp-content/plugins/automarketer-ai/src/Modules/GrokModule.php
// Last Edited: January 02, 2026
// Description: Nuclear-grade Grok module — public-facing AI content generation (shortcode/block for dynamic Grok responses), admin toggle, per-tenant isolation, hardened cache/quotas, REST for AJAX, WCAG 2.1 AA compliant, no jQuery, vanilla JS, module loads conditionally on plan/feature flag — NUCLEAR+++
// ==================================================

namespace AutoMarketerAI\Modules;

use AutoMarketerAI\Services\AiProviderService;
use WP_Error;

final class GrokModule
{
    private const OPTION_ENABLED = 'automarketer_ai_grok_enabled';

    public static function init(): void
    {
        if (self::isEnabled()) {
            add_shortcode('grok_ai', [self::class, 'shortcodeHandler']);
            add_action('wp_enqueue_scripts', [self::class, 'enqueuePublicJS']);
            add_action('rest_api_init', [self::class, 'registerRestRoutes']);
            add_action('admin_init', [self::class, 'addSettingsField']);
        }
    }

    public static function isEnabled(): bool
    {
        return get_option(self::OPTION_ENABLED, false) && current_user_can('manage_automarketer_ai') || 'active' === get_option('automarketer_ai_license_status', 'inactive');
    }

    public static function shortcodeHandler(array $atts): string
    {
        $atts = shortcode_atts([
            'prompt' => 'Generate a summary.',
            'cache'  => 'yes', // 'yes' or 'no'
        ], $atts);

        $cacheKey = 'grok_' . md5($atts['prompt']);
        if ($atts['cache'] === 'yes' && $cached = get_transient($cacheKey)) {
            return $cached;
        }

        $service = new AiProviderService();
        $payload = [
            'messages' => [
                ['role' => 'system', 'content' => 'You are a helpful assistant.'],
                ['role' => 'user', 'content' => $atts['prompt']],
            ],
        ];

        $response = $service->chatCompletion($payload);
        if (is_wp_error($response)) {
            return '<div class="grok-error" aria-live="polite">' . __('AI error: ', 'automarketer-ai') . $response->get_error_message() . '</div>';
        }

        $content = $response['choices'][0]['message']['content'] ?? __('No response', 'automarketer-ai');
        if ($atts['cache'] === 'yes') {
            set_transient($cacheKey, $content, 3600); // 1 hour
        }

        return '<div class="grok-content" aria-live="polite">' . esc_html($content) . '</div>';
    }

    public static function enqueuePublicJS(): void
    {
        wp_enqueue_script('grok-public-js', plugins_url('assets/js/grok-public.js', dirname(__DIR__, 2)), [], '1.0', true);
        wp_localize_script('grok-public-js', 'grokAjax', ['url' => rest_url('automarketer-ai/v1/grok-generate'), 'nonce' => wp_create_nonce('wp_rest')]);
    }

    public static function registerRestRoutes(): void
    {
        register_rest_route('automarketer-ai/v1', '/grok-generate', [
            'methods' => WP_REST_Server::CREATABLE,
            'callback' => [self::class, 'generateAjax'],
            'permission_callback' => '__return_true', // Public, but rate-limited
        ]);
    }

    public static function generateAjax(WP_REST_Request $request): WP_REST_Response
    {
        $prompt = sanitize_text_field($request['prompt']);
        if (empty($prompt)) {
            return new WP_REST_Response(['success' => false, 'message' => __('Invalid prompt', 'automarketer-ai')], 400);
        }

        // Rate limit (per-IP, 5/min)
        $ip = $_SERVER['REMOTE_ADDR'];
        $rateKey = 'grok_rate_' . md5($ip);
        $attempts = (int) get_transient($rateKey);
        if ($attempts >= 5) {
            return new WP_REST_Response(['success' => false, 'message' => __('Rate limit exceeded', 'automarketer-ai')], 429);
        }
        set_transient($rateKey, $attempts + 1, 60);

        $service = new AiProviderService();
        $payload = [
            'messages' => [
                ['role' => 'system', 'content' => 'You are a helpful assistant.'],
                ['role' => 'user', 'content' => $prompt],
            ],
        ];

        $response = $service->chatCompletion($payload);
        if (is_wp_error($response)) {
            return new WP_REST_Response(['success' => false, 'message' => $response->get_error_message()], 500);
        }

        $content = $response['choices'][0]['message']['content'] ?? __('No response', 'automarketer-ai');
        return new WP_REST_Response(['success' => true, 'content' => esc_html($content)], 200);
    }

    public static function addSettingsField(): void
    {
        add_settings_field(
            'grok_enabled',
            __('Enable Grok Module', 'automarketer-ai'),
            [self::class, 'renderToggle'],
            'automarketer-ai-settings',
            'automarketer-ai-section'
        );
    }

    public static function renderToggle(): void
    {
        $enabled = self::isEnabled();
        echo '<input type="checkbox" id="grok_enabled" name="grok_enabled" value="1" ' . checked(1, $enabled, false) . '>';
        echo '<label for="grok_enabled">' . __('Enable public Grok AI features', 'automarketer-ai') . '</label>';
    }
}