<?php
// activar_public.php
include('includes/functions.php');

// Conectar a la DB de códigos
$api_db_path = __DIR__.'/api/codes.db';
$api_db = new SQLite3($api_db_path);

$show_success_modal = false;
$error = '';

if (isset($_POST['activar_cuenta'])) {
    $codigo = trim($_POST['codigo_activacion'] ?? '');

    if ($codigo === '') {
        $error = "Por favor ingresa un código de activación.";
    } else {
        // Buscar el código en codes.db
        $stmt = $api_db->prepare("SELECT * FROM codes WHERE codigo = :codigo AND estado = 0 LIMIT 1");
        $stmt->bindValue(':codigo', $codigo, SQLITE3_TEXT);
        $result = $stmt->execute();
        $datos = $result->fetchArray(SQLITE3_ASSOC);

        if (!$datos) {
            $error = "Código inválido o ya usado.";
        } else {
            $mac = $datos['mac_address'];
            $dns_id = $datos['dns_id'];

            // Verificar duplicado
            $exists = $db->select('playlist', '*', "mac_address='$mac' AND dns_id='$dns_id'");
            if ($exists) {
                $error = "⚠️ Esta MAC ya tiene una cuenta en el mismo servidor DNS.";
            } else {
                // Insertar en playlist
                $datos_playlist = [
                    'dns_id' => $dns_id,
                    'mac_address' => $mac,
                    'username' => $datos['username'],
                    'password' => $datos['password'],
                    'pin' => $datos['pin'],
                    'device_key' => $datos['device_key']
                ];

                if ($db->insert('playlist', $datos_playlist)) {
                    // Marcar como usado
                    $update = $api_db->prepare("UPDATE codes SET estado = 1 WHERE codigo = :codigo");
                    $update->bindValue(':codigo', $codigo, SQLITE3_TEXT);
                    $update->execute();
                    
                    $show_success_modal = true;
                } else {
                    $error = "Error al activar la cuenta.";
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Activación de Cuenta</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        .neon-border {
            box-shadow: 0 0 10px #bc13fe;
            border: 1px solid #0ff;
        }
        .neon-text {
            text-shadow: 0 0 5px #0ff;
            color: #0ff;
        }
        .neon-button {
            background: linear-gradient(45deg, #08f, #0ff);
            box-shadow: 0 0 10px #0ff;
        }
        .bg-dark {
            background-color: #0f172a;
        }
        .checkmark {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            display: block;
            stroke-width: 5;
            stroke: #0ff;
            stroke-miterlimit: 10;
            margin: 0 auto;
            box-shadow: 0 0 15px #0ff;
            animation: fill .4s ease-in-out .4s forwards, scale .3s ease-in-out .9s both;
        }
        .checkmark-circle {
            stroke-dasharray: 166;
            stroke-dashoffset: 166;
            stroke-width: 5;
            stroke-miterlimit: 10;
            stroke: #0ff;
            fill: none;
            animation: stroke .6s cubic-bezier(0.65, 0, 0.45, 1) forwards;
        }
        .checkmark-check {
            transform-origin: 50% 50%;
            stroke-dasharray: 48;
            stroke-dashoffset: 48;
            animation: stroke .3s cubic-bezier(0.65, 0, 0.45, 1) .8s forwards;
        }
        @keyframes stroke {
            100% { stroke-dashoffset: 0; }
        }
        @keyframes scale {
            0%, 100% { transform: none; }
            50% { transform: scale3d(1.1, 1.1, 1); }
        }
        @keyframes fill {
            100% { box-shadow: inset 0 0 0 100px rgba(0, 255, 255, 0.1); }
        }
         /* Aviso flotante tipo neon en el centro */
.neon-alert {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%) scale(0.8);
    background: rgba(0, 255, 150, 0.2);
    color: #00ffcc;
    border: 2px solid #00ffcc;
    padding: 15px 30px;
    font-size: 18px;
    font-weight: bold;
    border-radius: 10px;
    box-shadow: 0 0 15px #00ffcc, 0 0 30px #00ffcc;
    opacity: 0;
    transition: opacity 0.5s ease, transform 0.5s ease;
    z-index: 9999;
    pointer-events: none;
    text-shadow: 0 0 5px #00ffcc, 0 0 15px #00ffcc;
}
    </style>
</head>
<body class="bg-dark min-h-screen flex items-center justify-center p-4">
    <div class="w-full max-w-md">
        <div class="neon-border bg-gray-900 rounded-xl p-6">
            <h1 class="neon-text text-2xl font-bold text-center mb-6">ACTIVACIÓN POR CÓDIGO</h1>
            
            <?php if ($error): ?>
                <div class="mb-4 p-3 bg-red-900 text-red-100 rounded-lg border border-red-500 text-sm">
                    <?= htmlspecialchars($error) ?>
                </div>
            <?php endif; ?>
            
            <form method="post" class="space-y-4">
                <div>
                    <label class="block text-cyan-300 mb-1 text-sm">Código de Activación</label>
                    <input type="text" name="codigo_activacion" placeholder="Ingrese el código" required
                        class="w-full px-3 py-2 bg-gray-800 border border-cyan-500 rounded-lg text-white focus:outline-none focus:ring-1 focus:ring-cyan-400 text-sm">
                </div>

                <div class="pt-2">
                    <button type="submit" name="activar_cuenta"
                        class="neon-button w-full py-2 px-4 rounded-lg text-white font-bold uppercase tracking-wider text-sm">
                        ACTIVAR CUENTA
                    </button>
                </div>
            </form>
        </div>
    </div>

    <?php if ($show_success_modal): ?>
    <div id="successModal" class="fixed inset-0 bg-black bg-opacity-80 flex items-center justify-center z-50" style="display: flex;">
        <div class="neon-border bg-gray-900 rounded-xl p-6 max-w-sm w-full mx-4">
            <div class="text-center">
                <svg class="checkmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">
                    <circle class="checkmark-circle" cx="26" cy="26" r="25" fill="none"/>
                    <path class="checkmark-check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8"/>
                </svg>
                
                <h2 class="neon-text text-xl font-bold mt-4 mb-2">¡ACTIVACIÓN EXITOSA!</h2>
                <p class="text-gray-300 mb-4">Dispositivo activado correctamente. Recarga tu app para cargar el contenido.</p>
                
                <button onclick="cerrarModal()"
                    class="neon-button px-4 py-2 rounded-lg text-white text-sm">
                    Cerrar
                </button>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <script>
    function cerrarModal() {
        document.getElementById('successModal').style.display = 'none';
    }

    // Cerrar al hacer clic fuera del modal
    window.addEventListener('click', (event) => {
        if (event.target === document.getElementById('successModal')) {
            cerrarModal();
        }
    });
    </script>
        <script>
        // Función para mostrar el aviso flotante
        function showNeonAlert(mensaje) {
            let aviso = document.createElement('div');
            aviso.className = 'neon-alert';
            aviso.textContent = mensaje;
            document.body.appendChild(aviso);

            // Mostrar con transición
            setTimeout(() => aviso.style.opacity = '1', 50);

            // Ocultar y eliminar después de 2 segundos
            setTimeout(() => {
                aviso.style.opacity = '0';
                setTimeout(() => aviso.remove(), 500);
            }, 2000);
        }

        // Bloquear clic derecho EXCEPTO en inputs y textareas
        document.addEventListener('contextmenu', function(e) {
            // Permitir clic derecho en elementos de formulario
            if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') {
                return; // No prevenir el comportamiento por defecto
            }
            
            e.preventDefault();
            showNeonAlert('⚠ Acceso restringido');
        });

        // Bloquear teclas (independiente de may/min)
        document.addEventListener('keydown', function(e) {
            const key = e.key.toLowerCase();

            if (key === 'f12' || 
                (e.ctrlKey && e.shiftKey && key === 'i') || 
                (e.ctrlKey && e.shiftKey && key === 'j') ||
                (e.ctrlKey && key === 'u')) {

                e.preventDefault();
                showNeonAlert('⚠ Acceso restringido');
            }
        });
    </script>
</body>
</html>