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

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

$feedback = '';

// Get all exams
$exams_result = $mysqli->query("SELECT examination_id, examination_title FROM examination_table WHERE admin_status = 'active' ORDER BY date_of_examination DESC");
$exams = [];
while ($e = $exams_result->fetch_assoc()) {
    $exams[$e['examination_id']] = $e['examination_title'];
}

$exam_available = count($exams) > 0;

// Handle new token generation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['student_id'], $_POST['examination_id'])) {
    $student_id = intval($_POST['student_id']);
    $examination_id = $_POST['examination_id'];
    $token_id = 'TK' . strtoupper(substr(md5(uniqid()), 0, 10));
    $admin_id = $_SESSION['admin_id'];

    $stmt = $mysqli->prepare("INSERT INTO token_management (token_id, student_id, examination_id, admin_id) VALUES (?, ?, ?, ?)");
    $stmt->bind_param('sisi', $token_id, $student_id, $examination_id, $admin_id);

    if ($stmt->execute()) {
        $feedback = "<div class='alert alert-success'>Token generated for student ID $student_id and exam <strong>$examination_id</strong></div>";
    } else {
        $feedback = "<div class='alert alert-danger'>Failed to generate token.</div>";
    }
}

// Get student list
$student_result = $mysqli->query("SELECT serial, surname, lastname FROM student_table WHERE status = 'active' ORDER BY surname");
$students = [];
while ($row = $student_result->fetch_assoc()) {
    $students[$row['serial']] = $row['surname'] . ' ' . $row['lastname'];
}

// Get tokens
$query = "
SELECT tm.*, s.surname, s.lastname, e.examination_title
FROM token_management tm
LEFT JOIN student_table s ON s.serial = tm.student_id
LEFT JOIN examination_table e ON e.examination_id = tm.examination_id
ORDER BY tm.gen_time DESC
";
$result = $mysqli->query($query);
?>

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Manage Tokens</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'; ?>

  <div class="content-wrapper">
    <div class="content-header">
      <div class="container-fluid"><h1 class="m-0">Manage Tokens</h1></div>
    </div>
    <section class="content">
      <div class="container-fluid">
        <?= $feedback ?>

        <?php if ($exam_available): ?>
          <button class="btn btn-primary mb-3" data-toggle="modal" data-target="#tokenModal"><i class="fas fa-plus-circle"></i> Generate New Token</button>
        <?php else: ?>
          <div class="alert alert-warning">
            ⚠️ No active examinations found. Please <a href="manage_exams.php" class="alert-link">create an exam</a> before generating tokens.
          </div>
        <?php endif; ?>

        <div class="card">
          <div class="card-header bg-secondary text-white">All Tokens</div>
          <div class="card-body p-0">
            <table class="table table-striped table-bordered" id="tokenTable">
              <thead>
                <tr>
                  <th>Token ID</th>
                  <th>Student</th>
                  <th>Exam</th>
                  <th>Status</th>
                  <th>Generated</th>
                  <th>Login Time</th>
                  <th>Last Activity</th>
                  <th>Admin ID</th>
                </tr>
              </thead>
              <tbody>
                <?php while ($row = $result->fetch_assoc()): ?>
                  <tr>
                    <td><?= htmlspecialchars($row['token_id']) ?></td>
                    <td><?= htmlspecialchars($row['surname'] . ' ' . $row['lastname']) ?></td>
                    <td><?= htmlspecialchars($row['examination_title'] ?: '-') ?></td>
                    <td>
                      <span class="badge badge-<?= $row['status'] === 'used' ? 'success' : ($row['status'] === 'expired' ? 'danger' : 'secondary') ?>">
                        <?= htmlspecialchars($row['status']) ?>
                      </span>
                    </td>
                    <td><?= htmlspecialchars($row['gen_time']) ?></td>
                    <td><?= htmlspecialchars($row['login_time'] ?: '-') ?></td>
                    <td><?= htmlspecialchars($row['last_activity'] ?: '-') ?></td>
                    <td><?= htmlspecialchars($row['admin_id']) ?></td>
                  </tr>
                <?php endwhile; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </section>
  </div>
</div>

<!-- Modal -->
<div class="modal fade" id="tokenModal" tabindex="-1">
  <div class="modal-dialog">
    <form class="modal-content" method="POST">
      <div class="modal-header">
        <h5 class="modal-title">Generate Token</h5>
        <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
      </div>
      <div class="modal-body">
        <div class="form-group">
          <label>Student *</label>
          <select name="student_id" class="form-control" required>
            <option value="">-- Select Student --</option>
            <?php foreach ($students as $id => $name): ?>
              <option value="<?= $id ?>"><?= htmlspecialchars($name) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="form-group">
          <label>Examination *</label>
          <select name="examination_id" class="form-control" required>
            <option value="">-- Select Exam --</option>
            <?php foreach ($exams as $id => $title): ?>
              <option value="<?= $id ?>"><?= htmlspecialchars($title) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>
      <div class="modal-footer">
        <button type="submit" class="btn btn-success">Generate</button>
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
      </div>
    </form>
  </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() {
    $('#tokenTable').DataTable();
  });
</script>
</body>
</html>
