<?php
/*
desenvolvedor: luciano donizeti
mania de script: www.maniadescript.com.br
whatsapp 43998240911
*/

session_start();

require_once './db/configdb.php';
require_once './ai_card_helper.php';

if (!isset($_SESSION["usuario"]) || !isset($_SESSION["user_id"]) || !isset($_SESSION["nivel"])) {
    header("Location: login.php");
    exit();
}

if ((int)$_SESSION["nivel"] !== ADMIN_LEVEL) {
    die('<div style="padding:20px;background:#ffdddd;border:1px solid red;border-radius:8px;">
        <strong>Erro:</strong> Acesso negado! Esta página é restrita a administradores.
    </div>');
}

$card_types = [
    'card_banner_1' => ['name' => 'Card Banner 1', 'fixed_filename' => 'card_banner_1'],
    'card_banner_2' => ['name' => 'Card Banner 2', 'fixed_filename' => 'card_banner_2'],
    'card_banner_3' => ['name' => 'Card Banner 3', 'fixed_filename' => 'card_banner_3'],
    'card_banner_4' => ['name' => 'Card Banner 4', 'fixed_filename' => 'card_banner_4'],
    'card_banner_5' => ['name' => 'Card Banner 5', 'fixed_filename' => 'card_banner_5'],
];

$current_card_key = $_GET['tipo'] ?? array_key_first($card_types);
if (!array_key_exists($current_card_key, $card_types)) {
    header("Location: card.php");
    exit();
}

$current_card_config = $card_types[$current_card_key];
$successMessage = '';
$errorMessage = '';
$aiPromptGerado = '';
$redirect_card_key = $current_card_key;
$aiConfig = aiCardLoadConfig();
$aiStyles = aiCardAvailableStyles();
$aiProviders = aiCardAvailableProviders();

if ($_SERVER['REQUEST_METHOD'] === "POST") {
    $posted_card_type = $_POST['card_type'] ?? null;
    if ($posted_card_type && isset($card_types[$posted_card_type])) {
        $redirect_card_key = $posted_card_type;
        $fixed_filename_base = $card_types[$posted_card_type]['fixed_filename'];

        if (isset($_POST['upload']) && isset($_FILES['image']) && $_FILES['image']['error'] === 0) {
            $file = $_FILES['image'];
            $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
            $mime = $file['type'] ?? '';
            if (in_array($mime, $allowedTypes, true)) {
                $content = @file_get_contents($file['tmp_name']);
                $saveError = null;
                if ($content !== false && aiCardSaveImageAsPng((string)$content, $fixed_filename_base, $saveError)) {
                    $successMessage = "Imagem enviada e convertida para PNG com sucesso!";
                } else {
                    $errorMessage = $saveError ?: 'Falha ao salvar o arquivo enviado.';
                }
            } else {
                $errorMessage = 'Tipo de arquivo inválido. Use PNG, JPG, GIF ou WebP.';
            }
        } elseif (isset($_POST['url-submit'])) {
            $imageUrl = trim((string)($_POST['image-url'] ?? ''));
            if (filter_var($imageUrl, FILTER_VALIDATE_URL)) {
                $saveError = null;
                if (aiCardDownloadAndSaveUrl($imageUrl, $fixed_filename_base, $saveError)) {
                    $successMessage = "Imagem da URL baixada e salva com sucesso!";
                } else {
                    $errorMessage = $saveError ?: 'Não foi possível baixar/salvar a imagem da URL.';
                }
            } else {
                $errorMessage = 'A URL fornecida não é válida.';
            }
        } elseif (isset($_POST['ai-submit'])) {
            $postedConfig = $aiConfig;
            $postedConfig['provider'] = aiCardNormalizeProvider((string)($_POST['ai_provider'] ?? ($aiConfig['provider'] ?? 'openai')));
            $postedConfig['api_url'] = trim((string)($_POST['ai_api_url'] ?? $aiConfig['api_url']));
            $postedConfig['model'] = trim((string)($_POST['ai_model'] ?? $aiConfig['model']));
            $postedConfig['size'] = trim((string)($_POST['ai_size'] ?? $aiConfig['size']));
            $postedConfig['quality'] = trim((string)($_POST['ai_quality'] ?? $aiConfig['quality']));
            $postedConfig['style'] = trim((string)($_POST['ai_style'] ?? $aiConfig['style']));

            $newKey = trim((string)($_POST['ai_api_key'] ?? ''));
            if ($newKey !== '') {
                $postedConfig['api_key'] = $newKey;
            }

            $saveKey = isset($_POST['ai_save_key']);
            if (!$saveKey && $newKey !== '') {
                // Usa a chave apenas nesta geracao e nao grava no disco.
                $tempConfig = $postedConfig;
                $postedConfig['api_key'] = $aiConfig['api_key'] ?? '';
                aiCardSaveConfig($postedConfig);
                $postedConfig = $tempConfig;
            } else {
                $postedConfig['save_key'] = true;
                aiCardSaveConfig($postedConfig);
            }
            $aiConfig = aiCardLoadConfig();
            if (!$saveKey && $newKey !== '') { $aiConfig['api_key'] = $newKey; }

            $tituloIa = trim((string)($_POST['ai_title'] ?? ''));
            $promptCustom = trim((string)($_POST['ai_prompt'] ?? ''));
            $aiPromptGerado = aiCardBuildPrompt($card_types[$posted_card_type]['name'], (string)$postedConfig['style'], $tituloIa, $promptCustom);

            $apiError = null;
            $binary = aiCardCallImageApi($postedConfig, $aiPromptGerado, $apiError);
            if ($binary === null || $binary === '') {
                $errorMessage = $apiError ?: 'Não foi possível gerar a imagem com IA.';
            } else {
                $saveError = null;
                if (aiCardSaveImageAsPng($binary, $fixed_filename_base, $saveError)) {
                    $successMessage = "Card criado automaticamente com IA e salvo com sucesso!";
                } else {
                    $errorMessage = $saveError ?: 'A IA gerou a imagem, mas não foi possível salvar o card.';
                }
            }
        }
    } else {
        $errorMessage = "Tipo de card inválido enviado.";
    }
}

$methord = "Não Definido";
$imageFilex = '';
$showPreview = false;
$uploadPath = './fzstore/card/';
$fileName = $current_card_config['fixed_filename'];
$possibleExtensions = ['png', 'jpg', 'jpeg', 'gif', 'webp'];
foreach ($possibleExtensions as $ext) {
    $filePath = $uploadPath . $fileName . '.' . $ext;
    if (file_exists($filePath)) {
        $imageFilex = $filePath;
        $methord = ($ext === 'png') ? "Arquivo PNG ativo" : "Arquivo enviado";
        $showPreview = true;
        break;
    }
}

$pageTitle = "Gerenciar Cards";
include "includes/header.php";
?>

<style>
    .two-column-grid {
        display: grid;
        grid-template-columns: 1fr;
        gap: 30px;
    }
    @media (min-width: 980px) {
        .two-column-grid { grid-template-columns: 0.9fr 1.1fr; }
    }
    .column-box {
        background: rgba(0,0,0,0.15);
        padding: 25px;
        border-radius: 10px;
    }
    .column-box h3 {
        color: var(--accent-color);
        margin-bottom: 20px;
        font-weight: 600;
        border-bottom: 1px solid var(--accent-color);
        padding-bottom: 10px;
    }
    .form-group { margin-bottom: 18px; }
    .form-group label { display: block; color: var(--text-secondary, var(--text-muted)); margin-bottom: 8px; font-weight: 500; }
    .form-select, .form-control, textarea.form-control {
        width: 100%; padding: 12px 15px; background-color: var(--page-bg);
        border: 1px solid rgba(255,255,255,0.2); border-radius: 8px; color: var(--text-color);
    }
    textarea.form-control { min-height: 120px; resize: vertical; }
    .form-select:focus, .form-control:focus { outline: none; border-color: var(--accent-color); }
    .form-hint { color: var(--text-muted); font-size: .86rem; margin-top: 6px; line-height: 1.4; }

    .preview-area {
        width: 100%;
        height: 300px;
        margin-top: 15px;
        background-color: var(--page-bg);
        background-image:
            linear-gradient(45deg, rgba(255,255,255,0.05) 25%, transparent 25%),
            linear-gradient(-45deg, rgba(255,255,255,0.05) 25%, transparent 25%),
            linear-gradient(45deg, transparent 75%, rgba(255,255,255,0.05) 75%),
            linear-gradient(-45deg, transparent 75%, rgba(255,255,255,0.05) 75%);
        background-size: 20px 20px;
        border: 2px dashed rgba(255,255,255,0.2);
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        overflow: hidden;
    }
    .preview-area img { max-width: 100%; max-height: 100%; object-fit: contain; }
    .preview-area .no-image { color: var(--text-muted); font-size: 0.9rem; text-align:center; padding: 12px; }
    .current-method-info {
        text-align: center;
        color: var(--text-muted);
        font-size: 0.9rem;
        margin-top: 15px;
        word-break: break-all;
    }
    .current-method-info strong { color: var(--accent-color); }

    .method-switcher {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        border-radius: 8px;
        overflow: hidden;
        margin-bottom: 18px;
    }
    .method-switcher input[type="radio"] { display: none; }
    .method-switcher label {
        text-align: center;
        padding: 12px 8px;
        cursor: pointer;
        background-color: rgba(0,0,0,0.2);
        color: var(--text-muted);
        transition: all 0.3s;
        font-weight: 500;
        border-right: 1px solid rgba(255,255,255,.08);
    }
    .method-switcher label:last-child { border-right: 0; }
    .method-switcher input[type="radio"]:checked + label {
        background-color: var(--accent-color);
        color: #fff;
    }
    @media (max-width: 640px) {
        .method-switcher { grid-template-columns: 1fr; }
        .method-switcher label { border-right: 0; border-bottom: 1px solid rgba(255,255,255,.08); }
    }

    .submit-btn {
        width: 100%;
        padding: 12px;
        font-size: 1rem;
        font-weight: 600;
        color: #fff;
        border: none;
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.3s;
        background-color: var(--success-color);
    }
    .submit-btn:hover { filter: brightness(1.08); transform: translateY(-2px); }
    .ai-btn { background: linear-gradient(135deg, var(--accent-color), #8b5cf6); }
    .error-message, .success-message {
        text-align: center;
        font-size: 0.95rem;
        margin-top: 15px;
        padding: 12px;
        border-radius: 8px;
    }
    .error-message { color: #fff; background: rgba(220, 53, 69, .22); border: 1px solid rgba(220, 53, 69, .4); }
    .success-message { color: #fff; background: rgba(40, 167, 69, .22); border: 1px solid rgba(40, 167, 69, .4); }
    .ai-grid { display:grid; grid-template-columns: 1fr 1fr; gap: 14px; }
    @media (max-width: 760px) { .ai-grid { grid-template-columns:1fr; } }
    .security-pill {
        display: inline-flex; align-items: center; gap: 8px;
        padding: 8px 10px; border-radius: 999px;
        background: rgba(255,255,255,.08); color: var(--text-muted); font-size: .84rem;
        margin-bottom: 14px;
    }
    .generated-prompt-box {
        margin-top: 14px; background: rgba(0,0,0,.25); border: 1px solid rgba(255,255,255,.12);
        border-radius: 8px; padding: 12px; color: var(--text-muted); font-size: .88rem; line-height: 1.45;
        white-space: pre-wrap;
    }
</style>

<div class="page-header">
    <h1><i class="fas fa-th-large" style="color: var(--accent-color);"></i> Gerenciar Cards</h1>
</div>

<div class="content-card">
    <div class="two-column-grid">
        <div class="column-box">
            <h3>1. Selecione e Visualize</h3>
            <div class="form-group">
                <label for="card-selector">Card para Editar:</label>
                <select id="card-selector" class="form-select">
                    <?php foreach ($card_types as $key => $details): ?>
                        <option value="<?= htmlspecialchars($key, ENT_QUOTES, 'UTF-8') ?>" <?= ($key === $current_card_key) ? 'selected' : '' ?>>
                            <?= htmlspecialchars($details['name'], ENT_QUOTES, 'UTF-8') ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <label>Prévia Atual:</label>
            <div class="preview-area">
                <?php if ($showPreview): ?>
                    <img src="<?= htmlspecialchars($imageFilex, ENT_QUOTES, 'UTF-8') ?>?v=<?= time() ?>" alt="Preview do Card" onerror="this.onerror=null;this.src='imgelementos/semimagem.png';">
                <?php else: ?>
                    <span class="no-image">Nenhum card definido ou imagem não encontrada.</span>
                <?php endif; ?>
            </div>
            <p class="current-method-info">Método Atual: <strong><?= htmlspecialchars($methord, ENT_QUOTES, 'UTF-8') ?></strong></p>
            <?php if ($showPreview): ?>
                <p class="current-method-info">Origem: <strong><?= htmlspecialchars($imageFilex, ENT_QUOTES, 'UTF-8') ?></strong></p>
            <?php endif; ?>
            <p class="current-method-info">Chave IA: <strong><?= htmlspecialchars(aiCardMaskKey((string)($aiConfig['api_key'] ?? '')), ENT_QUOTES, 'UTF-8') ?></strong></p>
        </div>

        <div class="column-box">
            <h3>2. Altere ou Crie a Imagem</h3>
            <div class="method-switcher">
                <input type="radio" id="upload-radio" name="upload-type" value="file" checked>
                <label for="upload-radio"><i class="fas fa-upload"></i> Enviar Arquivo</label>

                <input type="radio" id="url-radio" name="upload-type" value="url">
                <label for="url-radio"><i class="fas fa-link"></i> Usar URL</label>

                <input type="radio" id="ai-radio" name="upload-type" value="ai">
                <label for="ai-radio"><i class="fas fa-wand-magic-sparkles"></i> Criar com IA</label>
            </div>

            <div class="forms-container" style="margin-top: 20px;">
                <form method="post" enctype="multipart/form-data" id="upload-form" class="method-form" action="card.php?tipo=<?= htmlspecialchars($current_card_key, ENT_QUOTES, 'UTF-8') ?>">
                    <input type="hidden" name="card_type" value="<?= htmlspecialchars($current_card_key, ENT_QUOTES, 'UTF-8') ?>">
                    <div class="form-group">
                        <label for="image">Selecione uma imagem (PNG, JPG, GIF, WebP):</label>
                        <input class="form-control" type="file" name="image" id="image" accept="image/*">
                        <p class="form-hint">O arquivo será convertido e salvo como PNG para funcionar em todos os modelos do gerador.</p>
                    </div>
                    <button class="submit-btn" type="submit" name="upload"><i class="fas fa-paper-plane"></i> Enviar</button>
                </form>

                <form method="post" id="url-form" class="method-form" style="display: none;" action="card.php?tipo=<?= htmlspecialchars($current_card_key, ENT_QUOTES, 'UTF-8') ?>">
                    <input type="hidden" name="card_type" value="<?= htmlspecialchars($current_card_key, ENT_QUOTES, 'UTF-8') ?>">
                    <div class="form-group">
                        <label for="image-url">Insira a URL direta da imagem:</label>
                        <input class="form-control" type="text" name="image-url" id="image-url" placeholder="https://...">
                        <p class="form-hint">A imagem será baixada e salva localmente como PNG.</p>
                    </div>
                    <button class="submit-btn" type="submit" name="url-submit"><i class="fas fa-save"></i> Baixar e Salvar</button>
                </form>

                <form method="post" id="ai-form" class="method-form" style="display: none;" action="card.php?tipo=<?= htmlspecialchars($current_card_key, ENT_QUOTES, 'UTF-8') ?>">
                    <input type="hidden" name="card_type" value="<?= htmlspecialchars($current_card_key, ENT_QUOTES, 'UTF-8') ?>">
                    <span class="security-pill"><i class="fas fa-lock"></i> A chave fica salva apenas no servidor deste painel.</span>

                    <div class="form-group">
                        <label for="ai_provider">Provedor de IA:</label>
                        <select class="form-select" name="ai_provider" id="ai_provider">
                            <?php $providerAtual = aiCardNormalizeProvider((string)($aiConfig['provider'] ?? 'openai')); ?>
                            <?php foreach ($aiProviders as $value => $label): ?>
                                <option value="<?= htmlspecialchars($value, ENT_QUOTES, 'UTF-8') ?>" <?= $providerAtual === $value ? 'selected' : '' ?>><?= htmlspecialchars($label, ENT_QUOTES, 'UTF-8') ?></option>
                            <?php endforeach; ?>
                        </select>
                        <p class="form-hint">Use OpenAI quando tiver saldo/crédito ativo. Se aparecer limite de cobrança, escolha a alternativa sem chave.</p>
                    </div>

                    <div class="ai-grid">
                        <div class="form-group">
                            <label for="ai_api_key">Chave da IA / OpenAI API Key:</label>
                            <input class="form-control" type="password" name="ai_api_key" id="ai_api_key" placeholder="Cole uma nova chave ou deixe vazio para usar a salva">
                            <p class="form-hint">Atual: <?= htmlspecialchars(aiCardMaskKey((string)($aiConfig['api_key'] ?? '')), ENT_QUOTES, 'UTF-8') ?>. Na alternativa sem chave, este campo não é obrigatório.</p>
                        </div>
                        <div class="form-group">
                            <label for="ai_api_url">URL da API:</label>
                            <input class="form-control" type="text" name="ai_api_url" id="ai_api_url" value="<?= htmlspecialchars((string)($aiConfig['api_url'] ?? aiCardProviderDefaultUrl((string)($aiConfig['provider'] ?? 'openai'))), ENT_QUOTES, 'UTF-8') ?>">
                            <p class="form-hint">OpenAI: https://api.openai.com/v1/images/generations | Alternativa sem chave: https://image.pollinations.ai/prompt</p>
                        </div>
                    </div>

                    <div class="ai-grid">
                        <div class="form-group">
                            <label for="ai_model">Modelo:</label>
                            <select class="form-select" name="ai_model" id="ai_model">
                                <?php
                                $modelAtual = (string)($aiConfig['model'] ?? 'gpt-image-1');
                                $models = ['gpt-image-1', 'gpt-image-1-mini', 'gpt-image-2', 'chatgpt-image-latest', 'dall-e-3', 'dall-e-2', 'flux', 'turbo'];
                                foreach ($models as $model): ?>
                                    <option value="<?= htmlspecialchars($model, ENT_QUOTES, 'UTF-8') ?>" <?= $modelAtual === $model ? 'selected' : '' ?>><?= htmlspecialchars($model, ENT_QUOTES, 'UTF-8') ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="ai_size">Tamanho:</label>
                            <select class="form-select" name="ai_size" id="ai_size">
                                <?php
                                $sizeAtual = (string)($aiConfig['size'] ?? '1024x1024');
                                $sizes = ['1024x1024', '1024x1536', '1536x1024', '1792x1024', '1024x1792'];
                                foreach ($sizes as $size): ?>
                                    <option value="<?= htmlspecialchars($size, ENT_QUOTES, 'UTF-8') ?>" <?= $sizeAtual === $size ? 'selected' : '' ?>><?= htmlspecialchars($size, ENT_QUOTES, 'UTF-8') ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="ai-grid">
                        <div class="form-group">
                            <label for="ai_quality">Qualidade:</label>
                            <select class="form-select" name="ai_quality" id="ai_quality">
                                <?php
                                $qualityAtual = (string)($aiConfig['quality'] ?? 'medium');
                                $qualities = ['low' => 'Baixa / rápida', 'medium' => 'Média', 'high' => 'Alta', 'auto' => 'Automática', 'standard' => 'DALL-E Standard', 'hd' => 'DALL-E HD'];
                                foreach ($qualities as $value => $label): ?>
                                    <option value="<?= htmlspecialchars($value, ENT_QUOTES, 'UTF-8') ?>" <?= $qualityAtual === $value ? 'selected' : '' ?>><?= htmlspecialchars($label, ENT_QUOTES, 'UTF-8') ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="ai_style">Tema visual automático:</label>
                            <select class="form-select" name="ai_style" id="ai_style">
                                <?php $styleAtual = (string)($aiConfig['style'] ?? 'premium_esportivo'); ?>
                                <?php foreach ($aiStyles as $value => $label): ?>
                                    <option value="<?= htmlspecialchars($value, ENT_QUOTES, 'UTF-8') ?>" <?= $styleAtual === $value ? 'selected' : '' ?>><?= htmlspecialchars($label, ENT_QUOTES, 'UTF-8') ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="ai_title">Título/ideia para o card:</label>
                        <input class="form-control" type="text" name="ai_title" id="ai_title" placeholder="Ex: rodada premium, champions, brasileirão, clássico de hoje">
                        <p class="form-hint">O sistema transforma esse título em um prompt completo automaticamente.</p>
                    </div>

                    <div class="form-group">
                        <label for="ai_prompt">Instrução adicional opcional:</label>
                        <textarea class="form-control" name="ai_prompt" id="ai_prompt" placeholder="Ex: mais escuro, com bordas douradas, sem personagens, deixar centro limpo..."></textarea>
                    </div>

                    <div class="form-group" style="display:flex; align-items:center; gap:10px;">
                        <input type="checkbox" name="ai_save_key" id="ai_save_key" checked style="width:auto;">
                        <label for="ai_save_key" style="margin:0;">Salvar chave/configuração da IA para próximas gerações</label>
                    </div>

                    <button class="submit-btn ai-btn" type="submit" name="ai-submit"><i class="fas fa-wand-magic-sparkles"></i> Gerar Card Automaticamente com IA</button>
                    <p class="form-hint">Recomendação: gere cards sem texto. O sistema já coloca nomes dos times, horário, campeonato e canais por cima.</p>
                </form>
            </div>
            <?php if (!empty($errorMessage)): ?>
                <p class="error-message"><?= htmlspecialchars($errorMessage, ENT_QUOTES, 'UTF-8') ?></p>
            <?php endif; ?>
            <?php if (!empty($successMessage)): ?>
                <p class="success-message"><?= htmlspecialchars($successMessage, ENT_QUOTES, 'UTF-8') ?></p>
            <?php endif; ?>
            <?php if (!empty($aiPromptGerado)): ?>
                <div class="generated-prompt-box"><strong>Prompt usado pela IA:</strong><br><?= htmlspecialchars($aiPromptGerado, ENT_QUOTES, 'UTF-8') ?></div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.6.0/dist/confetti.browser.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const cardSelector = document.getElementById('card-selector');
    cardSelector.addEventListener('change', function() {
        window.location.href = 'card.php?tipo=' + encodeURIComponent(this.value);
    });

    const uploadRadio = document.getElementById('upload-radio');
    const urlRadio = document.getElementById('url-radio');
    const aiRadio = document.getElementById('ai-radio');
    const uploadForm = document.getElementById('upload-form');
    const urlForm = document.getElementById('url-form');
    const aiForm = document.getElementById('ai-form');
    const aiProvider = document.getElementById('ai_provider');
    const aiApiUrl = document.getElementById('ai_api_url');
    const aiModel = document.getElementById('ai_model');

    function updateProviderDefaults() {
        if (!aiProvider || !aiApiUrl || !aiModel) return;
        if (aiProvider.value === 'pollinations') {
            if (aiApiUrl.value.indexOf('api.openai.com') !== -1 || aiApiUrl.value.trim() === '') {
                aiApiUrl.value = 'https://image.pollinations.ai/prompt';
            }
            if (aiModel.value.indexOf('gpt') === 0 || aiModel.value.indexOf('dall-e') === 0 || aiModel.value === 'chatgpt-image-latest') {
                aiModel.value = 'flux';
            }
        } else {
            if (aiApiUrl.value.indexOf('image.pollinations.ai') !== -1 || aiApiUrl.value.trim() === '') {
                aiApiUrl.value = 'https://api.openai.com/v1/images/generations';
            }
            if (aiModel.value === 'flux' || aiModel.value === 'turbo') {
                aiModel.value = 'gpt-image-1';
            }
        }
    }
    if (aiProvider) { aiProvider.addEventListener('change', updateProviderDefaults); }

    function switchForms() {
        uploadForm.style.display = uploadRadio.checked ? 'block' : 'none';
        urlForm.style.display = urlRadio.checked ? 'block' : 'none';
        aiForm.style.display = aiRadio.checked ? 'block' : 'none';
    }

    uploadRadio.addEventListener('change', switchForms);
    urlRadio.addEventListener('change', switchForms);
    aiRadio.addEventListener('change', switchForms);
    switchForms();

    <?php if (!empty($successMessage)): ?>
        confetti({ particleCount: 150, spread: 90, origin: { y: 0.5 }, zIndex: 9999 });
        setTimeout(() => {
            window.location.href = window.location.pathname + '?tipo=<?= htmlspecialchars($redirect_card_key, ENT_QUOTES, 'UTF-8') ?>';
        }, 1800);
    <?php endif; ?>
});
</script>

<?php include "includes/footer.php"; ?>
