<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: /home/ploi/automarketer-ai.com/public/wp-content/plugins/automarketer-ai/includes/class-abstract-ai-provider.php
// Description: Abstract base class for all AI copy provider modules - NUCLEAR+++
// Last Edited: 2026-04-21
// ==================================================

namespace AutoMarketerAI;

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

abstract class AbstractAiProvider implements ModuleInterface
{
    // ---------------------------------------------------------------------------
    // Concrete shared implementations
    // ---------------------------------------------------------------------------

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

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

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

    // ---------------------------------------------------------------------------
    // Shared modal renderer — all providers use this identical flow.
    // Provider-specific values come from abstract method implementations.
    // ---------------------------------------------------------------------------

    public function render_activation_popup(): void
    {
        $provider_id    = $this->get_id();
        $provider_name  = $this->get_name();
        $modal_id       = $provider_id . '-activate-modal';
        $nonce          = wp_create_nonce('amai_provider_actions');
        $active_modules = (array) get_option('amai_active_modules', []);
        $is_active      = in_array($provider_id, $active_modules, true);
        $default_model  = $this->get_default_model();
        $saved_model    = $is_active
            ? (string) get_option('amai_model_' . $provider_id, $default_model)
            : '';
        $prefix         = $this->get_api_key_prefix();
        $placeholder    = $prefix !== '' ? $prefix . '...' : 'Paste your key here...';
        $pricing_note   = $this->get_pricing_note();
        $signup_url     = $this->get_signup_url();
        $signup_label   = $this->get_signup_label();
        ?>
        <script type="text/javascript">
            jQuery(document).ready(function($) {
                $(document).on('click', '[data-module-id="<?php echo esc_js($provider_id); ?>"] .amai-activate-btn', function(e) {
                    e.preventDefault();
                    e.stopPropagation();

                    const modalId = '<?php echo esc_js($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;">&times;</button>' +
                        '<h3 style="margin:0 0 24px; text-align:center; font-size:24px; color:#111; font-weight:600;">Activate <?php echo esc_js($provider_name); ?></h3>' +
                        '<p style="margin-bottom:24px; text-align:center; color:#555; font-size:14px;"><?php echo esc_js($pricing_note); ?></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 <?php echo esc_js($provider_name); ?> API Key:</label>' +
                        '<input type="text" id="' + modalId + '-key" placeholder="<?php echo esc_js($placeholder); ?>" 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
                        foreach ($this->get_available_models() as $value => $label) {
                            $selected = ($value === ($saved_model ?: $default_model)) ? ' selected' : '';
                            echo '<option value="' . esc_js($value) . '"' . $selected . '>' . esc_js($label) . '</option>';
                        }
                        ?>' +
                        '</select>' +
                        '<p style="margin-bottom:24px; text-align:center; color:#555; font-size:14px;">Don\'t have a key? <a href="<?php echo esc_js($signup_url); ?>" target="_blank" style="color:#2271b1; text-decoration:none;"><?php echo esc_js($signup_label); ?></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() || '<?php echo esc_js($default_model); ?>';

                        if (!apiKey) {
                            modal.find('#' + modalId + '-error').text('Please enter your <?php echo esc_js($provider_name); ?> API Key.').show();
                            return;
                        }

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

                        $.post(ajaxurl, {
                            action:      'amai_activate_provider',
                            provider_id: '<?php echo esc_js($provider_id); ?>',
                            api_key:     apiKey,
                            model:       model,
                            _ajax_nonce: '<?php echo esc_js($nonce); ?>'
                        }, function(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() {
                            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
    }

    // ---------------------------------------------------------------------------
    // Abstract methods — each provider must implement these
    // ---------------------------------------------------------------------------

    abstract public function get_id(): string;
    abstract public function get_name(): string;
    abstract public function get_description(): string;
    abstract public function get_logo_url(): string;
    abstract public function get_model_count(): int;
    abstract public function get_available_models(): array;
    abstract public function get_model_descriptions(): array;
    abstract public function get_default_model(): string;
    abstract public function get_api_key_prefix(): string;
    abstract public function validate_api_key(string $key): bool;
    abstract public function generate_raw(string $prompt, string $api_key, string $model): string;

    // Provider-specific modal copy — override in each provider
    abstract protected function get_pricing_note(): string;
    abstract protected function get_signup_url(): string;
    abstract protected function get_signup_label(): string;
}