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

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


$limit = 20;
$page = max(1, (int)($_GET['page'] ?? 1));
$offset = ($page - 1) * $limit;

$filter_user = $_GET['user_id'] ?? '';
$filter_from = $_GET['from_date'] ?? '';
$filter_to = $_GET['to_date'] ?? '';

$conditions = [];
$params = [];
$types = '';

// Filter by user
if ($filter_user !== '') {
    $conditions[] = 'u.id = ?';
    $params[] = $filter_user;
    $types .= 'i';
}

// Filter by login date range (between last_logged_in)
if ($filter_from !== '') {
    $conditions[] = 'u.last_logged_in >= ?';
    $params[] = $filter_from . ' 00:00:00';
    $types .= 's';
}
if ($filter_to !== '') {
    $conditions[] = 'u.last_logged_in <= ?';
    $params[] = $filter_to . ' 23:59:59';
    $types .= 's';
}

$where = $conditions ? 'WHERE ' . implode(' AND ', $conditions) : '';

// Count total for pagination
$count_sql = "SELECT COUNT(*) as total FROM users u $where";
$count_stmt = $conn->prepare($count_sql);
if ($params) $count_stmt->bind_param($types, ...$params);
$count_stmt->execute();
$total = $count_stmt->get_result()->fetch_assoc()['total'] ?? 0;
$count_stmt->close();
$total_pages = ceil($total / $limit);

// Fetch user sessions info
$sql = "
    SELECT u.id, u.username, u.first_name, u.last_name, u.role_id, r.role_name, u.store_id, s.store_name,
           u.last_logged_in, u.last_logged_out
    FROM users u
    LEFT JOIN roles r ON u.role_id = r.id
    LEFT JOIN stores s ON u.store_id = s.id
    $where
    ORDER BY u.last_logged_in DESC
    LIMIT ? OFFSET ?
";

$stmt = $conn->prepare($sql);
if ($params) {
    $stmt->bind_param($types . 'ii', ...array_merge($params, [$limit, $offset]));
} else {
    $stmt->bind_param('ii', $limit, $offset);
}
$stmt->execute();
$users_sessions = $stmt->get_result();
$stmt->close();

// Helper to format duration between login and logout or now
function formatDurationFromTo($login, $logout) {
    $start = strtotime($login);
    $end = $logout ? strtotime($logout) : time();
    $diff = max(0, $end - $start);
    $h = floor($diff / 3600);
    $m = floor(($diff % 3600) / 60);
    $s = $diff % 60;
    return sprintf('%02d:%02d:%02d', $h, $m, $s);
}

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

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>User Sessions - Digital POS</title>
    <link rel="stylesheet" href="../../css/dashboard.css" />
    <style>
        body {
            margin: 0; font-family: 'Segoe UI', sans-serif;
            background: url('../../images/bg.jpg') no-repeat center center fixed;
            background-size: cover; color: white;
        }
        .overlay {
            position: fixed; top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(0,0,0,0.6); z-index: -1;
        }
        .content {
            margin: 80px auto; max-width: 1100px; padding: 30px;
            background: rgba(255,255,255,0.08); border-radius: 20px;
            backdrop-filter: blur(15px); box-shadow: 0 8px 32px rgba(0,0,0,0.5);
        }
        h2 { text-align: center; margin-bottom: 15px; }
        .filters {
            display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 20px; align-items: center;
        }
        .filters select, .filters input {
            padding: 8px 12px; border-radius: 8px; border: none;
            background: rgba(255,255,255,0.2); color: white;
            font-size: 14px;
        }
        button.filter-btn, button.export-btn {
            background: #ff6f00; color: white; border: none; border-radius: 8px;
            padding: 8px 14px; cursor: pointer; font-weight: bold;
        }
        button.export-btn {
            margin-left: auto;
            background: #e65100;
        }
        table {
            width: 100%; border-collapse: collapse;
            background: rgba(0,0,0,0.3); border-radius: 12px;
            overflow: hidden; box-shadow: 0 0 12px rgba(0,0,0,0.6);
            font-size: 14px;
        }
        th, td {
            padding: 10px 14px; border-bottom: 1px solid rgba(255,255,255,0.1);
            text-align: left;
        }
        th { background: rgba(255,111,0,0.9); }
        .pagination {
            margin-top: 15px; text-align: center;
        }
        .pagination a {
            padding: 6px 12px; margin: 2px; border-radius: 5px;
            background: rgba(255,255,255,0.1); color: white; text-decoration: none;
        }
        .pagination a.active { background: #ff6f00; font-weight: bold; }
        @media (max-width: 768px) {
            table, thead, tbody, th, td, tr { display: block; }
            th { display: none; }
            td {
                position: relative; padding-left: 50%;
                border: none; border-bottom: 1px solid rgba(255,255,255,0.1);
            }
            td::before {
                position: absolute; top: 10px; left: 10px; width: 45%;
                white-space: nowrap; font-weight: bold; color: #ffa500;
            }
            td:nth-of-type(1)::before { content: "User"; }
            td:nth-of-type(2)::before { content: "Role"; }
            td:nth-of-type(3)::before { content: "Store"; }
            td:nth-of-type(4)::before { content: "Last Login"; }
            td:nth-of-type(5)::before { content: "Last Logout"; }
            td:nth-of-type(6)::before { content: "Duration"; }
            td:nth-of-type(7)::before { content: "Status"; }
        }
        .status-online {
            color: #4caf50;
            font-weight: bold;
        }
        .status-offline {
            color: #f44336;
            font-weight: bold;
        }
    </style>
</head>
<body>
<div class="overlay"></div>
<div class="content">
    <h2>User Sessions (Live & Past)</h2>

    <form method="GET" class="filters">
        <select name="user_id">
            <option value="">All Users</option>
            <?php while ($u = $users->fetch_assoc()): ?>
                <option value="<?= $u['id'] ?>" <?= ($filter_user == $u['id']) ? 'selected' : '' ?>>
                    <?= htmlspecialchars($u['username']) ?>
                </option>
            <?php endwhile; ?>
        </select>
        <input type="date" name="from_date" value="<?= htmlspecialchars($filter_from) ?>">
        <input type="date" name="to_date" value="<?= htmlspecialchars($filter_to) ?>">
        <button type="submit" class="filter-btn">Filter</button>
    </form>

    <table>
        <thead>
        <tr>
            <th>User</th>
            <th>Role</th>
            <th>Store</th>
            <th>Last Login</th>
            <th>Last Logout</th>
            <th>Duration</th>
            <th>Status</th>
        </tr>
        </thead>
        <tbody>
        <?php if ($users_sessions->num_rows): ?>
            <?php
            $now = time();
            while ($row = $users_sessions->fetch_assoc()):
                $login_ts = strtotime($row['last_logged_in']);
                $logout_ts = $row['last_logged_out'] ? strtotime($row['last_logged_out']) : null;
                $duration_seconds = $logout_ts ? $logout_ts - $login_ts : $now - $login_ts;
                $online = !$logout_ts || $logout_ts < $login_ts;
            ?>
                <tr>
                    <td><?= htmlspecialchars($row['first_name'] . ' ' . $row['last_name']) ?></td>
                    <td><?= htmlspecialchars($row['role_name'] ?? '-') ?></td>
                    <td><?= htmlspecialchars($row['store_name'] ?? '-') ?></td>
                    <td><?= date('d M Y H:i', $login_ts) ?></td>
                    <td><?= $logout_ts ? date('d M Y H:i', $logout_ts) : '-' ?></td>
                    <td><?= formatDurationFromTo($row['last_logged_in'], $row['last_logged_out']) ?></td>
                    <td>
                        <?php if ($online): ?>
                            <span class="status-online">Online</span>
                        <?php else: ?>
                            <span class="status-offline">Offline</span>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endwhile; ?>
        <?php else: ?>
            <tr><td colspan="7" style="text-align:center;">No user session data found.</td></tr>
        <?php endif; ?>
        </tbody>
    </table>

    <div class="pagination">
        <?php for ($i = 1; $i <= $total_pages; $i++): ?>
            <a href="?<?= http_build_query(array_merge($_GET, ['page' => $i])) ?>"
               class="<?= ($i == $page) ? 'active' : '' ?>">
                <?= $i ?>
            </a>
        <?php endfor; ?>
    </div>

</div>
</body>
</html>
