<?php
// admin_setup.php - Admin Settings & User Management
require_once 'config.php';
requireAdmin();

$message = '';
$error = '';

$pdo = getDBConnection();

// ============================================
// Handle Form Submissions
// ============================================

// Update VirusTotal API key
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_vt_key'])) {
    $vtKey = trim($_POST['virustotal_api_key'] ?? '');
    $stmt = $pdo->prepare("UPDATE system_settings SET setting_value = ? WHERE setting_key = 'virustotal_api_key'");
    $stmt->execute([$vtKey]);
    $message = "✅ VirusTotal API key updated successfully!";
}

// Update WPScan API key
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_wpscan_key'])) {
    $wpscanKey = trim($_POST['wpscan_api_key'] ?? '');
    $stmt = $pdo->prepare("UPDATE system_settings SET setting_value = ? WHERE setting_key = 'wpscan_api_key'");
    $stmt->execute([$wpscanKey]);
    $message = "✅ WPScan API key updated successfully!";
}

// Update Gemini API key
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_gemini_key'])) {
    $geminiKey = trim($_POST['gemini_api_key'] ?? '');
    $stmt = $pdo->prepare("UPDATE system_settings SET setting_value = ? WHERE setting_key = 'gemini_api_key'");
    $stmt->execute([$geminiKey]);
    $message = "✅ Gemini API key updated successfully!";
}

// Update system settings
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_system'])) {
    $siteName = trim($_POST['site_name'] ?? '');
    $maintenanceMode = isset($_POST['maintenance_mode']) ? 1 : 0;
    $allowRegistration = isset($_POST['allow_registration']) ? 1 : 0;
    $requireActivation = isset($_POST['require_activation']) ? 1 : 0;
    $theme = $_POST['theme'] ?? 'dark';
    
    $settings = [
        'site_name' => $siteName,
        'maintenance_mode' => $maintenanceMode,
        'allow_registration' => $allowRegistration,
        'require_activation' => $requireActivation,
        'theme' => $theme
    ];
    
    foreach ($settings as $key => $value) {
        $stmt = $pdo->prepare("UPDATE system_settings SET setting_value = ? WHERE setting_key = ?");
        $stmt->execute([$value, $key]);
    }
    
    $message = "✅ System settings updated successfully!";
}

// Update security settings
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_security'])) {
    $sessionTimeout = (int)$_POST['session_timeout'];
    $maxLoginAttempts = (int)$_POST['max_login_attempts'];
    $lockoutTime = (int)$_POST['lockout_time'];
    
    $settings = [
        'session_timeout' => $sessionTimeout,
        'max_login_attempts' => $maxLoginAttempts,
        'lockout_time' => $lockoutTime
    ];
    
    foreach ($settings as $key => $value) {
        $stmt = $pdo->prepare("UPDATE system_settings SET setting_value = ? WHERE setting_key = ?");
        $stmt->execute([$value, $key]);
    }
    
    $message = "✅ Security settings updated successfully!";
}

// Handle user activation (FIXED - removed updated_at)
if (isset($_GET['activate'])) {
    $userId = (int)$_GET['activate'];
    $user = getUserById($userId);
    
    if ($user && $user['is_admin'] != 1) {
        $stmt = $pdo->prepare("UPDATE users SET is_active = 1, activation_token = NULL WHERE id = ?");
        $stmt->execute([$userId]);
        logUserActivity($_SESSION['user_id'], 'admin_activate', "Activated user: {$user['username']}");
        $message = "✅ User '{$user['username']}' has been activated successfully!";
    } else {
        $error = "❌ Cannot activate this user.";
    }
}

// Handle user deactivation (FIXED - removed updated_at)
if (isset($_GET['deactivate'])) {
    $userId = (int)$_GET['deactivate'];
    $user = getUserById($userId);
    
    // Prevent self deactivation
    if ($userId == $_SESSION['user_id']) {
        $error = "❌ You cannot deactivate your own account!";
    } elseif ($user && $user['is_admin'] == 1) {
        $error = "❌ Cannot deactivate admin accounts!";
    } elseif ($user) {
        $stmt = $pdo->prepare("UPDATE users SET is_active = 0 WHERE id = ?");
        $stmt->execute([$userId]);
        logUserActivity($_SESSION['user_id'], 'admin_deactivate', "Deactivated user: {$user['username']}");
        $message = "⚠️ User '{$user['username']}' has been deactivated.";
    } else {
        $error = "❌ User not found.";
    }
}

// Handle user deletion
if (isset($_GET['delete'])) {
    $userId = (int)$_GET['delete'];
    $user = getUserById($userId);
    
    if ($userId == $_SESSION['user_id']) {
        $error = "❌ You cannot delete your own account!";
    } elseif ($user && $user['is_admin'] == 1) {
        $error = "❌ Cannot delete admin accounts!";
    } elseif ($user) {
        // First delete related records
        $pdo->prepare("DELETE FROM user_activity WHERE user_id = ?")->execute([$userId]);
        $pdo->prepare("DELETE FROM user_sessions WHERE user_id = ?")->execute([$userId]);
        $pdo->prepare("DELETE FROM users WHERE id = ?")->execute([$userId]);
        logUserActivity($_SESSION['user_id'], 'admin_delete', "Deleted user: {$user['username']}");
        $message = "🗑️ User '{$user['username']}' has been deleted.";
    } else {
        $error = "❌ User not found.";
    }
}

// Get current settings
$currentVtKey = $pdo->query("SELECT setting_value FROM system_settings WHERE setting_key = 'virustotal_api_key'")->fetchColumn();
$currentWpscanKey = $pdo->query("SELECT setting_value FROM system_settings WHERE setting_key = 'wpscan_api_key'")->fetchColumn();
$currentGeminiKey = $pdo->query("SELECT setting_value FROM system_settings WHERE setting_key = 'gemini_api_key'")->fetchColumn();

$siteName = $pdo->query("SELECT setting_value FROM system_settings WHERE setting_key = 'site_name'")->fetchColumn() ?: APP_NAME;
$maintenanceMode = $pdo->query("SELECT setting_value FROM system_settings WHERE setting_key = 'maintenance_mode'")->fetchColumn() ?: 0;
$allowRegistration = $pdo->query("SELECT setting_value FROM system_settings WHERE setting_key = 'allow_registration'")->fetchColumn() ?: 1;
$requireActivation = $pdo->query("SELECT setting_value FROM system_settings WHERE setting_key = 'require_activation'")->fetchColumn() ?: 1;
$currentTheme = $pdo->query("SELECT setting_value FROM system_settings WHERE setting_key = 'theme'")->fetchColumn() ?: 'dark';

$sessionTimeout = $pdo->query("SELECT setting_value FROM system_settings WHERE setting_key = 'session_timeout'")->fetchColumn() ?: 7200;
$maxLoginAttempts = $pdo->query("SELECT setting_value FROM system_settings WHERE setting_key = 'max_login_attempts'")->fetchColumn() ?: 5;
$lockoutTime = $pdo->query("SELECT setting_value FROM system_settings WHERE setting_key = 'lockout_time'")->fetchColumn() ?: 900;

// Get all users for management
$users = getAllUsers();

// Count statistics
$totalUsers = count($users);
$activeUsers = count(array_filter($users, function($u) { return isset($u['is_active']) && $u['is_active']; }));
$pendingUsers = count(array_filter($users, function($u) { return isset($u['is_active']) && !$u['is_active'] && !$u['is_admin']; }));
$adminCount = count(array_filter($users, function($u) { return $u['is_admin']; }));

$theme = getTheme();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Settings - <?php echo APP_NAME; ?></title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            transition: all 0.3s ease;
        }
        
        body.dark {
            background: #0a0a0f;
            color: #e4e4e7;
        }
        
        body.light {
            background: #f5f5f5;
            color: #1a1a2e;
        }
        
        .navbar {
            background: rgba(19, 19, 26, 0.95);
            backdrop-filter: blur(10px);
            border-bottom: 1px solid rgba(255, 255, 255, 0.06);
            padding: 15px 30px;
            position: sticky;
            top: 0;
            z-index: 100;
        }
        
        body.light .navbar {
            background: rgba(255, 255, 255, 0.95);
            border-bottom: 1px solid rgba(0, 0, 0, 0.1);
        }
        
        .nav-container {
            max-width: 1400px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
        }
        
        .logo h2 {
            background: linear-gradient(135deg, #06b6d4, #14b8a6);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            font-size: 24px;
        }
        
        .nav-links {
            display: flex;
            gap: 10px;
            align-items: center;
            flex-wrap: wrap;
        }
        
        .nav-links a {
            color: #a1a1aa;
            text-decoration: none;
            padding: 8px 14px;
            border-radius: 8px;
            transition: all 0.2s;
            font-size: 13px;
        }
        
        .nav-links a:hover, .nav-links a.active {
            background: rgba(6, 182, 212, 0.1);
            color: #06b6d4;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 30px;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: rgba(255, 255, 255, 0.03);
            border: 1px solid rgba(255, 255, 255, 0.06);
            border-radius: 16px;
            padding: 20px;
            text-align: center;
        }
        
        body.light .stat-card {
            background: #fff;
            border: 1px solid #e0e0e0;
        }
        
        .stat-value {
            font-size: 32px;
            font-weight: 800;
            color: #06b6d4;
        }
        
        .stat-label {
            font-size: 13px;
            opacity: 0.7;
            margin-top: 8px;
        }
        
        .card {
            background: rgba(255, 255, 255, 0.03);
            border: 1px solid rgba(255, 255, 255, 0.06);
            border-radius: 16px;
            padding: 25px;
            margin-bottom: 30px;
        }
        
        body.light .card {
            background: #fff;
            border: 1px solid #e0e0e0;
        }
        
        .card h3 {
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid rgba(6, 182, 212, 0.3);
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .form-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 15px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        label {
            display: block;
            margin-bottom: 8px;
            font-size: 13px;
            font-weight: 600;
        }
        
        input, select, textarea {
            width: 100%;
            padding: 12px 16px;
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 10px;
            color: inherit;
            font-size: 14px;
        }
        
        body.light input, body.light select, body.light textarea {
            background: #f9f9f9;
            border: 1px solid #ddd;
            color: #1a1a2e;
        }
        
        input:focus, select:focus {
            outline: none;
            border-color: #06b6d4;
        }
        
        input[type="checkbox"] {
            width: auto;
            margin-right: 8px;
        }
        
        .checkbox-group {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 10px;
        }
        
        .btn {
            padding: 12px 24px;
            background: linear-gradient(135deg, #06b6d4, #14b8a6);
            color: white;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            transition: all 0.3s;
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(6, 182, 212, 0.3);
        }
        
        .btn-danger {
            background: linear-gradient(135deg, #ef4444, #dc2626);
        }
        
        .btn-sm {
            padding: 6px 12px;
            font-size: 12px;
        }
        
        .message {
            background: rgba(34, 197, 94, 0.2);
            border: 1px solid rgba(34, 197, 94, 0.3);
            color: #22c55e;
            padding: 12px 16px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        
        .error {
            background: rgba(239, 68, 68, 0.2);
            border: 1px solid rgba(239, 68, 68, 0.3);
            color: #ef4444;
            padding: 12px 16px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid rgba(255, 255, 255, 0.06);
        }
        
        body.light th, body.light td {
            border-bottom: 1px solid #e0e0e0;
        }
        
        th {
            background: rgba(6, 182, 212, 0.1);
            font-weight: 600;
        }
        
        .badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
        }
        
        .badge-active {
            background: rgba(34, 197, 94, 0.2);
            color: #22c55e;
        }
        
        .badge-inactive {
            background: rgba(239, 68, 68, 0.2);
            color: #ef4444;
        }
        
        .badge-admin {
            background: rgba(245, 158, 11, 0.2);
            color: #f59e0b;
        }
        
        .actions {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }
        
        .action-btn {
            padding: 4px 10px;
            border-radius: 6px;
            text-decoration: none;
            font-size: 11px;
            transition: all 0.2s;
        }
        
        .action-activate {
            background: rgba(34, 197, 94, 0.2);
            color: #22c55e;
        }
        
        .action-deactivate {
            background: rgba(239, 68, 68, 0.2);
            color: #ef4444;
        }
        
        .action-delete {
            background: rgba(239, 68, 68, 0.15);
            color: #ef4444;
        }
        
        .theme-toggle {
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 50%;
            width: 36px;
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            font-size: 18px;
        }
        
        .tabs {
            display: flex;
            gap: 5px;
            margin-bottom: 20px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            flex-wrap: wrap;
        }
        
        .tab {
            padding: 10px 20px;
            cursor: pointer;
            border-radius: 8px 8px 0 0;
            transition: all 0.2s;
        }
        
        .tab.active {
            background: rgba(6, 182, 212, 0.1);
            color: #06b6d4;
            border-bottom: 2px solid #06b6d4;
        }
        
        .tab-content {
            display: none;
        }
        
        .tab-content.active {
            display: block;
        }
        
        @media (max-width: 768px) {
            .container {
                padding: 15px;
            }
            .form-row {
                grid-template-columns: 1fr;
            }
            table {
                font-size: 12px;
                overflow-x: auto;
                display: block;
            }
            .actions {
                flex-direction: column;
            }
        }
    </style>
</head>
<body class="<?php echo $theme; ?>">
    <nav class="navbar">
        <div class="nav-container">
            <div class="logo">
                <h2>⚙️ <?php echo APP_NAME; ?> Admin</h2>
            </div>
            <div class="nav-links">
                <a href="index.php">Dashboard</a>
                <a href="attack.php">Attack</a>
                <a href="defense.php">Defense</a>
                <a href="dpa.php">DPA</a>
                <a href="reports.php">Reports</a>
                <a href="admin_setup.php" class="active">Admin</a>
                <a href="member/logout.php">Logout</a>
                <div class="theme-toggle" onclick="toggleTheme()">
                    <?php echo $theme === 'dark' ? '☀️' : '🌙'; ?>
                </div>
            </div>
        </div>
    </nav>
    
    <div class="container">
        <?php if ($message): ?>
            <div class="message"><?php echo htmlspecialchars($message); ?></div>
        <?php endif; ?>
        
        <?php if ($error): ?>
            <div class="error"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>
        
        <!-- Statistics -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-value"><?php echo $totalUsers; ?></div>
                <div class="stat-label">Total Users</div>
            </div>
            <div class="stat-card">
                <div class="stat-value"><?php echo $activeUsers; ?></div>
                <div class="stat-label">Active Users</div>
            </div>
            <div class="stat-card">
                <div class="stat-value"><?php echo $pendingUsers; ?></div>
                <div class="stat-label">Pending Activation</div>
            </div>
            <div class="stat-card">
                <div class="stat-value"><?php echo $adminCount; ?></div>
                <div class="stat-label">Administrators</div>
            </div>
        </div>
        
        <!-- Tabs -->
        <div class="tabs">
            <div class="tab active" data-tab="users">👥 User Management</div>
            <div class="tab" data-tab="api">🔑 API Keys</div>
            <div class="tab" data-tab="system">⚙️ System Settings</div>
            <div class="tab" data-tab="security">🔒 Security</div>
            <div class="tab" data-tab="info">ℹ️ System Info</div>
        </div>
        
        <!-- Tab 1: User Management -->
        <div id="tab-users" class="tab-content active">
            <div class="card">
                <h3>👥 User Management</h3>
                <?php if (empty($users)): ?>
                    <p style="text-align: center; padding: 40px;">No users found.</p>
                <?php else: ?>
                    <div style="overflow-x: auto;">
                        <table>
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Username</th>
                                    <th>Email</th>
                                    <th>Full Name</th>
                                    <th>Status</th>
                                    <th>Role</th>
                                    <th>Joined</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($users as $user): ?>
                                <tr>
                                    <td><?php echo $user['id']; ?></td>
                                    <td><?php echo htmlspecialchars($user['username']); ?></td>
                                    <td><?php echo htmlspecialchars($user['email']); ?></td>
                                    <td><?php echo htmlspecialchars($user['full_name'] ?: '-'); ?></td>
                                    <td>
                                        <?php if (isset($user['is_active']) && $user['is_active']): ?>
                                            <span class="badge badge-active">✓ Active</span>
                                        <?php else: ?>
                                            <span class="badge badge-inactive">⏳ Pending</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($user['is_admin']): ?>
                                            <span class="badge badge-admin">👑 Admin</span>
                                        <?php else: ?>
                                            <span class="badge badge-active">👤 Member</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo date('Y-m-d', strtotime($user['created_at'])); ?></td>
                                    <td class="actions">
                                        <?php if (isset($user['is_active']) && !$user['is_active'] && !$user['is_admin']): ?>
                                            <a href="?activate=<?php echo $user['id']; ?>" class="action-btn action-activate" onclick="return confirm('Activate this user?')">✅ Activate</a>
                                        <?php elseif (isset($user['is_active']) && $user['is_active'] && !$user['is_admin'] && $user['id'] != $_SESSION['user_id']): ?>
                                            <a href="?deactivate=<?php echo $user['id']; ?>" class="action-btn action-deactivate" onclick="return confirm('Deactivate this user?')">⛔ Deactivate</a>
                                        <?php endif; ?>
                                        <?php if (!$user['is_admin'] && $user['id'] != $_SESSION['user_id']): ?>
                                            <a href="?delete=<?php echo $user['id']; ?>" class="action-btn action-delete" onclick="return confirm('Permanently delete this user? This cannot be undone.')">🗑️ Delete</a>
                                        <?php endif; ?>
                                        <?php if ($user['id'] == $_SESSION['user_id']): ?>
                                            <span style="opacity: 0.5;">(You)</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Tab 2: API Keys -->
        <div id="tab-api" class="tab-content">
            <div class="card">
                <h3>🔑 API Configuration</h3>
                
                <form method="POST">
                    <div class="form-group">
                        <label>🔐 VirusTotal API Key</label>
                        <input type="text" name="virustotal_api_key" value="<?php echo htmlspecialchars($currentVtKey); ?>" placeholder="Enter your VirusTotal API key">
                        <small>Get your free key from <a href="https://www.virustotal.com/gui/my-apikey" target="_blank">VirusTotal</a></small>
                    </div>
                    <button type="submit" name="update_vt_key" class="btn">💾 Save VirusTotal Key</button>
                </form>
                
                <form method="POST" style="margin-top: 25px;">
                    <div class="form-group">
                        <label>🔐 WPScan API Key</label>
                        <input type="text" name="wpscan_api_key" value="<?php echo htmlspecialchars($currentWpscanKey); ?>" placeholder="Enter your WPScan API key">
                        <small>Get your key from <a href="https://wpscan.com/" target="_blank">WPScan</a></small>
                    </div>
                    <button type="submit" name="update_wpscan_key" class="btn">💾 Save WPScan Key</button>
                </form>
                
                <form method="POST" style="margin-top: 25px;">
                    <div class="form-group">
                        <label>🤖 Google Gemini API Key</label>
                        <input type="text" name="gemini_api_key" value="<?php echo htmlspecialchars($currentGeminiKey); ?>" placeholder="Enter your Gemini API key">
                        <small>Get your key from <a href="https://makersuite.google.com/app/apikey" target="_blank">Google AI Studio</a></small>
                    </div>
                    <button type="submit" name="update_gemini_key" class="btn">💾 Save Gemini Key</button>
                </form>
            </div>
        </div>
        
        <!-- Tab 3: System Settings -->
        <div id="tab-system" class="tab-content">
            <div class="card">
                <h3>⚙️ System Configuration</h3>
                
                <form method="POST">
                    <div class="form-group">
                        <label>🏢 Site Name</label>
                        <input type="text" name="site_name" value="<?php echo htmlspecialchars($siteName); ?>" placeholder="Site Name">
                    </div>
                    
                    <div class="form-group">
                        <label>🎨 Theme</label>
                        <select name="theme">
                            <option value="dark" <?php echo $currentTheme == 'dark' ? 'selected' : ''; ?>>Dark</option>
                            <option value="light" <?php echo $currentTheme == 'light' ? 'selected' : ''; ?>>Light</option>
                        </select>
                    </div>
                    
                    <div class="checkbox-group">
                        <input type="checkbox" name="maintenance_mode" id="maintenance_mode" value="1" <?php echo $maintenanceMode ? 'checked' : ''; ?>>
                        <label for="maintenance_mode">🔧 Maintenance Mode (Only admins can access)</label>
                    </div>
                    
                    <div class="checkbox-group">
                        <input type="checkbox" name="allow_registration" id="allow_registration" value="1" <?php echo $allowRegistration ? 'checked' : ''; ?>>
                        <label for="allow_registration">📝 Allow New User Registration</label>
                    </div>
                    
                    <div class="checkbox-group">
                        <input type="checkbox" name="require_activation" id="require_activation" value="1" <?php echo $requireActivation ? 'checked' : ''; ?>>
                        <label for="require_activation">✅ Require Admin Activation for New Users</label>
                    </div>
                    
                    <button type="submit" name="update_system" class="btn">💾 Save System Settings</button>
                </form>
            </div>
        </div>
        
        <!-- Tab 4: Security Settings -->
        <div id="tab-security" class="tab-content">
            <div class="card">
                <h3>🔒 Security Configuration</h3>
                
                <form method="POST">
                    <div class="form-group">
                        <label>⏱️ Session Timeout (seconds)</label>
                        <input type="number" name="session_timeout" value="<?php echo $sessionTimeout; ?>" placeholder="7200 = 2 hours">
                        <small>How long until inactive users are logged out</small>
                    </div>
                    
                    <div class="form-group">
                        <label>🔐 Max Login Attempts</label>
                        <input type="number" name="max_login_attempts" value="<?php echo $maxLoginAttempts; ?>" placeholder="5">
                        <small>Number of failed login attempts before lockout</small>
                    </div>
                    
                    <div class="form-group">
                        <label>⏰ Lockout Time (seconds)</label>
                        <input type="number" name="lockout_time" value="<?php echo $lockoutTime; ?>" placeholder="900 = 15 minutes">
                        <small>How long to lock out after max attempts</small>
                    </div>
                    
                    <button type="submit" name="update_security" class="btn">💾 Save Security Settings</button>
                </form>
            </div>
        </div>
        
        <!-- Tab 5: System Info -->
        <div id="tab-info" class="tab-content">
            <div class="card">
                <h3>ℹ️ System Information</h3>
                <table style="width: 100%;">
                    <tr><th style="width: 200px;">Application Name</th><td><?php echo APP_NAME; ?></td></tr>
                    <tr><th>Version</th><td><?php echo APP_VERSION; ?></td></tr>
                    <tr><th>Copyright</th><td><?php echo COPYRIGHT; ?></td></tr>
                    <tr><th>PHP Version</th><td><?php echo phpversion(); ?></td></tr>
                    <tr><th>Database</th><td>SQLite 3</td></tr>
                    <tr><th>AI Model</th><td>Google Gemini 1.5 Flash</td></tr>
                    <tr><th>Server Software</th><td><?php echo $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown'; ?></td></tr>
                    <tr><th>Server Time</th><td><?php echo date('Y-m-d H:i:s'); ?></td></tr>
                    <tr><th>Timezone</th><td><?php echo date_default_timezone_get(); ?></td></tr>
                </table>
            </div>
        </div>
    </div>
    
    <script>
        // Tab switching
        document.querySelectorAll('.tab').forEach(tab => {
            tab.addEventListener('click', function() {
                const tabId = this.getAttribute('data-tab');
                
                document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
                document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
                
                this.classList.add('active');
                document.getElementById(`tab-${tabId}`).classList.add('active');
            });
        });
        
        // Theme toggle
        function toggleTheme() {
            const body = document.body;
            const isDark = body.classList.contains('dark');
            const newTheme = isDark ? 'light' : 'dark';
            
            body.classList.remove('dark', 'light');
            body.classList.add(newTheme);
            
            document.cookie = `soulguard_theme=${newTheme}; path=/; max-age=31536000`;
            location.reload();
        }
    </script>
</body>
</html>