<?php
session_start();

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

// Conectar a la base de datos de códigos
class SQLiteWrapperCodes {
    private $db;
    public function __construct($path) {
        $this->db = new SQLite3($path);
    }
    public function select($table, $columns, $where = '', $order = '', $params = []) {
        $query = "SELECT $columns FROM $table";
        if ($where) $query .= " WHERE $where";
        if ($order) $query .= " ORDER BY $order";
        $stmt = $this->db->prepare($query);
        foreach ($params as $key => $value) {
            $stmt->bindValue($key, $value);
        }
        $result = $stmt->execute();
        $rows = [];
        while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
            $rows[] = $row;
        }
        return $rows;
    }
    public function insert($table, $data) {
        $columns = implode(', ', array_keys($data));
        $placeholders = ':' . implode(', :', array_keys($data));
        $query = "INSERT INTO $table ($columns) VALUES ($placeholders)";
        $stmt = $this->db->prepare($query);
        foreach ($data as $key => $value) {
            $stmt->bindValue(":$key", $value);
        }
        return $stmt->execute();
    }
    public function update($table, $data, $where, $params) {
        $set = implode(', ', array_map(fn($k) => "$k = :$k", array_keys($data)));
        $query = "UPDATE $table SET $set WHERE $where";
        $stmt = $this->db->prepare($query);
        foreach ($data as $key => $value) {
            $stmt->bindValue(":$key", $value);
        }
        foreach ($params as $key => $value) {
            $stmt->bindValue($key, $value);
        }
        return $stmt->execute();
    }
    public function delete($table, $where, $params) {
        $query = "DELETE FROM $table WHERE $where";
        $stmt = $this->db->prepare($query);
        foreach ($params as $key => $value) {
            $stmt->bindValue($key, $value);
        }
        return $stmt->execute();
    }
    public function exec($query) {
        return $this->db->exec($query);
    }
    public function close() {
        $this->db->close();
    }
}

$db_codes = new SQLiteWrapperCodes('api/codigos_reseller.db');

// Añadir columna parent_reseller_code si no existe
$result = $db_codes->select('sqlite_master', 'sql', "type='table' AND name='reseller_codes'");
if ($result && strpos($result[0]['sql'], 'parent_reseller_code') === false) {
    $db_codes->exec('ALTER TABLE reseller_codes ADD COLUMN parent_reseller_code TEXT');
}

// Funciones para CSRF
function generate_csrf_token() {
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function verify_csrf_token($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

// Generar código único
function generate_unique_code($db_codes) {
    $chars = '0123456789';
    do {
        $code = '';
        for ($i = 0; $i < 6; $i++) {
            $code .= $chars[random_int(0, strlen($chars) - 1)];
        }
        $existing = $db_codes->select('reseller_codes', '*', 'code = :code', '', [':code' => $code]);
    } while (!empty($existing));
    return $code;
}

// Procesar acciones
$status = $_GET['status'] ?? '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && verify_csrf_token($_POST['csrf_token'])) {
    // Generar nuevo código
    if (isset($_POST['submit'])) {
        $reseller_code = filter_input(INPUT_POST, 'reseller_code', FILTER_SANITIZE_STRING);
        $reseller_name = filter_input(INPUT_POST, 'reseller_name', FILTER_SANITIZE_STRING);
        if (!empty($reseller_code) && !empty($reseller_name)) {
            // Validar el código de reseller
            $result = $db_codes->select('reseller_codes', '*', 'code = :code AND is_active = 1 AND parent_reseller_code IS NULL', '', [':code' => $reseller_code]);
            if (!empty($result) && $reseller_code === $_SESSION['reseller_code']) {
                $code = generate_unique_code($db_codes);
                $data = [
                    'code' => $code,
                    'reseller_name' => $reseller_name,
                    'created_at' => date('c'),
                    'is_active' => 1,
                    'parent_reseller_code' => $reseller_code
                ];
                if ($db_codes->insert('reseller_codes', $data)) {
                    echo "<script>window.location.href='".basename($_SERVER['SCRIPT_NAME'])."?status=1'</script>";
                } else {
                    $error = "❌ Error al generar el código";
                }
            } else {
                $error = "❌ Código de reseller inválido o no autorizado";
            }
        } else {
            $error = "❌ El código de reseller y el nombre son requeridos";
        }
    }

    // Actualizar código
    if (isset($_POST['submitU'])) {
        $id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
        $reseller_name = filter_input(INPUT_POST, 'reseller_name', FILTER_SANITIZE_STRING);
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        $regenerate = isset($_POST['regenerate']) ? 1 : 0;

        if ($id && !empty($reseller_name)) {
            // Verificar que el código pertenece al reseller autenticado
            $result = $db_codes->select('reseller_codes', '*', 'id = :id AND parent_reseller_code = :parent', '', [':id' => $id, ':parent' => $_SESSION['reseller_code']]);
            if (!empty($result)) {
                $data = [
                    'reseller_name' => $reseller_name,
                    'is_active' => $is_active
                ];
                if ($regenerate) {
                    $data['code'] = generate_unique_code($db_codes);
                    $data['created_at'] = date('c');
                }
                if ($db_codes->update('reseller_codes', $data, 'id = :id AND parent_reseller_code = :parent', [':id' => $id, ':parent' => $_SESSION['reseller_code']])) {
                    echo "<script>window.location.href='".basename($_SERVER['SCRIPT_NAME'])."?status=1'</script>";
                } else {
                    $error = "❌ Error al actualizar el código";
                }
            } else {
                $error = "❌ Código no encontrado o no autorizado";
            }
        } else {
            $error = "❌ ID inválido o nombre del reseller requerido";
        }
    }

    // Eliminar código
    if (isset($_POST['delete'])) {
        $id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
        if ($id) {
            $result = $db_codes->select('reseller_codes', '*', 'id = :id AND parent_reseller_code = :parent', '', [':id' => $id, ':parent' => $_SESSION['reseller_code']]);
            if (!empty($result)) {
                if ($db_codes->delete('reseller_codes', 'id = :id AND parent_reseller_code = :parent', [':id' => $id, ':parent' => $_SESSION['reseller_code']])) {
                    echo "<script>window.location.href='".basename($_SERVER['SCRIPT_NAME'])."?status=2'</script>";
                } else {
                    $error = "❌ Error al eliminar el código";
                }
            } else {
                $error = "❌ Código no encontrado o no autorizado";
            }
        } else {
            $error = "❌ ID inválido";
        }
    }

    // Inactivar/Activar código
    if (isset($_POST['toggle_active'])) {
        $id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
        $new_status = filter_input(INPUT_POST, 'new_status', FILTER_VALIDATE_INT);
        if ($id && in_array($new_status, [0, 1])) {
            $result = $db_codes->select('reseller_codes', '*', 'id = :id AND parent_reseller_code = :parent', '', [':id' => $id, ':parent' => $_SESSION['reseller_code']]);
            if (!empty($result)) {
                if ($db_codes->update('reseller_codes', ['is_active' => $new_status], 'id = :id AND parent_reseller_code = :parent', [':id' => $id, ':parent' => $_SESSION['reseller_code']])) {
                    echo "<script>window.location.href='".basename($_SERVER['SCRIPT_NAME'])."?status=1'</script>";
                } else {
                    $error = "❌ Error al cambiar el estado del código";
                }
            } else {
                $error = "❌ Código no encontrado o no autorizado";
            }
        } else {
            $error = "❌ ID o estado inválido";
        }
    }
}

// Obtener códigos de subresellers para el reseller autenticado
$codes = $db_codes->select('reseller_codes', '*', 'parent_reseller_code = :parent', 'id DESC', [':parent' => $_SESSION['reseller_code']]);
$codeU = isset($_GET['update']) ? $db_codes->select('reseller_codes', '*', 'id = :id AND parent_reseller_code = :parent', '', [':id' => $_GET['update'], ':parent' => $_SESSION['reseller_code']]) : [];
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestión de Códigos de Subresellers</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        .neon-border { box-shadow: 0 0 15px #bc13fe; border: 2px solid #0ff; }
        .neon-text { text-shadow: 0 0 10px #0ff; color: #0ff; }
        .neon-button { background: linear-gradient(45deg, #08f, #0ff); box-shadow: 0 0 15px #0ff; transition: all 0.3s ease; }
        .neon-button:hover { box-shadow: 0 0 25px #0ff, 0 0 40px #0ff; transform: translateY(-2px); }
        .bg-dark { background: linear-gradient(135deg, #0f172a 0%, #1e293b 50%, #0f172a 100%); }
        .glass-effect { background: rgba(30, 41, 59, 0.8); backdrop-filter: blur(10px); }
        .code-input { letter-spacing: 2px; font-size: 1.2rem; padding: 10px; background: rgba(30, 41, 59, 0.8); color: #0ff; border: 2px solid #0ff; border-radius: 8px; text-shadow: 0 0 5px #0ff; }
        .code-input:focus { box-shadow: 0 0 20px #0ff; outline: none; }
        .modal { display: none; position: fixed; z-index: 50; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.4); align-items: center; justify-content: center; }
        .modal-content { background-color: #1e293b; padding: 20px; border: 1px solid #0ff; width: 80%; max-width: 600px; border-radius: 12px; }
    </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">
        <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_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 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>

    <!-- Contenido principal -->
    <div class="container mx-auto p-4">
        <!-- Mensajes de estado -->
        <?php if ($status == 1) { ?>
            <div class="mb-4 p-4 bg-green-900 text-green-100 rounded-lg border border-green-500 text-center">✅ Operación realizada correctamente</div>
        <?php } elseif ($status == 2) { ?>
            <div class="mb-4 p-4 bg-red-900 text-red-100 rounded-lg border border-red-500 text-center">✅ Código eliminado correctamente</div>
        <?php } elseif ($error) { ?>
            <div class="mb-4 p-4 bg-red-900 text-red-100 rounded-lg border border-red-500 text-center"><?php echo htmlspecialchars($error); ?></div>
        <?php } ?>

        <!-- Formulario para generar nuevo código -->
        <?php if (isset($_GET['create'])) { ?>
            <div class="mb-8">
                <div class="neon-border rounded-2xl p-6 bg-gray-900 bg-opacity-90 backdrop-blur-sm">
                    <h2 class="neon-text text-2xl font-bold mb-4 text-center">🔑 Generar Código de Subreseller</h2>
                    <form method="POST" class="space-y-4">
                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(generate_csrf_token()); ?>">
                        <div>
                            <label for="reseller_code" class="block text-cyan-300 mb-2">Código de Reseller</label>
                            <input type="text" class="code-input w-full" id="reseller_code" name="reseller_code" 
                                   maxlength="6" pattern="\d{6}" title="6 dígitos numéricos" 
                                   required autocomplete="off" placeholder="000000" value="<?php echo htmlspecialchars($_SESSION['reseller_code']); ?>">
                        </div>
                        <div>
                            <label for="reseller_name" class="block text-cyan-300 mb-2">Nombre del Subreseller</label>
                            <input type="text" class="code-input w-full" id="reseller_name" name="reseller_name" 
                                   required placeholder="Nombre del Subreseller">
                        </div>
                        <div class="text-cyan-300 text-sm">
                            Al hacer clic en "Generar", se creará un código de 6 dígitos único asociado a este reseller.
                        </div>
                        <button type="submit" name="submit" class="neon-button w-full py-3 px-6 rounded-xl text-white font-bold">
                            🚀 Generar
                        </button>
                    </form>
                </div>
            </div>
        <?php } elseif (isset($_GET['update']) && !empty($codeU)) { ?>
            <!-- Formulario para editar código -->
            <div class="mb-8">
                <div class="neon-border rounded-2xl p-6 bg-gray-900 bg-opacity-90 backdrop-blur-sm">
                    <h2 class="neon-text text-2xl font-bold mb-4 text-center">✏️ Editar Código de Subreseller</h2>
                    <form method="POST" class="space-y-4">
                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(generate_csrf_token()); ?>">
                        <input type="hidden" name="id" value="<?php echo htmlspecialchars($codeU[0]['id']); ?>">
                        <div>
                            <label for="reseller_name" class="block text-cyan-300 mb-2">Nombre del Subreseller</label>
                            <input type="text" class="code-input w-full" id="reseller_name" name="reseller_name" 
                                   value="<?php echo htmlspecialchars($codeU[0]['reseller_name']); ?>" required>
                        </div>
                        <div>
                            <label for="code" class="block text-cyan-300 mb-2">Código</label>
                            <input type="text" class="code-input w-full" value="<?php echo htmlspecialchars($codeU[0]['code']); ?>" disabled>
                        </div>
                        <div>
                            <label class="block text-cyan-300 mb-2">Estado</label>
                            <label class="flex items-center text-cyan-300">
                                <input type="checkbox" name="is_active" class="mr-2" <?php echo $codeU[0]['is_active'] ? 'checked' : ''; ?>> Activo
                            </label>
                        </div>
                        <div>
                            <label class="block text-cyan-300 mb-2">Regenerar Código</label>
                            <label class="flex items-center text-cyan-300">
                                <input type="checkbox" name="regenerate" class="mr-2"> Generar un nuevo código
                            </label>
                        </div>
                        <button type="submit" name="submitU" class="neon-button w-full py-3 px-6 rounded-xl text-white font-bold">
                            💾 Guardar
                        </button>
                    </form>
                </div>
            </div>
        <?php } else { ?>
            <!-- Tabla principal de códigos -->
            <div class="mb-8">
                <div class="neon-border rounded-2xl p-6 bg-gray-900 bg-opacity-90 backdrop-blur-sm">
                    <h2 class="neon-text text-2xl font-bold mb-4 text-center">📋 Códigos de Subresellers</h2>
                    <div class="text-center mb-4">
                        <a href="./<?php echo basename($_SERVER['SCRIPT_NAME']); ?>?create" class="neon-button py-2 px-4 rounded text-white font-bold">
                            ➕ Nuevo Código
                        </a>
                    </div>
                   <div class="overflow-x-auto">
    <table class="w-full min-w-[600px] text-cyan-300 text-sm">
        <thead class="bg-gray-800">
            <tr>
                <th class="p-2 text-left">ID</th>
                <th class="p-2 text-left">Código</th>
                <th class="p-2 text-left">Nombre del Subreseller</th>
                <th class="p-2 text-left">Fecha de Creación</th>
                <th class="p-2 text-left">Estado</th>
                <th class="p-2 text-left">Acciones</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($codes as $row) { ?>
                <tr class="border-b border-gray-700 hover:bg-gray-800/50">
                    <td class="p-2"><?php echo htmlspecialchars($row['id']); ?></td>
                    <td class="p-2"><?php echo htmlspecialchars($row['code']); ?></td>
                    <td class="p-2"><?php echo htmlspecialchars($row['reseller_name']); ?></td>
                    <td class="p-2"><?php echo htmlspecialchars($row['created_at']); ?></td>
                    <td class="p-2"><?php echo $row['is_active'] ? 'Activo' : 'Inactivo'; ?></td>
                    <td class="p-2 flex flex-wrap gap-2">
                        <a href="./<?php echo basename($_SERVER['SCRIPT_NAME']); ?>?update=<?php echo $row['id']; ?>" class="neon-button py-1 px-3 rounded text-sm">✏️ Editar</a>
                        <form method="POST" class="inline">
                            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(generate_csrf_token()); ?>">
                            <input type="hidden" name="toggle_active" value="1">
                            <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
                            <input type="hidden" name="new_status" value="<?php echo $row['is_active'] ? 0 : 1; ?>">
                            <button type="submit" class="py-1 px-3 rounded text-sm <?php echo $row['is_active'] ? 'bg-yellow-600 hover:bg-yellow-500' : 'bg-green-600 hover:bg-green-500'; ?> text-white">
                                <?php echo $row['is_active'] ? '🚫 Inactivar' : '✅ Activar'; ?>
                            </button>
                        </form>
                        <button onclick="openDeleteModal(<?php echo $row['id']; ?>)" class="bg-red-600 hover:bg-red-500 py-1 px-3 rounded text-sm text-white">🗑️ Eliminar</button>
                    </td>
                </tr>
            <?php } ?>
        </tbody>
    </table>
</div>
                </div>
            </div>
        <?php } ?>

        <!-- Modal para eliminar código -->
        <div id="deleteModal" class="modal">
            <div class="modal-content">
                <h2 class="neon-text text-2xl font-bold mb-4 text-center">🗑️ Confirmar Eliminación</h2>
                <p class="text-cyan-300 mb-4">¿Realmente desea eliminar este código?</p>
                <form method="POST" class="flex justify-end space-x-4">
                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(generate_csrf_token()); ?>">
                    <input type="hidden" name="delete" value="1">
                    <input type="hidden" name="id" id="delete_id">
                    <button type="button" onclick="closeDeleteModal()" class="bg-gray-600 hover:bg-gray-500 py-2 px-4 rounded text-white">Cancelar</button>
                    <button type="submit" class="bg-red-600 hover:bg-red-500 py-2 px-4 rounded text-white">Eliminar</button>
                </form>
            </div>
        </div>
    </div>

    <script>
        // Toggle mobile menu
        document.getElementById('menu-toggle').addEventListener('click', function() {
            const mobileMenu = document.getElementById('mobile-menu');
            mobileMenu.classList.toggle('hidden');
        });

        // Funciones para modal de eliminación
        function openDeleteModal(id) {
            document.getElementById('delete_id').value = id;
            document.getElementById('deleteModal').style.display = 'flex';
        }

        function closeDeleteModal() {
            document.getElementById('deleteModal').style.display = 'none';
        }

        // Validar código de reseller en tiempo real
        document.getElementById('reseller_code')?.addEventListener('input', function(e) {
            this.value = this.value.replace(/[^0-9]/g, "");
            if (this.value.length > 6) {
                this.value = this.value.slice(0, 6);
            }
        });
    </script>
</body>
</html>