<?php
session_start(); // Necessário para salvar o código do captcha

// Configurações iniciais
require '../app/Controllers/auth.php';
require '../app/Controllers/layouts.php';

// --- LÓGICA DO CAPTCHA ---
// 1. Verifica se o formulário foi enviado
if (isset($_POST['register'])) {
    // Verifica se o código digitado bate com o da sessão
    if (!isset($_POST['captcha']) || $_POST['captcha'] != $_SESSION['vip_captcha']) {
        // Se estiver errado, define erro e impede o registro
        $toastMessage = "Código de verificación incorrecto";
        $toastType = "error";
        // Impede que o controller de auth processe (simulação, ajuste conforme sua controller real)
        // Você pode precisar adicionar uma flag aqui ou ajustar seu controller 'auth.php'
        // para checar o captcha antes de inserir no banco.
        $stopRegistration = true; 
    }
}

// 2. Gera um novo código aleatório de 4 dígitos para exibir (após a verificação)
$randomCode = rand(1000, 9999);
$_SESSION['vip_captcha'] = $randomCode;

// Fallback configs
if (!isset($stmtConfigsPlatformResult)) {
    $stmtConfigsPlatformResult = ['name_platform' => 'Plataforma', 'logo' => ''];
}
?>

<?php if (($stmtThemesPlatformResult['theme_actual'] ?? '') === 'brasileira') : ?>
  <script>window.location.href = '?theme=gringa2';</script>
<?php elseif (($stmtThemesPlatformResult['theme_actual'] ?? '') === 'gringa') : ?>
   <script>window.location.href = '?theme=gringa2';</script>
<?php elseif (($stmtThemesPlatformResult['theme_actual'] ?? '') === 'gringa2' || true) : ?>
<!DOCTYPE html>
<html lang="es-AR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Crear Cuenta</title>

    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://unpkg.com/imask"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&family=Oswald:wght@500&display=swap" rel="stylesheet">

    <script>
        tailwind.config = {
            theme: {
                fontFamily: { sans: ['Inter', 'sans-serif'], mono: ['Oswald', 'monospace'] },
                extend: {
                    colors: {
                        vip: {
                            blue: '#0EA5E9',
                            dark: '#0F172A',    
                            light: '#F0F9FF',   
                            gray: '#94A3B8',
                            red: '#EF4444',
                            green: '#10B981'
                        }
                    },
                    boxShadow: {
                        'soft': '0 20px 40px -10px rgba(14, 165, 233, 0.15)',
                        'glow': '0 0 20px rgba(14, 165, 233, 0.3)'
                    }
                }
            }
        }
    </script>

    <style>
        /* --- DESIGN SYSTEM V2 --- */
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 25%, #f093fb 50%, #4facfe 75%, #00f2fe 100%);
            background-size: 400% 400%;
            animation: gradientShift 15s ease infinite;
            min-height: 100vh;
            display: flex; align-items: center; justify-content: center;
            padding: 20px;
            position: relative;
            overflow-x: hidden;
        }
        
        @keyframes gradientShift {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }
        
        body::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: 
                radial-gradient(circle at 20% 30%, rgba(255, 255, 255, 0.1) 0%, transparent 50%),
                radial-gradient(circle at 80% 70%, rgba(255, 255, 255, 0.1) 0%, transparent 50%);
            pointer-events: none;
        }

        .register-card {
            width: 100%; max-width: 420px;
            background: rgba(255, 255, 255, 0.98);
            backdrop-filter: blur(20px);
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 24px;
            padding: 40px 35px;
            position: relative;
            box-shadow: 0 30px 60px -12px rgba(0, 0, 0, 0.25), 0 0 0 1px rgba(255, 255, 255, 0.1);
            border-top: 4px solid transparent;
            border-image: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%) 1;
            animation: fadeInUp 0.6s ease;
        }
        
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .input-group { position: relative; margin-bottom: 18px; }
        .input-label { font-size: 11px; color: #64748B; font-weight: 700; text-transform: uppercase; margin-bottom: 5px; display: block; }

        .vip-input {
            width: 100%; 
            background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%); 
            border: 2px solid #E2E8F0;
            padding: 16px 16px 16px 48px; 
            border-radius: 12px;
            font-size: 14px; 
            font-weight: 600;
            color: #334155; 
            transition: all 0.3s; 
            outline: none;
        }
        .vip-input:focus { 
            background: #FFF; 
            border-color: #667eea; 
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.15), 0 4px 15px rgba(102, 126, 234, 0.1);
            transform: translateY(-2px);
        }
        
        .input-icon {
            position: absolute; left: 16px; top: 40px; color: #94A3B8; 
            pointer-events: none; transition: all 0.3s;
        }
        .vip-input:focus + .input-icon { 
            color: #667eea; 
            transform: scale(1.1);
        }

        /* Estilos Específicos do Captcha */
        .captcha-container {
            display: flex; gap: 10px; align-items: flex-end;
        }
        .captcha-box {
            flex: 1;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
            background-size: 200% 200%;
            animation: gradientShift 3s ease infinite;
            color: #FFF; 
            font-family: 'Oswald', monospace; 
            font-size: 26px; 
            font-weight: 900;
            letter-spacing: 8px; 
            display: flex; 
            align-items: center; 
            justify-content: center;
            border-radius: 12px; 
            height: 48px; 
            user-select: none;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
            position: relative; 
            border: 2px solid rgba(255, 255, 255, 0.3);
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
        }
        /* Risco visual no captcha para "segurança" visual */
        .captcha-box::after {
            content: ''; position: absolute; top: 0; left: 0; right: 0; bottom: 0;
            background: linear-gradient(90deg, transparent 40%, rgba(255,255,255,0.1) 50%, transparent 60%);
            pointer-events: none;
        }

        .btn-action {
            width: 100%; 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
            background-size: 200% 200%;
            animation: gradientShift 3s ease infinite;
            color: white; 
            padding: 16px; 
            border-radius: 12px; 
            font-weight: 700;
            text-transform: uppercase; 
            font-size: 14px; 
            letter-spacing: 1.5px; 
            border: none;
            cursor: pointer; 
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4), 0 0 0 0 rgba(102, 126, 234, 0.4);
            transition: all 0.3s; 
            margin-top: 10px;
            position: relative;
            overflow: hidden;
        }
        .btn-action::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
            transition: left 0.5s;
        }
        .btn-action:hover::before {
            left: 100%;
        }
        .btn-action:hover {
            transform: translateY(-2px);
            box-shadow: 0 12px 35px rgba(102, 126, 234, 0.5), 0 0 0 4px rgba(102, 126, 234, 0.2);
        }
        .btn-action:active { transform: scale(0.98); }

        .tabs-pill {
            display: flex; 
            background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%); 
            border-radius: 50px;
            padding: 5px; 
            margin-bottom: 30px;
            box-shadow: inset 0 2px 4px rgba(0,0,0,0.1);
        }
        .tab-link {
            flex: 1; 
            text-align: center; 
            padding: 10px;
            font-size: 12px; 
            font-weight: 700; 
            color: #64748B;
            border-radius: 50px; 
            cursor: pointer; 
            text-decoration: none; 
            transition: all 0.3s;
        }
        .tab-link.active { 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
            color: white; 
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
            transform: scale(1.05);
        }

        #toast-container { position: fixed; top: 20px; left: 50%; transform: translateX(-50%); z-index: 9999; width: 90%; max-width: 400px; }
        .toast-custom {
            background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%); 
            border: 2px solid #E2E8F0; 
            border-left: 4px solid #667eea;
            color: #333; 
            padding: 18px 22px; 
            width: 100%;
            display: flex; 
            align-items: center; 
            gap: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.15), 0 0 0 1px rgba(102, 126, 234, 0.1); 
            border-radius: 12px;
            transform: translateY(-150%); 
            transition: transform 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            animation: slideDown 0.4s ease forwards;
        }
        @keyframes slideDown {
            from { transform: translateY(-150%); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
        .toast-custom.show { transform: translateY(0); }
    </style>
</head>
<body>

    <audio id="clickSound" src="https://cdn.freesound.org/previews/256/256113_3263906-lq.mp3"></audio>
    <div id="toast-container"></div>

    <?php if ($toastMessage) : ?>
      <script>
        document.addEventListener('DOMContentLoaded', () => {
            showToast('<?= htmlspecialchars($toastMessage) ?>', '<?= htmlspecialchars($toastType) ?>');
        });
      </script>
    <?php endif; ?>

    <div class="register-card">
        
        <div class="flex flex-col items-center mb-8">
            <div class="w-20 h-20 bg-gradient-to-br from-purple-500 via-pink-500 to-blue-500 rounded-2xl flex items-center justify-center shadow-2xl mb-4 transform rotate-3 animate-pulse" style="animation-duration: 2s;">
                <i data-lucide="zap" class="text-white w-10 h-10"></i>
            </div>
            <h1 class="text-3xl font-black bg-gradient-to-r from-purple-600 via-pink-600 to-blue-600 bg-clip-text text-transparent tracking-tight mb-2">
                <span class="text-purple-600"><?= htmlspecialchars($stmtConfigsPlatformResult['name_platform']) ?></span>
            </h1>
            <p class="text-xs text-gray-500 uppercase tracking-widest font-bold">Verificación de Seguridad</p>
        </div>

        <div class="tabs-pill sound-trigger">
            <a href="login.php" class="tab-link sound-trigger">LOGIN</a>
            <div class="tab-link active">REGISTRARSE</div>
        </div>

        <form method="POST" action="">
            
            <div class="input-group">
                <label class="input-label">Celular</label>
                <input type="text" name="phone" id="phone" class="vip-input sound-trigger" placeholder="(00) 00000-0000" required value="<?= htmlspecialchars($_POST['phone'] ?? '') ?>">
                <i data-lucide="smartphone" class="input-icon w-4 h-4"></i>
            </div>

            <div class="input-group">
                <label class="input-label">Contraseña</label>
                <input type="password" name="password" class="vip-input sound-trigger" placeholder="Mínimo 6 caracteres" required>
                <i data-lucide="lock" class="input-icon w-4 h-4"></i>
            </div>

            <div class="input-group">
                <label class="input-label">Código de Verificación</label>
                <div class="captcha-container">
                    <div class="relative w-full">
    <input 
        type="tel" 
        name="captcha" 
        class="vip-input sound-trigger w-full pl-10"
        placeholder="Ingrese el código" 
        maxlength="4" 
        required
    >

    <i 
        data-lucide="shield-check" 
        class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none">
    </i>
</div>

                    <div class="captcha-box" title="Código de seguridad">
                        <?= $randomCode ?>
                    </div>
                </div>
            </div>

            <div class="input-group">
                <label class="input-label">Cód. Referido (Opcional)</label>
                <input type="text" name="reference_code" class="vip-input sound-trigger" placeholder="Ej: CHEVRON10" value="<?= htmlspecialchars($affiliates_ref ?? $_POST['reference_code'] ?? '') ?>">
                <i data-lucide="ticket" class="input-icon w-4 h-4"></i>
            </div>

            <button type="submit" name="register" class="btn-action sound-trigger">
                Verificar y Crear Cuenta <i data-lucide="arrow-right" class="inline-block w-4 h-4 ml-1"></i>
            </button>

        </form>

        <div class="mt-6 text-center space-y-4">
            <a href="login.php" class="block text-vip-blue text-sm font-semibold hover:opacity-80 sound-trigger">
                <i data-lucide="user-check" class="w-4 h-4 inline mr-1"></i> ¿Ya tenés cuenta? Ingresar
            </a>
            <div class="text-[10px] text-gray-400 uppercase tracking-wider">Protección Anti-Bot Activa</div>
        </div>

    </div>

    <script>
        lucide.createIcons();

        // Máscara
        const phoneInput = document.getElementById('phone');
        if (phoneInput && typeof IMask !== 'undefined') {
            IMask(phoneInput, { mask: '(00) 00000-0000' });
        }

        // Som de Clique
        const audio = document.getElementById('clickSound');
        audio.volume = 0.2; 
        const playSound = () => {
            const playPromise = audio.play();
            if (playPromise !== undefined) { playPromise.catch(e => {}); }
            audio.currentTime = 0;
        };
        document.querySelectorAll('a, button, input, .tab-link').forEach(el => {
            el.addEventListener('mousedown', playSound);
        });

        // Toast
        function showToast(message, type = 'success') {
            const container = document.getElementById('toast-container');
            const toast = document.createElement('div');
            const isError = type !== 'success';
            const iconName = isError ? 'x-circle' : 'check-circle';
            const title = isError ? 'ERROR' : 'LISTO';
            const colorClass = isError ? 'text-vip-red' : 'text-vip-blue';
            toast.className = `toast-custom ${isError ? 'border-l-red-500' : 'border-l-green-500'}`;
            toast.innerHTML = `
                <div class="${colorClass}"><i data-lucide="${iconName}" class="w-7 h-7"></i></div>
                <div class="flex-1">
                    <p class="text-xs font-black text-gray-900 uppercase tracking-wide mb-1">${title}</p>
                    <p class="text-sm text-gray-600 font-sans leading-relaxed">${message}</p>
                </div>
            `;
            container.appendChild(toast);
            if (typeof lucide !== 'undefined') lucide.createIcons();
            setTimeout(() => toast.classList.add('show'), 10);
            setTimeout(() => { toast.classList.remove('show'); setTimeout(() => toast.remove(), 600); }, 3000);
        }
    </script>
</body>
</html>
<?php endif; ?>