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

// 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 close() {
        $this->db->close();
    }
}

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

// 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);
}

// Función para normalizar MAC (copiada de admin.php)
function normalise_mac(string $raw): string {
    $dec = base64_decode($raw, true);
    if ($dec !== false) $raw = $dec;
    $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));
}

// Procesar login
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login'])) {
    if (!verify_csrf_token($_POST['csrf_token'])) {
        $login_error = "Error de validación CSRF";
    } else {
        $code = filter_input(INPUT_POST, 'code', FILTER_SANITIZE_STRING);
        if (preg_match('/^\d{6}$/', $code)) {
            $result = $db_codes->select('reseller_codes', '*', 'code = :code AND is_active = 1', '', [':code' => $code]);
            if (!empty($result)) {
                $_SESSION['reseller_logged_in'] = true;
                $_SESSION['reseller_code'] = $code;
                $_SESSION['reseller_name'] = $result[0]['reseller_name'];
                header('Location: ' . basename($_SERVER['PHP_SELF']));
                exit;
            } else {
                $login_error = "Código inválido o inactivo";
            }
        } else {
            $login_error = "El código debe ser exactamente 6 dígitos numéricos";
        }
    }
}

// Cerrar sesión
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: ' . basename($_SERVER['PHP_SELF']));
    exit;
}

// Si no está logueado, mostrar formulario de login
if (!isset($_SESSION['reseller_logged_in']) || !$_SESSION['reseller_logged_in']) {
    ?>
    <!DOCTYPE html>
    <html lang="es">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Acceso Resellers</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%); }
            .code-input { letter-spacing: 4px; font-size: 1.8rem; text-align: center; padding: 15px; background: rgba(30, 41, 59, 0.8); color: #0ff; border: 2px solid #0ff; border-radius: 12px; text-shadow: 0 0 5px #0ff; }
            .code-input:focus { box-shadow: 0 0 20px #0ff; outline: none; }
        </style>
    </head>
    <body class="bg-dark min-h-screen flex items-center justify-center p-4">
        <div class="neon-border rounded-2xl p-8 bg-gray-900 bg-opacity-90 backdrop-blur-sm">
            <div class="text-center mb-8">
                <h1 class="neon-text text-4xl font-bold mb-4">🔐 ACCESO RESELLERS</h1>
                <p class="text-cyan-300 text-lg">Ingrese su código de 6 dígitos</p>
            </div>
            <?php if (isset($login_error)) { ?>
                <div class="mb-6 p-4 bg-red-900 text-red-100 rounded-lg border border-red-500"><?php echo htmlspecialchars($login_error); ?></div>
            <?php } ?>
            <form method="POST" action="" class="space-y-6">
                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(generate_csrf_token()); ?>">
                <div>
                    <label for="code" class="block text-cyan-300 mb-2">Código de acceso</label>
                    <input type="text" class="code-input w-full" id="code" name="code" 
                           maxlength="6" pattern="\d{6}" title="6 dígitos numéricos" 
                           required autocomplete="off" placeholder="000000">
                </div>
                <button type="submit" name="login" class="neon-button w-full py-4 px-6 rounded-xl text-white font-bold text-lg">
                    🚀 INGRESAR
                </button>
            </form>
        </div>
        <script>
            document.getElementById("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>
    <?php
    exit;
}

// Procesar búsqueda por MAC
$search_results = [];
$search_error = '';
$search_mac = '';

// Procesar agregar, actualizar, eliminar cliente
$add_success = '';
$add_error = '';
$update_success = '';
$update_error = '';
$delete_success = '';
$delete_error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST['csrf_token'])) {
        $add_error = $update_error = $delete_error = "Error de validación CSRF";
    } else {
        // Búsqueda
        if (isset($_POST['search_mac'])) {
            $search_mac = $_POST['search_mac'] ?? '';
            $normalized_mac = normalise_mac($search_mac);
            
            if (count(explode(':', $normalized_mac)) === 8) {
                try {
                    $search_results = $db->select('playlist', '*', 'mac_address = :mac', '', [':mac' => $normalized_mac]);
                    if (empty($search_results)) {
                        $search_error = "No se encontraron clientes con la MAC: " . htmlspecialchars($normalized_mac);
                    }
                } catch (Exception $e) {
                    $search_error = "Error en la base de datos: " . htmlspecialchars($e->getMessage());
                }
            } else {
                $search_error = "Formato de MAC inválido. Debe tener 8 pares (16 caracteres)";
            }
        }
        
        // Agregar cliente
        if (isset($_POST['action']) && $_POST['action'] === 'add_client') {
            $dns_id = filter_input(INPUT_POST, 'dns_id', FILTER_VALIDATE_INT);
            $mac_address = normalise_mac($_POST['mac_address'] ?? '');
            $username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
            $password = $_POST['password'] ?? '';
            $pin = preg_match('/^\d{4}$/', $_POST['pin']) ? $_POST['pin'] : '0000';
            
            // Generar device_key (como en admin.php)
            $chars = '1234567890';
            $device_key = '';
            for ($i = 0; $i < 8; $i++) {
                $device_key .= $chars[random_int(0, strlen($chars) - 1)];
            }
            
            if ($dns_id && count(explode(':', $mac_address)) === 8 && $username && $password) {
                try {
                    // Verificar si ya existe con el mismo DNS
                    $existing = $db->select('playlist', '*', 'mac_address = :mac AND dns_id = :dns', '', [':mac' => $mac_address, ':dns' => $dns_id]);
                    if (!empty($existing)) {
                        $add_error = "Esta MAC ya tiene una cuenta con el mismo servidor DNS";
                    } else {
                        $data = [
                            'dns_id' => $dns_id,
                            'mac_address' => $mac_address,
                            'username' => $username,
                            'password' => $password,
                            'pin' => $pin,
                            'device_key' => $device_key
                        ];
                        
                        if ($db->insert('playlist', $data)) {
                            $add_success = "✅ Cliente agregado correctamente";
                            $_POST = [];
                        } else {
                            $add_error = "❌ Error al agregar el cliente";
                        }
                    }
                } catch (Exception $e) {
                    $add_error = "Error al guardar cliente: " . htmlspecialchars($e->getMessage());
                }
            } else {
                $add_error = "❌ Todos los campos son requeridos y la MAC debe ser válida";
            }
        }
        
        // Actualizar cliente
        if (isset($_POST['action']) && $_POST['action'] === 'update_client') {
            $id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
            $dns_id = filter_input(INPUT_POST, 'dns_id', FILTER_VALIDATE_INT);
            $mac_address = normalise_mac($_POST['mac_address'] ?? '');
            $username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
            $password = $_POST['password'] ?? '';
            $pin = preg_match('/^\d{4}$/', $_POST['pin']) ? $_POST['pin'] : '0000';
            
            if ($id && $dns_id && count(explode(':', $mac_address)) === 8 && $username && $password) {
                try {
                    // Verificar si ya existe con el mismo DNS (excluyendo el registro actual)
                    $existing = $db->select('playlist', '*', 'mac_address = :mac AND dns_id = :dns AND id != :id', '', [':mac' => $mac_address, ':dns' => $dns_id, ':id' => $id]);
                    if (!empty($existing)) {
                        $update_error = "Esta MAC ya tiene una cuenta con el mismo servidor DNS";
                    } else {
                        $data = [
                            'dns_id' => $dns_id,
                            'mac_address' => $mac_address,
                            'username' => $username,
                            'password' => $password,
                            'pin' => $pin
                        ];
                        
                        if ($db->update('playlist', $data, 'id = :id', [':id' => $id])) {
                            $update_success = "✅ Cliente actualizado correctamente";
                            if (!empty($search_mac)) {
                                $search_results = $db->select('playlist', '*', 'mac_address = :mac', '', [':mac' => normalise_mac($search_mac)]);
                            }
                        } else {
                            $update_error = "❌ Error al actualizar el cliente";
                        }
                    }
                } catch (Exception $e) {
                    $update_error = "Error al actualizar cliente: " . htmlspecialchars($e->getMessage());
                }
            } else {
                $update_error = "❌ Todos los campos son requeridos y la MAC debe ser válida";
            }
        }
        
        // Eliminar cliente
        if (isset($_POST['action']) && $_POST['action'] === 'delete_client') {
            $id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
            if ($id) {
                try {
                    if ($db->delete('playlist', 'id = :id', [':id' => $id])) {
                        $delete_success = "✅ Cliente eliminado correctamente";
                        if (!empty($search_mac)) {
                            $search_results = $db->select('playlist', '*', 'mac_address = :mac', '', [':mac' => normalise_mac($search_mac)]);
                        }
                    } else {
                        $delete_error = "❌ Error al eliminar el cliente";
                    }
                } catch (Exception $e) {
                    $delete_error = "Error al eliminar cliente: " . htmlspecialchars($e->getMessage());
                }
            } else {
                $delete_error = "❌ ID inválido";
            }
        }
    }
}

// Obtener DNS para dropdown y mapa de títulos
try {
    $dnss = $db->select('dns', '*', '', '');
    $dnsTitles = [];
    foreach ($dnss as $dns) {
        $dnsTitles[$dns['id']] = $dns['title'];
    }
} catch (Exception $e) {
    $dnss = [];
    $dnsTitles = [];
    $search_error = "Error al cargar DNS: " . htmlspecialchars($e->getMessage());
}
?>
<!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 Clientes MAC</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); }
        .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ódigo 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 href="?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="?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>

    <!-- Main Content -->
    <div class="container mx-auto p-6">
        <!-- Mensajes de éxito/error -->
        <?php if ($add_success || $update_success || $delete_success) { ?>
            <div class="neon-border border-green-500 rounded-2xl p-4 glass-effect mb-6">
                <div class="text-green-400 text-center text-lg">
                    <?php echo htmlspecialchars($add_success ?: ($update_success ?: $delete_success)); ?>
                </div>
            </div>
        <?php } ?>
        
        <?php if ($add_error || $update_error || $delete_error) { ?>
            <div class="neon-border border-red-500 rounded-2xl p-4 glass-effect mb-6">
                <div class="text-red-400 text-center text-lg">
                    <?php echo htmlspecialchars($add_error ?: ($update_error ?: $delete_error)); ?>
                </div>
            </div>
        <?php } ?>

        <!-- Search Form -->
        <div class="neon-border rounded-2xl p-6 glass-effect mb-8">
            <h2 class="neon-text text-xl font-bold mb-4">🔍 BUSCAR CLIENTE POR MAC</h2>
            <form method="POST" class="space-y-4">
                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(generate_csrf_token()); ?>">
                <div>
                    <label class="block text-cyan-300 mb-2">MAC Address (8 pares)</label>
                    <input type="text" name="search_mac" value="<?php echo htmlspecialchars($search_mac); ?>" 
                           placeholder="00:11:22:33:44:55:66:77" required
                           class="w-full px-4 py-3 bg-gray-800 border border-cyan-500 rounded-lg text-white text-center font-mono">
                </div>
                <button type="submit" class="neon-button w-full py-3 px-6 rounded-lg text-white font-bold">
                    🔍 BUSCAR
                </button>
            </form>
        </div>

        <!-- Results -->
        <?php if ($search_error) { ?>
            <div class="neon-border border-red-500 rounded-2xl p-6 glass-effect mb-8">
                <div class="text-red-400 text-center">
                    <span class="text-2xl">⚠️</span>
                    <p class="text-lg"><?php echo htmlspecialchars($search_error); ?></p>
                </div>
            </div>
        <?php } ?>

        <?php if (!empty($search_results)) { ?>
        <div class="neon-border rounded-2xl p-6 glass-effect">
            <h2 class="neon-text text-xl font-bold mb-6">📋 RESULTADOS DE BÚSQUEDA</h2>
            <div class="overflow-x-auto">
                <table class="w-full text-white">
                    <thead>
                        <tr class="text-cyan-300 border-b border-cyan-500/30">
                            <th class="px-4 py-3">DNS</th>
                            <th class="px-4 py-3">MAC Address</th>
                            <th class="px-4 py-3">Username</th>
                            <th class="px-4 py-3">Password</th>
                            <th class="px-4 py-3">PIN</th>
                            <th class="px-4 py-3">Device Key</th>
                            <th class="px-4 py-3">Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($search_results as $row) { ?>
                        <tr class="border-b border-gray-700/50 hover:bg-cyan-900/20">
                            <td class="px-4 py-3 text-center"><?php echo htmlspecialchars($dnsTitles[$row['dns_id']] ?? 'Unknown DNS'); ?></td>
                            <td class="px-4 py-3 text-center font-mono"><?php echo htmlspecialchars($row['mac_address']); ?></td>
                            <td class="px-4 py-3 text-center"><?php echo htmlspecialchars($row['username']); ?></td>
                            <td class="px-4 py-3 text-center"><?php echo htmlspecialchars($row['password']); ?></td>
                            <td class="px-4 py-3 text-center"><?php echo htmlspecialchars($row['pin'] ?? '0000'); ?></td>
                            <td class="px-4 py-3 text-center font-mono"><?php echo htmlspecialchars($row['device_key']); ?></td>
                            <td class="px-4 py-3 text-center">
                                <button onclick="openEditModal('<?php echo $row['id']; ?>', '<?php echo $row['dns_id']; ?>', '<?php echo htmlspecialchars($row['mac_address']); ?>', '<?php echo htmlspecialchars($row['username']); ?>', '<?php echo htmlspecialchars($row['password']); ?>', '<?php echo htmlspecialchars($row['pin'] ?? '0000'); ?>')" class="bg-blue-500 text-white px-2 py-1 rounded">Editar</button>
                                <form method="POST" style="display: inline;">
                                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(generate_csrf_token()); ?>">
                                    <input type="hidden" name="action" value="delete_client">
                                    <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
                                    <button type="submit" onclick="return confirm('¿Está seguro de eliminar este cliente?')" class="bg-red-500 text-white px-2 py-1 rounded">Eliminar</button>
                                </form>
                            </td>
                        </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php } ?>

        <!-- Add Client Form -->
        <div class="neon-border rounded-2xl p-6 glass-effect mt-8">
            <h2 class="neon-text text-xl font-bold mb-6">➕ AGREGAR NUEVO CLIENTE</h2>
            <form method="POST" action="" class="space-y-4">
                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(generate_csrf_token()); ?>">
                <input type="hidden" name="action" value="add_client">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-cyan-300 mb-2">DNS</label>
                        <select name="dns_id" required class="w-full px-4 py-3 bg-gray-800 border border-cyan-500 rounded-lg text-white">
                            <option value="">Seleccionar DNS</option>
                            <?php foreach ($dnss as $dns) { ?>
                                <option value="<?php echo htmlspecialchars($dns['id']); ?>" <?php echo (isset($_POST['dns_id']) && $_POST['dns_id'] == $dns['id']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($dns['title']); ?>
                                </option>
                            <?php } ?>
                        </select>
                    </div>
                    <div>
                        <label class="block text-cyan-300 mb-2">MAC Address</label>
                        <input type="text" name="mac_address" value="<?php echo htmlspecialchars($_POST['mac_address'] ?? ''); ?>" 
                               placeholder="00:11:22:33:44:55:66:77" required
                               class="w-full px-4 py-3 bg-gray-800 border border-cyan-500 rounded-lg text-white font-mono">
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-cyan-300 mb-2">Username</label>
                        <input type="text" name="username" value="<?php echo htmlspecialchars($_POST['username'] ?? ''); ?>" required
                               class="w-full px-4 py-3 bg-gray-800 border border-cyan-500 rounded-lg text-white">
                    </div>
                    <div>
                        <label class="block text-cyan-300 mb-2">Password</label>
                        <input type="password" name="password" value="<?php echo htmlspecialchars($_POST['password'] ?? ''); ?>" required
                               class="w-full px-4 py-3 bg-gray-800 border border-cyan-500 rounded-lg text-white">
                    </div>
                </div>
                <div>
                    <label class="block text-cyan-300 mb-2">Parental PIN</label>
                    <input type="text" name="pin" value="<?php echo htmlspecialchars($_POST['pin'] ?? '0000'); ?>" required
                           class="w-full px-4 py-3 bg-gray-800 border border-cyan-500 rounded-lg text-white">
                </div>
                <button type="submit" class="neon-button w-full py-3 px-6 rounded-lg text-white font-bold">
                    💾 GUARDAR CLIENTE
                </button>
            </form>
        </div>

        <!-- Edit Modal -->
        <div id="editModal" class="modal">
            <div class="modal-content neon-border rounded-2xl p-6">
                <h2 class="neon-text text-xl font-bold mb-4">✏️ EDITAR CLIENTE</h2>
                <form method="POST" action="" class="space-y-4">
                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(generate_csrf_token()); ?>">
                    <input type="hidden" name="action" value="update_client">
                    <input type="hidden" name="id" id="edit_id">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-cyan-300 mb-2">DNS</label>
                            <select name="dns_id" id="edit_dns_id" required class="w-full px-4 py-3 bg-gray-800 border border-cyan-500 rounded-lg text-white">
                                <option value="">Seleccionar DNS</option>
                                <?php foreach ($dnss as $dns) { ?>
                                    <option value="<?php echo htmlspecialchars($dns['id']); ?>"><?php echo htmlspecialchars($dns['title']); ?></option>
                                <?php } ?>
                            </select>
                        </div>
                        <div>
                            <label class="block text-cyan-300 mb-2">MAC Address</label>
                            <input type="text" name="mac_address" id="edit_mac_address" required
                                   class="w-full px-4 py-3 bg-gray-800 border border-cyan-500 rounded-lg text-white font-mono">
                        </div>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-cyan-300 mb-2">Username</label>
                            <input type="text" name="username" id="edit_username" required
                                   class="w-full px-4 py-3 bg-gray-800 border border-cyan-500 rounded-lg text-white">
                        </div>
                        <div>
                            <label class="block text-cyan-300 mb-2">Password</label>
                            <input type="password" name="password" id="edit_password" required
                                   class="w-full px-4 py-3 bg-gray-800 border border-cyan-500 rounded-lg text-white">
                        </div>
                    </div>
                    <div>
                        <label class="block text-cyan-300 mb-2">Parental PIN</label>
                        <input type="text" name="pin" id="edit_pin" required
                               class="w-full px-4 py-3 bg-gray-800 border border-cyan-500 rounded-lg text-white">
                    </div>
                    <div class="flex justify-end space-x-4">
                        <button type="button" onclick="closeEditModal()" class="bg-gray-500 text-white py-2 px-4 rounded">Cancelar</button>
                        <button type="submit" class="neon-button py-2 px-4 rounded text-white font-bold">Guardar Cambios</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
    // Auto-formato MAC address para formulario de agregar
    document.querySelector('input[name="mac_address"]').addEventListener('input', function(e) {
        let value = this.value.replace(/[^0-9A-Fa-f]/g, '');
        if (value.length > 16) value = value.substring(0, 16);
        let formatted = '';
        for (let i = 0; i < value.length; i += 2) {
            if (i > 0) formatted += ':';
            formatted += value.substring(i, i + 2);
        }
        this.value = formatted.toUpperCase();
    });

    // Validación antes de enviar para formulario de agregar
    document.querySelector('form[action=""]').addEventListener('submit', function(e) {
        const macInput = document.querySelector('input[name="mac_address"]');
        const macValue = macInput.value.replace(/:/g, '');
        if (macValue.length !== 16) {
            e.preventDefault();
            alert('La MAC debe tener exactamente 16 caracteres (8 pares)');
            macInput.focus();
        }
    });

    // Funciones para el modal de edición
    function openEditModal(id, dns_id, mac_address, username, password, pin) {
        document.getElementById('editModal').style.display = 'flex';
        document.getElementById('edit_id').value = id;
        document.getElementById('edit_dns_id').value = dns_id;
        document.getElementById('edit_mac_address').value = mac_address;
        document.getElementById('edit_username').value = username;
        document.getElementById('edit_password').value = password;
        document.getElementById('edit_pin').value = pin;

        // Auto-formato para MAC en el modal
        document.getElementById('edit_mac_address').addEventListener('input', function(e) {
            let value = this.value.replace(/[^0-9A-Fa-f]/g, '');
            if (value.length > 16) value = value.substring(0, 16);
            let formatted = '';
            for (let i = 0; i < value.length; i += 2) {
                if (i > 0) formatted += ':';
                formatted += value.substring(i, i + 2);
            }
            this.value = formatted.toUpperCase();
        });
    }

    function closeEditModal() {
        document.getElementById('editModal').style.display = 'none';
    }

    window.onclick = function(event) {
        if (event.target == document.getElementById('editModal')) {
            closeEditModal();
        }
    }
    </script>
</body>
</html>