<?php

session_start();
require_once 'inc/connect.php';

if (!isset($_SESSION['admin_id'])) {
    header("Location: admin_login.php");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'fetch_activity') {
    $student = "%" . ($_POST['student'] ?? '') . "%";
    $exam = "%" . ($_POST['exam'] ?? '') . "%";
    $school_id = "%" . ($_POST['school_id'] ?? '') . "%";
    $token_id = "%" . ($_POST['token_id'] ?? '') . "%";

   $sql = "
    SELECT 
      CONCAT(s.lastname, ' ', COALESCE(s.middlename, ''), ' ', s.surname) AS student,
      s.school_id,
      e.examination_title AS examination,
      t.token_id,
      t.last_activity,
      TIMESTAMPDIFF(MINUTE, t.last_activity, NOW()) AS mins_ago
    FROM token_management t
    JOIN student_table s ON s.serial = t.student_id
    JOIN examination_table e ON e.examination_id = t.examination_id
    WHERE CONCAT(s.lastname, ' ', COALESCE(s.middlename, ''), ' ', s.surname) LIKE ?
      AND e.examination_title LIKE ?
      AND s.school_id LIKE ?
      AND t.token_id LIKE ?
      AND t.status = 'used'
      AND t.last_activity >= (NOW() - INTERVAL 40 MINUTE)
    ORDER BY t.last_activity DESC
";


    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param('ssss', $student, $exam, $school_id, $token_id);
    $stmt->execute();
    $result = $stmt->get_result();

    $output = [];
    while ($row = $result->fetch_assoc()) {
        $output[] = [
            'student' => $row['student'],
            'school_id' => $row['school_id'],
            'examination' => $row['examination'],
            'token_id' => $row['token_id'],
            'last_activity' => $row['last_activity'],
            'is_active' => $row['mins_ago'] !== null && $row['mins_ago'] < 5
        ];
    }

    header('Content-Type: application/json');
    echo json_encode($output);
    exit;
}
?>




<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Live Token Activity Tracker</title>
  <link rel="stylesheet" href="/plugins/fontawesome-free/css/all.min.css">
  <link rel="stylesheet" href="/plugins/datatables-bs4/css/dataTables.bootstrap4.min.css">
  <link rel="stylesheet" href="/dist/css/adminlte.min.css">
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">
  <?php include 'inc/admin_nav.php'; ?>
<!-- Content Wrapper -->
<div class="content-wrapper">
  <section class="content-header">
    <div class="container-fluid">
      <h1>Live Token Activity Tracker</h1>
    </div>
  </section>

  <section class="content">
    <div class="card card-primary">
      <div class="card-header">
        <h3 class="card-title">Filter Activity</h3>
      </div>
      <div class="card-body">
        <div class="row mb-3">
          <div class="col-md-3">
            <input type="text" id="filter_student" class="form-control" placeholder="Student Name">
          </div>
          <div class="col-md-3">
            <input type="text" id="filter_exam" class="form-control" placeholder="Examination Title">
          </div>
          <div class="col-md-3">
            <input type="text" id="filter_school" class="form-control" placeholder="School ID">
          </div>
          <div class="col-md-3">
            <input type="text" id="filter_token" class="form-control" placeholder="Token ID">
          </div>
        </div>
      </div>
    </div>

    <div class="card card-outline card-info">
      <div class="card-body table-responsive">
        <table id="activity_table" class="table table-bordered table-striped">
          <thead>
            <tr>
              <th>Student</th>
              <th>School ID</th>
              <th>Examination</th>
              <th>Token ID</th>
              <th>Last Activity</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody id="activity_body">
            <!-- Populated by JS -->
          </tbody>
        </table>
      </div>
    </div>
  </section>
</div>
</div>



<script src="/plugins/jquery/jquery.min.js"></script>
<script src="/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="/plugins/datatables/jquery.dataTables.min.js"></script>
<script src="/plugins/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>
<script src="/dist/js/adminlte.min.js"></script>

<script>
function fetchActivity() {
  const formData = new FormData();
  formData.append('action', 'fetch_activity');
  formData.append('student', document.getElementById('filter_student').value.trim());
  formData.append('exam', document.getElementById('filter_exam').value.trim());
  formData.append('school_id', document.getElementById('filter_school').value.trim());
  formData.append('token_id', document.getElementById('filter_token').value.trim());

  fetch(location.href, {
    method: 'POST',
    body: formData
  })
  .then(res => res.json())
  .then(response => {
    const tbody = document.getElementById('activity_body');
    tbody.innerHTML = '';
    response.forEach(row => {
      const tr = document.createElement('tr');
      const active = row.is_active ? 'text-success font-weight-bold' : 'text-muted';
      tr.innerHTML = `
        <td>${row.student}</td>
        <td>${row.school_id}</td>
        <td>${row.examination}</td>
        <td>${row.token_id}</td>
        <td>${row.last_activity}</td>
        <td class="${active}">${row.is_active ? 'Active' : 'Inactive'}</td>
      `;
      tbody.appendChild(tr);
    });
  });
}

setInterval(fetchActivity, 10000); // update every 10 seconds
document.querySelectorAll('input').forEach(input => {
  input.addEventListener('input', fetchActivity);
});
window.onload = fetchActivity;
</script>
</body>
</html>