<?php
require_once '../includes/init.php';

// Check admin access
if (!isAuthenticated() || !$_SESSION['is_admin']) {
    redirect(APP_URL . '/login.php');
}

$db = getDB();

// Handle settings update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $autoLogoutEnabled = isset($_POST['auto_logout_enabled']) ? 1 : 0;
    $autoLogoutMinutes = intval($_POST['auto_logout_minutes'] ?? 5);
    
    // Validate minutes
    if ($autoLogoutMinutes < 1 || $autoLogoutMinutes > 60) {
        $autoLogoutMinutes = 5;
    }
    
    // Update settings (key-value format)
    $stmt = $db->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = ?");
    $stmt->execute([$autoLogoutEnabled, 'auto_logout_enabled']);
    $stmt->execute([$autoLogoutMinutes, 'auto_logout_minutes']);
    
    // Log the action
    $stmt = $db->prepare("INSERT INTO activity_logs (user_id, action, details, ip_address, created_at) VALUES (?, 'update_auto_logout_settings', ?, ?, NOW())");
    $stmt->execute([$_SESSION['user_id'], json_encode([
        'auto_logout_enabled' => $autoLogoutEnabled,
        'auto_logout_minutes' => $autoLogoutMinutes,
        'updated_by' => $_SESSION['user_name']
    ]), $_SERVER['REMOTE_ADDR']]);
    
    $success = 'Auto-logout settings updated successfully';
}

// Get current settings (key-value format)
$stmt = $db->prepare("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('auto_logout_enabled', 'auto_logout_minutes')");
$stmt->execute();
$settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

$autoLogoutEnabled = ($settings['auto_logout_enabled'] ?? '1') === '1';
$autoLogoutMinutes = intval($settings['auto_logout_minutes'] ?? '5');

// Get user statistics
$stmt = $db->prepare("
    SELECT 
        COUNT(*) as total_users,
        COUNT(CASE WHEN status = 'approved' THEN 1 END) as approved_users,
        COUNT(CASE WHEN status = 'blocked' THEN 1 END) as blocked_users,
        COUNT(CASE WHEN failed_login_attempts >= 5 THEN 1 END) as locked_users
    FROM users
    WHERE is_admin = 0
");
$stmt->execute();
$userStats = $stmt->fetch();

$pageTitle = 'Auto-Logout Settings';
include '../includes/header.php';
?>

<div class="min-h-screen bg-slate-50 dark:bg-slate-900">
    <div class="max-w-4xl mx-auto">
        <!-- Header -->
        <header class="bg-white dark:bg-slate-800 shadow-sm border-b border-slate-200 dark:border-slate-700">
            <div class="px-6 py-4">
                <div class="flex items-center justify-between">
                    <div class="flex items-center gap-3">
                        <a href="dashboard.php" class="text-slate-600 dark:text-slate-400 hover:text-primary transition-colors">
                            <span class="material-symbols-outlined">arrow_back</span>
                        </a>
                        <div>
                            <h1 class="text-xl font-semibold text-slate-900 dark:text-slate-100">Auto-Logout Settings</h1>
                            <p class="text-sm text-slate-500 dark:text-slate-400">Configure automatic logout behavior</p>
                        </div>
                    </div>
                </div>
            </div>
        </header>

        <main class="p-6 space-y-6">
            <!-- Success Message -->
            <?php if (isset($success)): ?>
            <div class="bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg p-4">
                <div class="flex items-center gap-2">
                    <span class="material-symbols-outlined text-green-600 dark:text-green-400">check_circle</span>
                    <p class="text-green-800 dark:text-green-200"><?php echo htmlspecialchars($success); ?></p>
                </div>
            </div>
            <?php endif; ?>

            <!-- Settings Form -->
            <div class="bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 p-6">
                <h2 class="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-6">Auto-Logout Configuration</h2>
                
                <form method="POST" class="space-y-6">
                    <!-- Enable/Disable Auto-Logout -->
                    <div class="flex items-center justify-between p-4 bg-slate-50 dark:bg-slate-700 rounded-lg">
                        <div>
                            <h3 class="font-medium text-slate-900 dark:text-slate-100">Enable Auto-Logout</h3>
                            <p class="text-sm text-slate-600 dark:text-slate-400">Automatically logout users after inactivity</p>
                        </div>
                        <label class="relative inline-flex items-center cursor-pointer">
                            <input type="checkbox" name="auto_logout_enabled" class="sr-only peer" <?php echo $autoLogoutEnabled ? 'checked' : ''; ?>>
                            <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"></div>
                        </label>
                    </div>

                    <!-- Auto-Logout Minutes -->
                    <div>
                        <label class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                            Auto-Logout After (Minutes)
                        </label>
                        <div class="flex items-center gap-4">
                            <input type="range" name="auto_logout_minutes" min="1" max="60" value="<?php echo $autoLogoutMinutes; ?>" 
                                   class="flex-1 h-2 bg-slate-200 rounded-lg appearance-none cursor-pointer dark:bg-slate-700">
                            <div class="flex items-center gap-2 bg-slate-100 dark:bg-slate-700 rounded-lg px-3 py-2 min-w-[80px] text-center">
                                <span class="font-medium text-slate-900 dark:text-slate-100" id="minutes-display"><?php echo $autoLogoutMinutes; ?></span>
                                <span class="text-sm text-slate-600 dark:text-slate-400">min</span>
                            </div>
                        </div>
                        <p class="text-xs text-slate-500 dark:text-slate-400 mt-1">
                            Users will be automatically logged out after this many minutes of inactivity
                        </p>
                    </div>

                    <!-- Submit Button -->
                    <div class="flex justify-end gap-3 pt-4 border-t border-slate-200 dark:border-slate-700">
                        <a href="dashboard.php" class="px-4 py-2 text-slate-700 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg transition-colors">
                            Cancel
                        </a>
                        <button type="submit" class="px-6 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors font-medium">
                            Save Settings
                        </button>
                    </div>
                </form>
            </div>

            <!-- User Statistics -->
            <div class="bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 p-6">
                <h2 class="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-4">User Statistics</h2>
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                    <div class="text-center p-4 bg-slate-50 dark:bg-slate-700 rounded-lg">
                        <div class="text-2xl font-bold text-slate-900 dark:text-slate-100"><?php echo $userStats['total_users']; ?></div>
                        <div class="text-sm text-slate-600 dark:text-slate-400">Total Users</div>
                    </div>
                    <div class="text-center p-4 bg-green-50 dark:bg-green-900/20 rounded-lg">
                        <div class="text-2xl font-bold text-green-600 dark:text-green-400"><?php echo $userStats['approved_users']; ?></div>
                        <div class="text-sm text-green-600 dark:text-green-400">Approved</div>
                    </div>
                    <div class="text-center p-4 bg-red-50 dark:bg-red-900/20 rounded-lg">
                        <div class="text-2xl font-bold text-red-600 dark:text-red-400"><?php echo $userStats['blocked_users']; ?></div>
                        <div class="text-sm text-red-600 dark:text-red-400">Blocked</div>
                    </div>
                    <div class="text-center p-4 bg-orange-50 dark:bg-orange-900/20 rounded-lg">
                        <div class="text-2xl font-bold text-orange-600 dark:text-orange-400"><?php echo $userStats['locked_users']; ?></div>
                        <div class="text-sm text-orange-600 dark:text-orange-400">Locked</div>
                    </div>
                </div>
            </div>

            <!-- Security Information -->
            <div class="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-xl p-6">
                <h2 class="text-lg font-semibold text-blue-900 dark:text-blue-100 mb-4">Security Information</h2>
                <div class="space-y-3 text-sm text-blue-800 dark:text-blue-200">
                    <div class="flex items-start gap-2">
                        <span class="material-symbols-outlined text-blue-600 dark:text-blue-400 mt-0.5">info</span>
                        <div>
                            <p class="font-medium">Failed Login Protection:</p>
                            <p>Users are locked out after 5 failed login attempts for 30 minutes</p>
                        </div>
                    </div>
                    <div class="flex items-start gap-2">
                        <span class="material-symbols-outlined text-blue-600 dark:text-blue-400 mt-0.5">info</span>
                        <div>
                            <p class="font-medium">Auto-Logout Benefits:</p>
                            <p>Prevents unauthorized access and reduces security risks</p>
                        </div>
                    </div>
                    <div class="flex items-start gap-2">
                        <span class="material-symbols-outlined text-blue-600 dark:text-blue-400 mt-0.5">info</span>
                        <div>
                            <p class="font-medium">Session Management:</p>
                            <p>All user sessions are invalidated when auto-logout occurs</p>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<script>
// Update minutes display when slider changes
const slider = document.querySelector('input[name="auto_logout_minutes"]');
const display = document.getElementById('minutes-display');

slider.addEventListener('input', function() {
    display.textContent = this.value;
});
</script>

<?php include '../includes/footer.php'; ?>
