<?php
session_start();

if (!isset($_SESSION['reseller_logged_in']) || !$_SESSION['reseller_logged_in']) {
    header('Location: resellers_login.php');
    exit;
}

// generar_public_reseller.php
include('includes/functions.php');

// Función para normalizar MAC
function normalise_mac(string $raw): string {
    $raw = trim($raw);
    if (strpos($raw, '00:') === 0) $raw = substr($raw, 3);
    $hex = preg_replace('/[^0-9a-fA-F]/', '', $raw);
    $pairs = array_filter(str_split($hex, 2), fn($p) => strlen($p) === 2);
    return strtoupper(implode(':', $pairs));
}

// Función para generar código
function generar_codigo(): string {
    return str_pad(random_int(0, 99999999), 8, '0', STR_PAD_LEFT);
}

// Procesar formulario
$error = '';
$codigo_generado = '';
$mac_normalizada = '';
$device_key = '';
$mensaje_whatsapp = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $mac_raw = $_POST['mac_address'] ?? '';
    $dns_id = (int)($_POST['dns_id'] ?? 0);
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';
    $pin = $_POST['pin'] ?? '0000';

    if (empty($mac_raw) || empty($username) || empty($password) || $dns_id <= 0) {
        $error = "⚠️ Todos los campos son requeridos";
    } else {
        $mac_normalizada = normalise_mac($mac_raw);
        $codigo_generado = generar_codigo();
        $device_key = str_pad(random_int(0, 99999999), 8, '0', STR_PAD_LEFT);

        // Preparar URL para WhatsApp
        $is_https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || 
                   (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443);
        $scheme = $is_https ? 'https' : 'http';
        $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
        $dir = rtrim(dirname($_SERVER['PHP_SELF'] ?? ''), '/\\');
        $base = $dir ? "$scheme://$host$dir" : "$scheme://$host";
        $url_activacion = $base . "/activar_public.php";
        $mensaje_whatsapp = "🚀 *Estimado cliente se ha generado un código para la*
📡 MAC: *$mac_normalizada*

Tu *código de activación* es: 
🔐 *$codigo_generado*

✅ Copia tu código y activa tu servicio aquí:
👉 $url_activacion

☺️ *Gracias por preferirnos*.";
        // Guardar en la base de datos
        $api_db_path = __DIR__.'/api/codes.db';
        $api_db = new SQLite3($api_db_path);
        
        $stmt = $api_db->prepare("INSERT INTO codes 
            (mac_address, dns_id, username, password, pin, device_key, codigo, estado) 
            VALUES (:mac, :dns, :user, :pass, :pin, :devkey, :code, 0)");
        
        $stmt->bindValue(':mac', $mac_normalizada, SQLITE3_TEXT);
        $stmt->bindValue(':dns', $dns_id, SQLITE3_INTEGER);
        $stmt->bindValue(':user', $username, SQLITE3_TEXT);
        $stmt->bindValue(':pass', $password, SQLITE3_TEXT);
        $stmt->bindValue(':pin', $pin, SQLITE3_TEXT);
        $stmt->bindValue(':devkey', $device_key, SQLITE3_TEXT);
        $stmt->bindValue(':code', $codigo_generado, SQLITE3_TEXT);
        
        if (!$stmt->execute()) {
            $error = "❌ Error al guardar en la base de datos";
        }
        $api_db->close();
    }
}

// Obtener lista de DNS
$dnss = $db->select('dns', '*', '', '');
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generador Público para Resellers</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        .neon-border {
            box-shadow: 0 0 10px #bc13fe;
            transition: all 0.3s ease;
        }
        .neon-text {
            text-shadow: 0 0 5px #0ff;
            color: #0ff;
        }
        .neon-button {
            background: linear-gradient(45deg, #08f, #0ff);
            transition: all 0.3s ease;
        }
        .bg-dark {
            background-color: #0f172a;
        }
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.7);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }
        .modal-content {
            background: #1e293b;
            border-radius: 0.5rem;
            padding: 1.5rem;
            width: 90%;
            max-width: 400px;
            border: 1px solid #0ff;
            box-shadow: 0 0 20px #0ff;
        }
        .glass-effect {
            background: rgba(15, 23, 42, 0.8);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
        }
        body {
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body class="bg-dark min-h-screen">
    <!-- Navbar -->
    <nav class="glass-effect p-4 border-b border-cyan-500/20 sticky top-0 z-50 w-full">
        <div class="container mx-auto flex justify-between items-center">
            <!-- Logo/Title -->
            <h1 class="neon-text text-2xl font-bold">Gestión de Subresellers</h1>
            
            <!-- Desktop Menu -->
            <div class="hidden md:flex items-center space-x-6">
                <a href="resellers_login.php" class="flex items-center text-cyan-300 hover:text-cyan-100 transition">
                    <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"></path>
                    </svg>
                    Panel Principal
                </a>
                <a href="subresellers_codes.php" class="flex items-center text-cyan-300 hover:text-cyan-100 transition">
                    <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                    </svg>
                    Códigos para Resellers
                </a>
                <a href="generar_public.php" class="flex items-center text-cyan-300 hover:text-cyan-100 transition">
                    <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                    </svg>
                    Códigos de Activación Clientes
                </a>
                <a href="activar_public.php" class="flex items-center text-cyan-300 hover:text-cyan-100 transition">
                    <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 7a2 2 0 012 2m4 0a6 6 0 01-12 0 6 6 0 0112 0z"></path>
                    </svg>
                    Activar Código
                </a>
                <a href="resellers_login.php?logout=1" class="flex items-center text-red-400 hover:text-red-300 transition">
                    <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h3a3 3 0 013 3v1"></path>
                    </svg>
                    Cerrar Sesión
                </a>
            </div>

            <!-- Mobile Menu Button -->
            <button id="menu-toggle" class="md:hidden text-cyan-300 hover:text-cyan-100 focus:outline-none">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path>
                </svg>
            </button>
        </div>

        <!-- Mobile Menu -->
        <div id="mobile-menu" class="hidden md:hidden bg-gray-900 bg-opacity-90 glass-effect border-t border-cyan-500/20">
            <div class="container mx-auto py-4 flex flex-col space-y-4">
                <a href="resellers_login.php" class="flex items-center text-cyan-300 hover:text-cyan-100 transition px-4 py-2">
                    <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"></path>
                    </svg>
                    Panel Principal
                </a>
                <a href="subresellers_codes.php" class="flex items-center text-cyan-300 hover:text-cyan-100 transition px-4 py-2">
                    <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                    </svg>
                    Códigos para Resellers
                </a>
                <a href="generar_public.php" class="flex items-center text-cyan-300 hover:text-cyan-100 transition px-4 py-2">
                    <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                    </svg>
                    Códigos de Activación Clientes
                </a>
                <a href="activar_public.php" class="flex items-center text-cyan-300 hover:text-cyan-100 transition px-4 py-2">
                    <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 7a2 2 0 012 2m4 0a6 6 0 01-12 0 6 6 0 0112 0z"></path>
                    </svg>
                    Activar Código
                </a>
                <a href="resellers_login.php?logout=1" class="flex items-center text-red-400 hover:text-red-300 transition px-4 py-2">
                    <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h3a3 3 0 013 3v1"></path>
                    </svg>
                    Cerrar Sesión
                </a>
            </div>
        </div>
    </nav>
<script>
    // Toggle mobile menu
        document.getElementById('menu-toggle').addEventListener('click', function() {
            const mobileMenu = document.getElementById('mobile-menu');
            mobileMenu.classList.toggle('hidden');
        });
</script>
    <!-- Contenido principal -->
    <main class="flex items-center justify-center p-4 pt-24"> <!-- Añadido pt-24 para espacio debajo del nav -->
        <div class="w-full max-w-md relative">
            <div class="neon-border bg-gray-900 bg-opacity-80 rounded-xl p-6">
                <h1 class="neon-text text-2xl font-bold text-center mb-6">GENERADOR DE CÓDIGOS</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">DNS</label>
                        <select name="dns_id" 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">
                            <option value="">Seleccionar DNS</option>
                            <?php foreach ($dnss as $dns): ?>
                                <option value="<?= htmlspecialchars($dns['id']) ?>">
                                    <?= htmlspecialchars($dns['title']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div>
                        <label class="block text-cyan-300 mb-1 text-sm">MAC Address</label>
                        <input type="text" name="mac_address" placeholder="00:1A:2B:3C:4D:5E" 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>
                        <label class="block text-cyan-300 mb-1 text-sm">Username</label>
                        <input type="text" name="username" 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>
                        <label class="block text-cyan-300 mb-1 text-sm">Password</label>
                        <input type="text" name="password" 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>
                        <label class="block text-cyan-300 mb-1 text-sm">Parental PIN</label>
                        <input type="text" name="pin" placeholder="0000"
                            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" 
                            class="neon-button w-full py-2 px-4 rounded-lg text-white font-bold uppercase tracking-wider text-sm">
                            GENERAR CÓDIGO
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </main>

        <?php if ($codigo_generado): ?>
        <div id="resultModal" class="modal" style="display: flex;">
            <div class="modal-content">
                <div class="text-center">
                    <h2 class="neon-text text-xl font-bold mb-4">CÓDIGO GENERADO</h2>
                    
                    <div class="space-y-3 text-left mb-4">
                        <p><span class="text-cyan-300">MAC:</span> <span class="text-white"><?= htmlspecialchars($mac_normalizada) ?></span></p>
                        <p><span class="text-cyan-300">Código:</span> <span class="text-white font-bold"><?= htmlspecialchars($codigo_generado) ?></span></p>
                        <p><span class="text-cyan-300">Device Key:</span> <span class="text-white"><?= htmlspecialchars($device_key) ?></span></p>
                    </div>
                    
                    <div class="flex flex-col space-y-2">
    <button onclick="copiarCodigo()"
        class="px-4 py-2 bg-cyan-600 hover:bg-cyan-500 rounded-lg text-white text-sm">
        📋 Copiar Código
    </button>
    <a href="https://wa.me/?text=<?= urlencode($mensaje_whatsapp) ?>" target="_blank"
        class="px-4 py-2 bg-green-600 hover:bg-green-500 rounded-lg text-white text-sm text-center">
        📤 Compartir por WhatsApp
    </a>
    <a href="activar_public.php"
        class="px-4 py-2 bg-purple-600 hover:bg-purple-500 rounded-lg text-white text-sm text-center">
        🔗 Ir a Activación
    </a>
    <button onclick="cerrarModal()"
        class="px-4 py-2 bg-gray-600 hover:bg-gray-500 rounded-lg text-white text-sm">
        Cerrar
    </button>
</div>
</div>
</div>
</div>
<?php endif; ?>
</div>

    <script>
    function copiarCodigo() {
        const codigo = "<?= htmlspecialchars($codigo_generado) ?>";
        navigator.clipboard.writeText(codigo).then(() => {
            alert('Código copiado: ' + codigo);
        });
    }

    function cerrarModal() {
        document.getElementById('resultModal').style.display = 'none';
    }

    // Cerrar modal al hacer clic fuera
    window.addEventListener('click', (event) => {
        if (event.target === document.getElementById('resultModal')) {
            cerrarModal();
        }
    });
    </script>
</body>
</html>