<?php
require_once __DIR__ . '/../config/database.php';

requireLogin();
requireAnyRole(['admin', 'super_admin']);

$db = Database::getInstance();

$student = isset($_GET['student']) ? (int)$_GET['student'] : 0;
$role = isset($_GET['role']) ? trim($_GET['role']) : 'student';
$activeOnly = isset($_GET['active']) ? (int)$_GET['active'] : 1;

$where = [];
$params = [];

if ($role !== '') {
    $where[] = 'us.role = ?';
    $params[] = $role;
}
if ($student > 0) {
    $where[] = 'us.user_id = ?';
    $params[] = $student;
}
if ($activeOnly === 1) {
    $where[] = 'us.is_active = 1';
}

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

$sessions = $db->getAll(
    "SELECT us.*, u.username, u.email, u.first_name, u.last_name,
            u.region, u.status AS user_status
       FROM user_sessions us
       JOIN users u ON us.user_id = u.id
       $whereSql
   ORDER BY us.created_at DESC
      LIMIT 500",
    $params
);

$students = $db->getAll(
    "SELECT u.id, u.username, u.first_name, u.last_name
       FROM users u
       JOIN user_roles ur ON u.id = ur.user_id
      WHERE ur.role = 'student' AND u.status = 'active'
   ORDER BY u.last_name, u.first_name",
    []
);

$pageTitle = 'Student Sessions';
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="h4 mb-0">Student Sessions</h1>
    <p class="text-muted mb-0">View active and recent login sessions for students</p>
  </div>
</div>

<div class="card mb-4">
  <div class="card-header">
    <form method="get" class="row g-3">
      <div class="col-sm-3">
        <label class="form-label">Student</label>
        <select name="student" class="form-select">
          <option value="">All</option>
          <?php foreach ($students as $s): ?>
            <option value="<?php echo (int)$s['id']; ?>" <?php echo $student === (int)$s['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars(($s['first_name'] ?? '') . ' ' . ($s['last_name'] ?? '') . ' (' . ($s['username'] ?? '') . ')'); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-sm-3">
        <label class="form-label">Role</label>
        <select name="role" class="form-select">
          <?php foreach (['student','instructor','admin','super_admin'] as $r): ?>
            <option value="<?php echo $r; ?>" <?php echo $role === $r ? 'selected' : ''; ?>><?php echo ucfirst(str_replace('_',' ',$r)); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-sm-3">
        <label class="form-label">Status</label>
        <select name="active" class="form-select">
          <option value="1" <?php echo $activeOnly === 1 ? 'selected' : ''; ?>>Active only</option>
          <option value="0" <?php echo $activeOnly === 0 ? 'selected' : ''; ?>>All (active and ended)</option>
        </select>
      </div>
      <div class="col-sm-3 align-self-end">
        <button class="btn btn-primary" type="submit">Filter</button>
      </div>
    </form>
  </div>
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-striped table-hover mb-0">
        <thead>
          <tr>
            <th>ID</th>
            <th>Student</th>
            <th>Role</th>
            <th>IP</th>
            <th>User Agent</th>
            <th>Active</th>
            <th>Started</th>
            <th>Last Seen</th>
            <th>Ended</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$sessions): ?>
            <tr><td colspan="9" class="text-center text-muted py-4">No sessions found.</td></tr>
          <?php else: foreach ($sessions as $row): ?>
            <tr>
              <td><?php echo (int)$row['id']; ?></td>
              <td>
                <div>
                  <strong><?php echo htmlspecialchars(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? '')); ?></strong><br>
                  <small class="text-muted"><?php echo htmlspecialchars($row['username'] ?? ''); ?> &lt;<?php echo htmlspecialchars($row['email'] ?? ''); ?>&gt;</small>
                </div>
              </td>
              <td><?php echo htmlspecialchars(ucfirst(str_replace('_',' ', $row['role'] ?? ''))); ?></td>
              <td><?php echo htmlspecialchars($row['ip_address'] ?? ''); ?></td>
              <td><small class="text-muted"><?php echo htmlspecialchars($row['user_agent'] ?? ''); ?></small></td>
              <td>
                <?php if ((int)($row['is_active'] ?? 0) === 1): ?>
                  <span class="badge bg-success">Active</span>
                <?php else: ?>
                  <span class="badge bg-secondary">Ended</span>
                <?php endif; ?>
              </td>
              <td><?php echo htmlspecialchars($row['created_at'] ?? ''); ?></td>
              <td><?php echo htmlspecialchars($row['last_seen'] ?? ''); ?></td>
              <td><?php echo htmlspecialchars($row['ended_at'] ?? ''); ?></td>
            </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

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