<?php
session_start();

if (!isset($_SESSION['admin_logged'])) {
    if ($_POST && isset($_POST['admin_password'])) {
        if ($_POST['admin_password'] === 'admin123') {
            $_SESSION['admin_logged'] = true;
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit;
        } else {
            $admin_error = 'Contraseña incorrecta';
        }
    }
    if (!isset($_SESSION['admin_logged'])) {
        ?>
        <!DOCTYPE html>
        <html lang="es">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Admin Login - IPTV Panel</title>
            <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
            <style>
                * {
                    margin: 0;
                    padding: 0;
                    box-sizing: border-box;
                }
                
                body {
                    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                    background: linear-gradient(135deg, #0a0e27 0%, #1a1f3a 100%);
                    min-height: 100vh;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                }
                
                .login-container {
                    background: rgba(255, 255, 255, 0.05);
                    backdrop-filter: blur(10px);
                    border-radius: 20px;
                    padding: 40px;
                    width: 100%;
                    max-width: 400px;
                    border: 1px solid rgba(255, 255, 255, 0.1);
                    text-align: center;
                }
                
                .login-icon {
                    font-size: 60px;
                    color: #667eea;
                    margin-bottom: 20px;
                }
                
                h2 {
                    color: white;
                    margin-bottom: 10px;
                }
                
                .subtitle {
                    color: #a0aec0;
                    margin-bottom: 30px;
                    font-size: 14px;
                }
                
                .input-group {
                    position: relative;
                    margin-bottom: 20px;
                }
                
                .input-group i {
                    position: absolute;
                    left: 15px;
                    top: 50%;
                    transform: translateY(-50%);
                    color: #667eea;
                }
                
                .input-group input {
                    width: 100%;
                    padding: 15px 15px 15px 45px;
                    background: rgba(255, 255, 255, 0.1);
                    border: 1px solid rgba(255, 255, 255, 0.2);
                    border-radius: 12px;
                    color: white;
                    font-size: 16px;
                    transition: all 0.3s ease;
                }
                
                .input-group input:focus {
                    outline: none;
                    border-color: #667eea;
                    background: rgba(255, 255, 255, 0.15);
                }
                
                .login-btn {
                    width: 100%;
                    padding: 15px;
                    background: linear-gradient(135deg, #667eea, #764ba2);
                    border: none;
                    border-radius: 12px;
                    color: white;
                    font-size: 16px;
                    font-weight: 600;
                    cursor: pointer;
                    transition: all 0.3s ease;
                }
                
                .login-btn:hover {
                    transform: translateY(-2px);
                    box-shadow: 0 10px 25px -5px rgba(102, 126, 234, 0.4);
                }
                
                .error {
                    background: rgba(220, 38, 38, 0.2);
                    border: 1px solid rgba(220, 38, 38, 0.5);
                    border-radius: 12px;
                    padding: 12px;
                    color: #fca5a5;
                    font-size: 14px;
                    margin-top: 20px;
                }
            </style>
        </head>
        <body>
            <div class="login-container">
                <div class="login-icon"><i class="fas fa-shield-alt"></i></div>
                <h2>Administrador Web Player</h2>
                <p class="subtitle">Propiedad Grupo Full IPTV</p>
                <form method="POST">
                    <div class="input-group">
                        <i class="fas fa-lock"></i>
                        <input type="password" name="admin_password" placeholder="Contraseña de administrador" required>
                    </div>
                    <button type="submit" class="login-btn">
                        <i class="fas fa-sign-in-alt" style="margin-right: 8px;"></i>
                        Acceder al Panel
                    </button>
                </form>
                <?php if (isset($admin_error)): ?>
                <div class="error">
                    <i class="fas fa-exclamation-triangle" style="margin-right: 8px;"></i>
                    <?= $admin_error ?>
                </div>
                <?php endif; ?>
            </div>
        </body>
        </html>
        <?php
        exit;
    }
}

$data_dir = 'data';
if (!is_dir($data_dir)) {
    mkdir($data_dir, 0755, true);
}

if (!file_exists('images.json')) {
    file_put_contents('images.json', json_encode(['images' => []], JSON_PRETTY_PRINT));
}

$last_check_file = $data_dir . '/last_auto_check.txt';

function autoCleanExpiredUsers($users_db, $servers, $last_check_file) {
    $now = time();
    $last_check = 0;
    
    if (file_exists($last_check_file)) {
        $last_check = intval(file_get_contents($last_check_file));
    }
    
    if (($now - $last_check) >= 86400) {
        try {
            $expired_count = 0;
            $stmt = $users_db->query('SELECT * FROM users');
            $all_users = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            foreach ($all_users as $user) {
                $server = null;
                foreach ($servers as $s) {
                    if ($s['id'] == $user['server_id']) {
                        $server = $s;
                        break;
                    }
                }
                
                if ($server) {
                    $verification = verifyUserWithXtreme($server['url'], $user['username'], $user['password']);
                    
                    if (!$verification['success'] || 
                        ($verification['expiry_date'] && new DateTime($verification['expiry_date']) < new DateTime())) {
                        
                        $delete_stmt = $users_db->prepare('DELETE FROM users WHERE id = ?');
                        $delete_stmt->execute([$user['id']]);
                        $expired_count++;
                    } else {
                        $update_stmt = $users_db->prepare('UPDATE users SET expiry_date = ?, status = ? WHERE id = ?');
                        $update_stmt->execute([
                            $verification['expiry_date'],
                            $verification['status'],
                            $user['id']
                        ]);
                    }
                }
            }
            
            file_put_contents($last_check_file, $now);
            
            $log_message = date('Y-m-d H:i:s') . " - Limpieza automática completada. $expired_count usuarios eliminados.\n";
            file_put_contents($data_dir . '/auto_cleanup.log', $log_message, FILE_APPEND);
            
            return $expired_count;
            
        } catch (Exception $e) {
            $error_log = date('Y-m-d H:i:s') . " - Error en limpieza automática: " . $e->getMessage() . "\n";
            file_put_contents($data_dir . '/auto_cleanup_errors.log', $error_log, FILE_APPEND);
            return false;
        }
    }
    
    return null;
}

$users_db_file = $data_dir . '/users.db';
try {
    $users_db = new PDO('sqlite:' . $users_db_file);
    $users_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $users_db->exec("CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        code VARCHAR(6) UNIQUE NOT NULL,
        username TEXT NOT NULL,
        password TEXT NOT NULL,
        server_id INTEGER NOT NULL,
        server_name TEXT NOT NULL,
        expiry_date TEXT,
        status TEXT DEFAULT 'active',
        created DATETIME DEFAULT CURRENT_TIMESTAMP,
        active INTEGER DEFAULT 1
    )");
    
} catch (Exception $e) {
    die("Error creando base de datos: " . $e->getMessage());
}

$servers_file = $data_dir . '/servers.json';
$servers = [];
if (file_exists($servers_file)) {
    $content = file_get_contents($servers_file);
    $decoded = json_decode($content, true);
    if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
        $servers = $decoded;
    }
}
if (empty($servers) || !is_array($servers)) {
    $servers = [];
    file_put_contents($servers_file, json_encode([], JSON_PRETTY_PRINT));
}

$auto_cleanup_result = autoCleanExpiredUsers($users_db, $servers, $last_check_file);

$images_content = file_get_contents('images.json');
$images_data = json_decode($images_content, true);

if (json_last_error() !== JSON_ERROR_NONE || !isset($images_data['images']) || !is_array($images_data['images'])) {
    $images = [];
    file_put_contents('images.json', json_encode(['images' => []], JSON_PRETTY_PRINT));
} else {
    $images = $images_data['images'];
}

$users = [];
try {
    $stmt = $users_db->query('SELECT * FROM users ORDER BY created DESC');
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $users = [];
}

$expiring_users = [];
$now = new DateTime();
foreach ($users as $user) {
    if ($user['expiry_date']) {
        try {
            $expiry = new DateTime($user['expiry_date']);
            $diff = $now->diff($expiry);
            
            if ($diff->days <= 3 && $expiry > $now) {
                $expiring_users[] = $user;
            }
        } catch (Exception $e) {
            // Ignorar errores de fecha
        }
    }
}

function verifyUserWithXtreme($server_url, $username, $password) {
    $api_url = rtrim($server_url, '/') . '/player_api.php?' . http_build_query([
        'username' => $username,
        'password' => $password,
        'action' => 'get_account_info'
    ]);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_USERAGENT, 'XtremePlayer/1.0');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($response && $http_code == 200) {
        $data = json_decode($response, true);
        
        if (isset($data['user_info']) && $data['user_info']['auth'] == 1) {
            $expiry_timestamp = $data['user_info']['exp_date'] ?? null;
            $status = $data['user_info']['status'] ?? 'active';
            $is_trial = $data['user_info']['is_trial'] ?? '0';
            $max_connections = $data['user_info']['max_connections'] ?? '1';
            
            $expiry_date = null;
            if ($expiry_timestamp && $expiry_timestamp != '0') {
                $expiry_date = date('Y-m-d H:i:s', $expiry_timestamp);
            }
            
            return [
                'success' => true,
                'expiry_date' => $expiry_date,
                'status' => $status,
                'is_trial' => $is_trial,
                'max_connections' => $max_connections,
                'raw_data' => $data['user_info']
            ];
        } else {
            return [
                'success' => false,
                'message' => 'Usuario inválido o no autorizado',
                'raw_data' => $data
            ];
        }
    } else {
        return [
            'success' => false,
            'message' => 'Error de conexión con el servidor (HTTP: ' . $http_code . ')',
            'raw_data' => null
        ];
    }
}

function testServerConnection($server_url, $timeout = 5) {
    $test_url = rtrim($server_url, '/') . '/player_api.php';
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $test_url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_CONNECTTIMEOUT => 3,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_NOBODY => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS => 3,
        CURLOPT_USERAGENT => 'IPTV-Panel/1.0',
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    ]);
    
    $result = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    $curl_errno = curl_errno($ch);
    curl_close($ch);
    
    if ($curl_error && $curl_errno) {
        return [
            'success' => false,
            'status' => 'offline',
            'message' => 'Error de conexión',
            'technical_error' => $curl_error
        ];
    }
    
    if ($http_code >= 200 && $http_code < 500) {
        $status = 'online';
        $message = 'Servidor respondiendo correctamente';
    } elseif ($http_code >= 500) {
        $status = 'limited';
        $message = 'Servidor con problemas pero alcanzable';
    } else {
        $status = 'offline';
        $message = 'Respuesta inesperada';
    }
    
    return [
        'success' => true,
        'status' => $status,
        'http_code' => $http_code,
        'message' => $message
    ];
}

function generateUniqueCode($db) {
    $max_attempts = 1000;
    $attempts = 0;
    
    do {
        $code = str_pad(mt_rand(0, 999999), 6, '0', STR_PAD_LEFT);
        
        $stmt = $db->prepare('SELECT COUNT(*) FROM users WHERE code = ?');
        $stmt->execute([$code]);
        $exists = $stmt->fetchColumn() > 0;
        
        $attempts++;
        if ($attempts >= $max_attempts) {
            throw new Exception('No se pudo generar un código único después de ' . $max_attempts . ' intentos');
        }
        
    } while ($exists);
    
    return $code;
}

function saveServers($servers, $file) {
    $result = file_put_contents($file, json_encode($servers, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
    return $result !== false;
}

function saveImages($images) {
    $data = ['images' => $images];
    $result = file_put_contents('images.json', json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
    return $result !== false;
}

function isValidUrl($url) {
    return filter_var($url, FILTER_VALIDATE_URL) !== false;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['action'])) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Acción no especificada']);
        exit;
    }
    
    $action = $_POST['action'];
    
    header('Content-Type: application/json');
    header('Cache-Control: no-cache, must-revalidate');
    
    try {
        switch ($action) {
            case 'add_user':
                $username = trim($_POST['username'] ?? '');
                $password = trim($_POST['password'] ?? '');
                $server_id = intval($_POST['server_id'] ?? 0);
                
                if (!$username || !$password || !$server_id) {
                    echo json_encode(['success' => false, 'message' => 'Todos los campos son obligatorios']);
                    exit;
                }
                
                $stmt = $users_db->prepare('SELECT COUNT(*) FROM users WHERE username = ? AND password = ? AND server_id = ?');
                $stmt->execute([$username, $password, $server_id]);
                if ($stmt->fetchColumn() > 0) {
                    echo json_encode(['success' => false, 'message' => 'Ya existe un usuario con estas credenciales en este servidor']);
                    exit;
                }
                
                $server = null;
                foreach ($servers as $s) {
                    if ($s['id'] == $server_id) {
                        $server = $s;
                        break;
                    }
                }
                
                if (!$server) {
                    echo json_encode(['success' => false, 'message' => 'Servidor no encontrado']);
                    exit;
                }
                
                $verification = verifyUserWithXtreme($server['url'], $username, $password);
                
                if (!$verification['success']) {
                    echo json_encode([
                        'success' => false, 
                        'message' => 'Error verificando usuario: ' . $verification['message']
                    ]);
                    exit;
                }
                
                $code = generateUniqueCode($users_db);
                
                $stmt = $users_db->prepare('INSERT INTO users (code, username, password, server_id, server_name, expiry_date, status) VALUES (?, ?, ?, ?, ?, ?, ?)');
                if ($stmt->execute([
                    $code, 
                    $username, 
                    $password, 
                    $server_id, 
                    $server['name'],
                    $verification['expiry_date'],
                    $verification['status']
                ])) {
                    $new_user = [
                        'id' => $users_db->lastInsertId(),
                        'code' => $code,
                        'username' => $username,
                        'password' => $password,
                        'server_id' => $server_id,
                        'server_name' => $server['name'],
                        'expiry_date' => $verification['expiry_date'],
                        'status' => $verification['status'],
                        'created' => date('Y-m-d H:i:s'),
                        'active' => 1
                    ];
                    echo json_encode([
                        'success' => true, 
                        'message' => 'Usuario verificado y creado exitosamente', 
                        'user' => $new_user
                    ]);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Error creando usuario en la base de datos']);
                }
                break;
                
            case 'delete_user':
                $id = intval($_POST['id'] ?? 0);
                if ($id <= 0) {
                    echo json_encode(['success' => false, 'message' => 'ID de usuario inválido']);
                    exit;
                }
                
                $stmt = $users_db->prepare('DELETE FROM users WHERE id = ?');
                if ($stmt->execute([$id])) {
                    echo json_encode(['success' => true, 'message' => 'Usuario eliminado exitosamente']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Error eliminando usuario']);
                }
                break;
                
            case 'toggle_user':
                $id = intval($_POST['id'] ?? 0);
                if ($id <= 0) {
                    echo json_encode(['success' => false, 'message' => 'ID de usuario inválido']);
                    exit;
                }
                
                $stmt = $users_db->prepare('UPDATE users SET active = NOT active WHERE id = ?');
                if ($stmt->execute([$id])) {
                    echo json_encode(['success' => true, 'message' => 'Estado actualizado exitosamente']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Error actualizando estado']);
                }
                break;

            case 'check_expired':
                $expired_count = 0;
                $stmt = $users_db->query('SELECT * FROM users');
                $all_users = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                foreach ($all_users as $user) {
                    $server = null;
                    foreach ($servers as $s) {
                        if ($s['id'] == $user['server_id']) {
                            $server = $s;
                            break;
                        }
                    }
                    
                    if ($server) {
                        $verification = verifyUserWithXtreme($server['url'], $user['username'], $user['password']);
                        
                        if (!$verification['success'] || 
                            ($verification['expiry_date'] && new DateTime($verification['expiry_date']) < new DateTime())) {
                            
                            $delete_stmt = $users_db->prepare('DELETE FROM users WHERE id = ?');
                            $delete_stmt->execute([$user['id']]);
                            $expired_count++;
                        } else {
                            $update_stmt = $users_db->prepare('UPDATE users SET expiry_date = ?, status = ? WHERE id = ?');
                            $update_stmt->execute([
                                $verification['expiry_date'],
                                $verification['status'],
                                $user['id']
                            ]);
                        }
                    }
                }
                
                echo json_encode([
                    'success' => true, 
                    'message' => "Verificación completada. $expired_count usuarios expirados eliminados.",
                    'expired_count' => $expired_count
                ]);
                break;
                
            case 'save_images':
                if (!isset($_POST['images']) || !is_array($_POST['images'])) {
                    echo json_encode(['success' => false, 'message' => 'Datos de imagen inválidos']);
                    exit;
                }
                
                if (saveImages($_POST['images'])) {
                    echo json_encode(['success' => true, 'message' => 'Imágenes guardadas exitosamente']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Error guardando imágenes']);
                }
                break;
                
            case 'add_image':
                $name = trim($_POST['name'] ?? '');
                $url = trim($_POST['url'] ?? '');
                
                if (!$name || !$url) {
                    echo json_encode(['success' => false, 'message' => 'Nombre y URL son obligatorios']);
                    exit;
                }
                
                if (!filter_var($url, FILTER_VALIDATE_URL)) {
                    echo json_encode(['success' => false, 'message' => 'URL inválida']);
                    exit;
                }
                
                $current_images = json_decode(file_get_contents('images.json'), true)['images'] ?? [];
                $current_images[] = ['name' => $name, 'url' => $url];
                
                if (saveImages($current_images)) {
                    echo json_encode(['success' => true, 'message' => 'Imagen agregada exitosamente']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Error agregando imagen']);
                }
                break;
                
            case 'delete_image':
                $index = intval($_POST['index'] ?? -1);
                
                if ($index < 0) {
                    echo json_encode(['success' => false, 'message' => 'Índice inválido']);
                    exit;
                }
                
                $current_images = json_decode(file_get_contents('images.json'), true)['images'] ?? [];
                
                if (!isset($current_images[$index])) {
                    echo json_encode(['success' => false, 'message' => 'Imagen no encontrada']);
                    exit;
                }
                
                array_splice($current_images, $index, 1);
                
                if (saveImages($current_images)) {
                    echo json_encode(['success' => true, 'message' => 'Imagen eliminada exitosamente']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Error eliminando imagen']);
                }
                break;
                
            case 'edit_image':
                $index = intval($_POST['index'] ?? -1);
                $name = trim($_POST['name'] ?? '');
                $url = trim($_POST['url'] ?? '');
                
                if ($index < 0 || !$name || !$url) {
                    echo json_encode(['success' => false, 'message' => 'Datos inválidos']);
                    exit;
                }
                
                if (!filter_var($url, FILTER_VALIDATE_URL)) {
                    echo json_encode(['success' => false, 'message' => 'URL inválida']);
                    exit;
                }
                
                $current_images = json_decode(file_get_contents('images.json'), true)['images'] ?? [];
                
                if (!isset($current_images[$index])) {
                    echo json_encode(['success' => false, 'message' => 'Imagen no encontrada']);
                    exit;
                }
                
                $current_images[$index] = ['name' => $name, 'url' => $url];
                
                if (saveImages($current_images)) {
                    echo json_encode(['success' => true, 'message' => 'Imagen actualizada exitosamente']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Error actualizando imagen']);
                }
                break;

            case 'add_server':
                $name = trim($_POST['name'] ?? '');
                $dns = trim($_POST['dns'] ?? '');
                
                if (!$name || !$dns) {
                    echo json_encode(['success' => false, 'message' => 'Nombre y DNS son obligatorios']);
                    exit;
                }
                
                if (!isValidUrl($dns)) {
                    echo json_encode(['success' => false, 'message' => 'URL inválida']);
                    exit;
                }
                
                foreach ($servers as $server) {
                    if ($server['url'] === rtrim($dns, '/')) {
                        echo json_encode(['success' => false, 'message' => 'Ya existe un servidor con esta URL']);
                        exit;
                    }
                }
                
                $new_id = count($servers) > 0 ? max(array_column($servers, 'id')) + 1 : 1;
                $new_server = [ 
                    'id' => $new_id, 
                    'name' => $name, 
                    'url' => rtrim($dns, '/') 
                ];
                
                $servers[] = $new_server;
                
                if (saveServers($servers, $servers_file)) {
                    echo json_encode([
                        'success' => true, 
                        'message' => 'Servidor agregado exitosamente', 
                        'server' => $new_server
                    ]);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Error guardando servidor']);
                }
                break;
                
            case 'delete_server':
                $id = intval($_POST['id'] ?? 0);
                
                if ($id <= 0) {
                    echo json_encode(['success' => false, 'message' => 'ID de servidor inválido']);
                    exit;
                }
                
                $stmt = $users_db->prepare('SELECT COUNT(*) FROM users WHERE server_id = ?');
                $stmt->execute([$id]);
                $user_count = $stmt->fetchColumn();
                
                if ($user_count > 0) {
                    echo json_encode([
                        'success' => false, 
                        'message' => "No se puede eliminar: hay $user_count usuario(s) usando este servidor"
                    ]);
                    exit;
                }
                
                $original_count = count($servers);
                $servers = array_filter($servers, function($s) use ($id) { 
                    return $s['id'] != $id; 
                });
                $servers = array_values($servers);
                
                if (count($servers) < $original_count && saveServers($servers, $servers_file)) {
                    echo json_encode(['success' => true, 'message' => 'Servidor eliminado exitosamente']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Error eliminando servidor']);
                }
                break;
                
            case 'test_server':
                $id = intval($_POST['id'] ?? 0);
                
                if ($id <= 0) {
                    echo json_encode(['success' => false, 'message' => 'ID de servidor inválido']);
                    exit;
                }
                
                $server = null;
                foreach ($servers as $s) {
                    if ($s['id'] == $id) { 
                        $server = $s; 
                        break; 
                    }
                }
                
                if (!$server) {
                    echo json_encode(['success' => false, 'message' => 'Servidor no encontrado']);
                    exit;
                }
                
                $test_result = testServerConnection($server['url']);
                
                echo json_encode([
                    'success' => $test_result['success'],
                    'status' => $test_result['status'],
                    'http_code' => $test_result['http_code'] ?? 0,
                    'message' => $test_result['message'],
                    'server_name' => $server['name']
                ]);
                break;
                
            default:
                echo json_encode(['success' => false, 'message' => 'Acción inválida: ' . $action]);
                break;
        }
        
    } catch (Exception $e) {
        echo json_encode([
            'success' => false, 
            'message' => 'Error del servidor: ' . $e->getMessage()
        ]);
    }
    
    exit;
}

if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Admin Panel - Gestión DNS</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #0a0e27;
            color: white;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea, #764ba2);
            padding: 20px 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
        }
        
        .header h1 {
            font-size: 24px;
            margin: 0;
        }
        
        .stats {
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
            align-items: center;
        }
        
        .stats span {
            background: rgba(255, 255, 255, 0.2);
            padding: 8px 15px;
            border-radius: 20px;
            font-size: 14px;
        }
        
        .logout {
            background: rgba(220, 38, 38, 0.8);
            color: white;
            padding: 8px 15px;
            border-radius: 20px;
            text-decoration: none;
            transition: all 0.3s ease;
        }
        
        .logout:hover {
            background: #dc2626;
            color: white;
            text-decoration: none;
        }
        
        .container {
            max-width: 1400px;
            margin: 30px auto;
            padding: 0 20px;
        }
        
        .tabs-container {
            margin-bottom: 30px;
        }
        
        .tabs {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            border-bottom: 2px solid rgba(255, 255, 255, 0.1);
            padding-bottom: 10px;
        }
        
        .tab-btn {
            background: none;
            border: none;
            padding: 12px 24px;
            color: #a0aec0;
            cursor: pointer;
            font-size: 16px;
            transition: all 0.3s ease;
            border-radius: 8px;
        }
        
        .tab-btn:hover {
            color: white;
            background: rgba(255, 255, 255, 0.1);
        }
        
        .tab-btn.active {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
        }
        
        .tab-content {
            display: none;
            animation: fadeIn 0.3s ease;
        }
        
        .tab-content.active {
            display: block;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .add-form {
            background: rgba(255, 255, 255, 0.05);
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 30px;
        }
        
        .add-form h3 {
            margin-bottom: 20px;
            font-size: 20px;
        }
        
        .form-row {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
            align-items: flex-end;
        }
        
        .form-group {
            flex: 1;
            min-width: 200px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #a0aec0;
            font-size: 14px;
        }
        
        .form-group input, .form-group select {
            width: 100%;
            padding: 12px;
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 8px;
            color: white;
            font-size: 14px;
        }
        
        .form-group input:focus, .form-group select:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        .btn-danger {
            background: #dc2626;
            color: white;
        }
        
        .btn-danger:hover {
            background: #b91c1c;
        }
        
        .btn-warning {
            background: #f59e0b;
            color: white;
        }
        
        .btn-warning:hover {
            background: #d97706;
        }
        
        .btn-info {
            background: #3b82f6;
            color: white;
        }
        
        .btn-info:hover {
            background: #2563eb;
        }
        
        .servers-table, .users-table {
            background: rgba(255, 255, 255, 0.05);
            border-radius: 15px;
            overflow-x: auto;
        }
        
        .table-header {
            display: grid;
            gap: 15px;
            padding: 15px;
            background: rgba(255, 255, 255, 0.1);
            font-weight: 600;
            font-size: 14px;
        }
        
        .table-header.servers {
            grid-template-columns: 80px 1fr 1fr 150px;
        }
        
        .table-header.users {
            grid-template-columns: 100px 1fr 1fr 1fr 120px 100px 150px;
        }
        
        .server-row, .user-row {
            display: grid;
            gap: 15px;
            padding: 15px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            align-items: center;
        }
        
        .server-row {
            grid-template-columns: 80px 1fr 1fr 150px;
        }
        
        .user-row {
            grid-template-columns: 100px 1fr 1fr 1fr 120px 100px 150px;
        }
        
        .status {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: #666;
        }
        
        .status.online {
            background: #46D369;
            box-shadow: 0 0 5px #46D369;
        }
        
        .status.offline {
            background: #E50914;
        }
        
        .status.limited {
            background: #ffc107;
        }
        
        .status.testing {
            background: #f59e0b;
            animation: pulse 1s infinite;
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }
        
        .status-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 600;
        }
        
        .status-badge.active {
            background: #46D369;
            color: white;
        }
        
        .status-badge.inactive {
            background: #E50914;
            color: white;
        }
        
        .code-display {
            font-family: monospace;
            font-size: 18px;
            font-weight: bold;
            color: #667eea;
        }
        
        .actions {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #a0aec0;
        }
        
        .empty-state i {
            font-size: 64px;
            margin-bottom: 20px;
        }
        
        .message {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 20px;
            border-radius: 10px;
            z-index: 1000;
            animation: slideIn 0.3s ease;
            max-width: 400px;
        }
        
        .message.success {
            background: #10b981;
            color: white;
        }
        
        .message.error {
            background: #ef4444;
            color: white;
        }
        
        @keyframes slideIn {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }
        
        .image-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }
        
        .image-card {
            background: rgba(255, 255, 255, 0.05);
            border-radius: 12px;
            overflow: hidden;
            transition: transform 0.3s ease;
        }
        
        .image-card:hover {
            transform: translateY(-5px);
        }
        
        .image-preview {
            width: 100%;
            height: 150px;
            object-fit: cover;
        }
        
        .image-info {
            padding: 15px;
        }
        
        .image-info h5 {
            margin-bottom: 8px;
            font-size: 14px;
        }
        
        .image-actions {
            margin-top: 10px;
            display: flex;
            gap: 8px;
        }
        
        .modal-content {
            background: #1a1f3a;
            color: white;
        }
        
        .modal-header {
            border-bottom-color: rgba(255, 255, 255, 0.1);
        }
        
        .modal-footer {
            border-top-color: rgba(255, 255, 255, 0.1);
        }
        
        .close {
            color: white;
        }
        
        @media (max-width: 768px) {
            .table-header, .server-row, .user-row {
                grid-template-columns: 1fr;
                gap: 8px;
            }
            
            .table-header {
                display: none;
            }
            
            .server-row, .user-row {
                padding: 15px;
            }
            
            .stats {
                margin-top: 10px;
            }
            
            .header h1 {
                font-size: 18px;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <h1><i class="fas fa-server"></i> Panel de Administración DNS</h1>
        <div class="stats">
            <span><i class="fas fa-database"></i> Servidores: <?= count($servers) ?></span>
            <span><i class="fas fa-users"></i> Usuarios: <?= count($users) ?></span>
            <span><i class="fas fa-exclamation-triangle" style="color: #ffc107;"></i> Por vencer: <?= count($expiring_users) ?></span>
            <?php if ($auto_cleanup_result !== null && $auto_cleanup_result !== false): ?>
                <span><i class="fas fa-broom" style="color: #46D369;"></i> Limpieza: <?= $auto_cleanup_result ?> eliminados</span>
            <?php endif; ?>
            <span><i class="fas fa-circle" style="color: #46D369;"></i> Online: <span id="onlineCount">-</span></span>
            <span><i class="fas fa-circle" style="color: #E50914;"></i> Offline: <span id="offlineCount">-</span></span>
            <a href="?logout=1" class="logout">
                <i class="fas fa-sign-out-alt"></i> Cerrar sesión
            </a>
        </div>
    </div>
    <div class="container">
        <div id="message"></div>
        <div class="tabs-container">
            <div class="tabs">
                <button class="tab-btn active" onclick="showTab('servers')"><i class="fas fa-server"></i> Servidores DNS</button>
                <button class="tab-btn" onclick="showTab('users')"><i class="fas fa-users"></i> Usuarios</button>
                <button class="tab-btn" onclick="showTab('expiring')"><i class="fas fa-exclamation-triangle"></i> Por Vencer (<?= count($expiring_users) ?>)</button>
            </div>
        </div>
        
        <!-- Tab Servidores -->
        <div id="tab-servers" class="tab-content active">
            <div class="add-form">
                <h3><i class="fas fa-plus-circle"></i> Agregar Nuevo Servidor DNS</h3>
                <form id="addServerForm">
                    <div class="form-row">
                        <div class="form-group">
                            <label><i class="fas fa-tag"></i> Nombre</label>
                            <input type="text" id="serverName" placeholder="Ej: Servidor Premium" required>
                        </div>
                        <div class="form-group">
                            <label><i class="fas fa-link"></i> URL del Servidor</label>
                            <input type="text" id="serverDns" placeholder="http://tudominio.com:8080" required>
                        </div>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-plus"></i> Agregar Servidor
                        </button>
                    </div>
                </form>
            </div>
            <div class="servers-table">
                <div class="table-header servers">
                    <span>Estado</span>
                    <span>Nombre</span>
                    <span>URL</span>
                    <span>Acciones</span>
                </div>
                <div id="serversList">
                    <?php if (empty($servers)): ?>
                    <div class="empty-state">
                        <i class="fas fa-server"></i>
                        <h3>No hay servidores configurados</h3>
                        <p>Añade tu primer servidor usando el formulario de arriba</p>
                    </div>
                    <?php else: ?>
                        <?php foreach ($servers as $server): ?>
                        <div class="server-row" data-id="<?= $server['id'] ?>">
                            <div class="status" id="status-<?= $server['id'] ?>"></div>
                            <div><?= htmlspecialchars($server['name']) ?></div>
                            <div class="server-url"><?= htmlspecialchars($server['url']) ?></div>
                            <div class="actions">
                                <button class="btn btn-info" onclick="testServer(<?= $server['id'] ?>)">
                                    <i class="fas fa-wifi"></i> Probar
                                </button>
                                <button class="btn btn-danger" onclick="deleteServer(<?= $server['id'] ?>)">
                                    <i class="fas fa-trash"></i> Eliminar
                                </button>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Tab Usuarios -->
        <div id="tab-users" class="tab-content">
            <div class="add-form">
                <h3><i class="fas fa-user-plus"></i> Agregar Nuevo Usuario</h3>
                <form id="addUserForm">
                    <div class="form-row">
                        <div class="form-group">
                            <label><i class="fas fa-user"></i> Usuario</label>
                            <input type="text" id="userName" placeholder="nombre_usuario" required>
                        </div>
                        <div class="form-group">
                            <label><i class="fas fa-key"></i> Contraseña</label>
                            <input type="text" id="userPassword" placeholder="contraseña" required>
                        </div>
                        <div class="form-group">
                            <label><i class="fas fa-server"></i> Servidor DNS</label>
                            <select id="userServer" required>
                                <option value="">Seleccionar Servidor...</option>
                                <?php foreach ($servers as $server): ?>
                                <option value="<?= $server['id'] ?>"><?= htmlspecialchars($server['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-plus"></i> Crear Usuario
                        </button>
                    </div>
                </form>
            </div>
            
            <div class="servers-table">
                <div class="table-header users">
                    <span>Código</span>
                    <span>Usuario</span>
                    <span>Contraseña</span>
                    <span>Servidor</span>
                    <span>Vencimiento</span>
                    <span>Estado</span>
                    <span>Acciones</span>
                </div>
                <div id="usersList">
                    <?php if (empty($users)): ?>
                    <div class="empty-state">
                        <i class="fas fa-users"></i>
                        <h3>No hay usuarios configurados</h3>
                        <p>Añade tu primer usuario utilizando el formulario de arriba</p>
                    </div>
                    <?php else: ?>
                        <?php foreach ($users as $user): ?>
                        <div class="user-row" data-id="<?= $user['id'] ?>">
                            <div class="code-display"><?= $user['code'] ?></div>
                            <div><?= htmlspecialchars($user['username']) ?></div>
                            <div><?= htmlspecialchars($user['password']) ?></div>
                            <div><?= htmlspecialchars($user['server_name']) ?></div>
                            <div>
                                <?php if ($user['expiry_date']): ?>
                                    <?php 
                                    $expiry = new DateTime($user['expiry_date']);
                                    $now = new DateTime();
                                    $is_expired = $expiry < $now;
                                    $days_left = $now->diff($expiry)->days;
                                    ?>
                                    <span style="color: <?= $is_expired ? '#E50914' : ($days_left <= 7 ? '#ffc107' : '#46D369') ?>; font-size: 12px; font-weight: bold;">
                                        <?= $expiry->format('d/m/Y') ?><br>
                                        <small>(<?= $is_expired ? 'Expirado' : $days_left . ' días' ?>)</small>
                                    </span>
                                <?php else: ?>
                                    <span style="color: #666; font-size: 12px;">Sin datos</span>
                                <?php endif; ?>
                            </div>
                            <div>
                                <span class="status-badge <?= $user['active'] ? 'active' : 'inactive' ?>">
                                    <?= $user['active'] ? 'Activo' : 'Inactivo' ?>
                                </span>
                            </div>
                            <div class="actions">
                                <button class="btn btn-<?= $user['active'] ? 'warning' : 'success' ?>" onclick="toggleUser(<?= $user['id'] ?>)">
                                    <i class="fas fa-toggle-<?= $user['active'] ? 'off' : 'on' ?>"></i>
                                    <?= $user['active'] ? 'Desactivar' : 'Activar' ?>
                                </button>
                                <button class="btn btn-danger" onclick="deleteUser(<?= $user['id'] ?>)">
                                    <i class="fas fa-trash"></i> Eliminar
                                </button>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <!-- Tab Por Vencer -->
        <div id="tab-expiring" class="tab-content">
            <div class="add-form">
                <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px; margin-bottom: 20px;">
                    <h3><i class="fas fa-exclamation-triangle"></i> Usuarios por vencer (3 días o menos)</h3>
                    <button class="btn btn-warning" onclick="checkExpiredUsers()">
                        <i class="fas fa-sync-alt"></i> Verificar Manualmente
                    </button>
                </div>
                <div style="background: rgba(0,0,0,0.3); padding: 15px; border-radius: 8px; margin-bottom: 20px;">
                    <p style="color: #a0aec0; margin-bottom: 0;">
                        <i class="fas fa-info-circle"></i> Los usuarios que se muestran aquí caducan en los próximos 3 días. 
                        El sistema los verificará y los eliminará automáticamente si están vencidos.
                    </p>
                </div>
            </div>
            
            <div class="servers-table">
                <div class="table-header users">
                    <span>Código</span>
                    <span>Usuario</span>
                    <span>Contraseña</span>
                    <span>Servidor</span>
                    <span>Vencimiento</span>
                    <span>Estado</span>
                    <span>Acciones</span>
                </div>
                <div id="expiringUsersList">
                    <?php if (empty($expiring_users)): ?>
                    <div class="empty-state">
                        <i class="fas fa-check-circle" style="color: #46D369;"></i>
                        <h3>¡Excelente!</h3>
                        <p>No hay usuarios que expiren pronto</p>
                    </div>
                    <?php else: ?>
                        <?php foreach ($expiring_users as $user): ?>
                        <div class="user-row" data-id="<?= $user['id'] ?>">
                            <div class="code-display"><?= $user['code'] ?></div>
                            <div><?= htmlspecialchars($user['username']) ?></div>
                            <div><?= htmlspecialchars($user['password']) ?></div>
                            <div><?= htmlspecialchars($user['server_name']) ?></div>
                            <div>
                                <?php if ($user['expiry_date']): ?>
                                    <?php 
                                    $expiry = new DateTime($user['expiry_date']);
                                    $now = new DateTime();
                                    $diff = $now->diff($expiry);
                                    $days_left = $diff->days;
                                    ?>
                                    <span style="color: #ffc107; font-size: 12px; font-weight: bold;">
                                        <?= $expiry->format('d/m/Y') ?><br>
                                        <small>(<?= $days_left ?> días restantes)</small>
                                    </span>
                                <?php else: ?>
                                    <span style="color: #E50914; font-size: 12px;">Sin datos</span>
                                <?php endif; ?>
                            </div>
                            <div>
                                <span class="status-badge <?= $user['active'] ? 'active' : 'inactive' ?>">
                                    <?= $user['active'] ? 'Activo' : 'Inactivo' ?>
                                </span>
                            </div>
                            <div class="actions">
                                <button class="btn btn-<?= $user['active'] ? 'warning' : 'success' ?>" onclick="toggleUser(<?= $user['id'] ?>)">
                                    <i class="fas fa-toggle-<?= $user['active'] ? 'off' : 'on' ?>"></i>
                                    <?= $user['active'] ? 'Desactivar' : 'Activar' ?>
                                </button>
                                <button class="btn btn-danger" onclick="deleteUser(<?= $user['id'] ?>)">
                                    <i class="fas fa-trash"></i> Eliminar
                                </button>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

    <script>
        let processingRequest = false;
        
        function showMessage(text, type) {
            const messageEl = document.getElementById('message');
            const icon = type === 'success' ? 'fas fa-check-circle' : 'fas fa-exclamation-triangle';
            
            messageEl.innerHTML = `
                <div class="message ${type}">
                    <i class="${icon}"></i>
                    ${text}
                </div>
            `;
            
            setTimeout(() => {
                const msg = messageEl.querySelector('.message');
                if (msg) {
                    msg.style.opacity = '0';
                    msg.style.transition = 'opacity 0.3s';
                    setTimeout(() => {
                        messageEl.innerHTML = '';
                    }, 300);
                }
            }, 5000);
        }

        function makeRequest(data, successCallback, errorCallback) {
            if (processingRequest) {
                console.log('Solicitud en proceso, ignorando...');
                return;
            }
            
            processingRequest = true;
            
            $.ajax({
                type: 'POST',
                url: window.location.href,
                data: data,
                dataType: 'json',
                timeout: 15000,
                success: function(response) {
                    processingRequest = false;
                    if (response.success) {
                        if (successCallback) successCallback(response);
                    } else {
                        showMessage(response.message || 'Error desconocido', 'error');
                        if (errorCallback) errorCallback(response);
                    }
                },
                error: function(xhr, status, error) {
                    processingRequest = false;
                    let errorMsg = 'Error de conexión';
                    if (status === 'timeout') {
                        errorMsg = 'Tiempo de espera agotado';
                    } else if (xhr.responseJSON && xhr.responseJSON.message) {
                        errorMsg = xhr.responseJSON.message;
                    }
                    showMessage(errorMsg, 'error');
                    if (errorCallback) errorCallback({ message: errorMsg });
                }
            });
        }

        function testServer(id) {
            const statusEl = $('#status-' + id);
            const testBtn = $(`.server-row[data-id="${id}"] button:contains("Probar")`);
            
            statusEl.removeClass('online offline limited').addClass('testing');
            testBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Probando...');
            
            makeRequest({
                action: 'test_server',
                id: id
            }, 
            function(response) {
                statusEl.removeClass('testing').addClass(response.status);
                showMessage(`${response.server_name}: ${response.message}`, response.success ? 'success' : 'error');
                updateOnlineCount();
                testBtn.prop('disabled', false).html('<i class="fas fa-wifi"></i> Probar');
            },
            function() {
                statusEl.removeClass('testing').addClass('offline');
                updateOnlineCount();
                testBtn.prop('disabled', false).html('<i class="fas fa-wifi"></i> Probar');
            });
        }

        function autoTestServers() {
            $('.server-row').each(function(index) {
                const id = $(this).data('id');
                if (id) {
                    setTimeout(() => {
                        testServer(id);
                    }, index * 1000);
                }
            });
        }

        function updateOnlineCount() {
            let online = 0;
            let offline = 0;
            
            $('.status').each(function() {
                if ($(this).hasClass('online')) {
                    online++;
                } else if ($(this).hasClass('offline')) {
                    offline++;
                }
            });
            
            $('#onlineCount').text(online);
            $('#offlineCount').text(offline);
        }

        $('#addUserForm').on('submit', function(e) {
            e.preventDefault();
            
            const username = $('#userName').val().trim();
            const password = $('#userPassword').val().trim();
            const server_id = $('#userServer').val();
            
            if (!username || !password || !server_id) {
                showMessage('Todos los campos son obligatorios', 'error');
                return;
            }
            
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Verificando...';
            submitBtn.disabled = true;
            
            makeRequest({
                action: 'add_user',
                username: username,
                password: password,
                server_id: server_id
            }, 
            function(response) {
                let message = response.message;
                if (response.user && response.user.code) {
                    message += `<br><strong>Código generado:</strong> ${response.user.code}`;
                }
                if (response.user && response.user.expiry_date) {
                    message += `<br><strong>Fecha de expiración:</strong> ${response.user.expiry_date}`;
                }
                showMessage(message, 'success');
                
                $('#userName').val('');
                $('#userPassword').val('');
                $('#userServer').val('');
                
                setTimeout(() => location.reload(), 2000);
            },
            function() {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            });
            
            setTimeout(() => {
                if (submitBtn.disabled) {
                    submitBtn.innerHTML = originalText;
                    submitBtn.disabled = false;
                }
            }, 15000);
        });

        function deleteUser(id) {
            if (!confirm('¿Estás seguro de que quieres eliminar este usuario? Esta acción no se puede deshacer.')) {
                return;
            }
            
            makeRequest({
                action: 'delete_user',
                id: id
            }, 
            function(response) {
                showMessage(response.message, 'success');
                setTimeout(() => location.reload(), 1000);
            });
        }

        function toggleUser(id) {
            makeRequest({
                action: 'toggle_user',
                id: id
            }, 
            function(response) {
                showMessage(response.message, 'success');
                setTimeout(() => location.reload(), 1000);
            });
        }

        function checkExpiredUsers() {
            if (!confirm('¿Estás seguro de que quieres verificar y eliminar usuarios expirados?')) {
                return;
            }
            
            showMessage('Verificando usuarios... Esto puede tomar unos momentos.', 'success');
            
            makeRequest({
                action: 'check_expired'
            }, 
            function(response) {
                showMessage(response.message, 'success');
                setTimeout(() => location.reload(), 3000);
            });
        }

        function showTab(tabName) {
            document.querySelectorAll('.tab-content').forEach(tab => { 
                tab.classList.remove('active'); 
            });
            document.querySelectorAll('.tab-btn').forEach(btn => { 
                btn.classList.remove('active'); 
            });
            document.getElementById('tab-' + tabName).classList.add('active');
            event.target.classList.add('active');
        }

        $('#addServerForm').on('submit', function(e) {
            e.preventDefault();
            
            const name = $('#serverName').val().trim();
            const dns = $('#serverDns').val().trim();
            
            if (!name || !dns) {
                showMessage('Nombre y URL son obligatorios', 'error');
                return;
            }
            
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Agregando...';
            submitBtn.disabled = true;
            
            makeRequest({
                action: 'add_server',
                name: name,
                dns: dns
            }, 
            function(response) {
                showMessage(response.message, 'success');
                $('#serverName').val('');
                $('#serverDns').val('');
                setTimeout(() => location.reload(), 1000);
            },
            function() {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            });
            
            setTimeout(() => {
                if (submitBtn.disabled) {
                    submitBtn.innerHTML = originalText;
                    submitBtn.disabled = false;
                }
            }, 10000);
        });

        function deleteServer(id) {
            if (!confirm('¿Estás seguro de que quieres eliminar este servidor? No se puede eliminar si tiene usuarios asociados.')) {
                return;
            }
            
            makeRequest({
                action: 'delete_server',
                id: id
            }, 
            function(response) {
                showMessage(response.message, 'success');
                setTimeout(() => location.reload(), 1000);
            });
        }

        $(document).ready(function() {
            setTimeout(autoTestServers, 1000);
            setTimeout(updateOnlineCount, 10000);
        });
    </script>
</body>
</html>