<?php
session_start();
if (!isset($_SESSION['role_id']) || $_SESSION['role_id'] != 1) {
    header("Location: ../../index.php");
    exit();
}

include('../../includes/config.php');

// Fetch all users
$users = $conn->query("SELECT id, username FROM users ORDER BY username");

// Fetch login/logout info from session_durations
$logs = $conn->query("
    SELECT sd.*, u.username 
    FROM session_durations sd
    JOIN users u ON u.id = sd.user_id
    ORDER BY sd.login_time DESC
");
?>
<!-- HTML starts -->
<!DOCTYPE html>
<html>
<head>
    <title>User Logs</title>
    <link rel="stylesheet" href="../../css/dashboard.css">
    <style>
        body { background: url('../../images/profile.jpg') no-repeat center center fixed; background-size: cover; color: white; font-family: 'Segoe UI', sans-serif; }
        .container { max-width: 1000px; margin: 90px auto; padding: 30px; background: rgba(255,255,255,0.08); backdrop-filter: blur(15px); border-radius: 15px; }
        table { width: 100%; border-collapse: collapse; background: rgba(255,255,255,0.05); margin-top: 20px; }
        th, td { padding: 12px; border-bottom: 1px solid rgba(255,255,255,0.1); }
        th { background-color: rgba(255, 111, 0, 0.9); }
        .online { color: #4caf50; font-weight: bold; }
    </style>
</head>
<body>
<div class="container">
    <h2>User Session Logs</h2>
    <table>
        <thead>
            <tr>
                <th>User</th>
                <th>Login Time</th>
                <th>Logout Time</th>
                <th>Duration</th>
            </tr>
        </thead>
        <tbody>
        <?php while ($log = $logs->fetch_assoc()):
            $login = strtotime($log['login_time']);
            $logout = $log['logout_time'] ? strtotime($log['logout_time']) : time();
            $duration = $logout - $login;
        ?>
            <tr>
                <td><?= htmlspecialchars($log['username']) ?></td>
                <td><?= date("d M Y H:i", $login) ?></td>
                <td><?= $log['logout_time'] ? date("d M Y H:i", $logout) : '<span class="online">Online</span>' ?></td>
                <td><?= gmdate("H:i:s", $duration) ?></td>
            </tr>
        <?php endwhile; ?>
        </tbody>
    </table>
</div>
</body>
</html>
