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

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

$feedback = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $exam_id = trim($_POST['exam_id'] ?? '');
    $title = trim($_POST['title'] ?? '');
    $definition = trim($_POST['definition'] ?? '');
    $date = $_POST['date'] ?? '';
    $total_time = intval($_POST['total_time'] ?? 0);
    $question_time = intval($_POST['question_time'] ?? 0);
    $allowed_questions = intval($_POST['allowed_questions'] ?? 0);
    $token_prefix = strtoupper(substr(trim($_POST['token_prefix'] ?? ''), 0, 5));
    $allow_repeat = isset($_POST['allow_repeat']) ? 1 : 0;

    if ($title && $definition && $date && $total_time > 0 && $allowed_questions > 0) {
        if ($exam_id) {
            // Update existing
            $stmt = $mysqli->prepare("UPDATE examination_table SET 
                examination_definition = ?, examination_title = ?, date_of_examination = ?, 
                total_allowed_time = ?, total_question_time = ?, total_allowed_questions = ?, 
                token_prefix = ?, allow_question_repeat = ? 
                WHERE examination_id = ?");
            $stmt->bind_param('sssiiiiss', $definition, $title, $date, $total_time, $question_time, $allowed_questions, $token_prefix, $allow_repeat, $exam_id);
            $stmt->execute();
            $feedback = "<div class='alert alert-success'>Exam updated successfully!</div>";
        } else {
            // Insert new
            $exam_id = 'EX' . strtoupper(substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 6));
            $stmt = $mysqli->prepare("INSERT INTO examination_table 
                (examination_id, examination_definition, examination_title, date_of_examination, 
                 total_allowed_time, total_question_time, total_allowed_questions, token_prefix, allow_question_repeat, admin_status)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'active')");
            $stmt->bind_param('ssssiiiis', $exam_id, $definition, $title, $date, $total_time, $question_time, $allowed_questions, $token_prefix, $allow_repeat);
            $stmt->execute();
            $feedback = "<div class='alert alert-success'>Exam created successfully!</div>";
        }
    } else {
        $feedback = "<div class='alert alert-danger'>Please fill all required fields.</div>";
    }
}

// Fetch exams
$exams = mysqli_query($mysqli, "SELECT * FROM examination_table ORDER BY serial DESC");
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Manage Exams</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>Manage Exams</h1></div></div>

    <section class="content">
      <div class="container-fluid">
        <?= $feedback ?>
        <button class="btn btn-primary mb-3" data-toggle="modal" data-target="#addExamModal"><i class="fas fa-plus"></i> Add New Exam</button>

        <table id="examTable" class="table table-bordered table-striped">
          <thead>
            <tr>
              <th>Exam ID</th>
              <th>Title</th>
              <th>Date</th>
              <th>Total Time</th>
              <th>Questions</th>
              <th>Repeat</th>
              <th>Status</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>
            <?php while ($row = mysqli_fetch_assoc($exams)): ?>
              <tr>
                <td><?= htmlspecialchars($row['examination_id']) ?></td>
                <td><?= htmlspecialchars($row['examination_title']) ?></td>
                <td><?= htmlspecialchars($row['date_of_examination']) ?></td>
                <td><?= $row['total_allowed_time'] ?> mins</td>
                <td><?= $row['total_allowed_questions'] ?></td>
                <td><?= $row['allow_question_repeat'] ? 'Yes' : 'No' ?></td>
                <td><?= ucfirst($row['admin_status']) ?></td>
                <td>
                  <button class="btn btn-sm btn-warning editBtn"
                    data-id="<?= $row['examination_id'] ?>"
                    data-title="<?= htmlspecialchars($row['examination_title'], ENT_QUOTES) ?>"
                    data-definition="<?= htmlspecialchars($row['examination_definition'], ENT_QUOTES) ?>"
                    data-date="<?= $row['date_of_examination'] ?>"
                    data-time="<?= $row['total_allowed_time'] ?>"
                    data-qtime="<?= $row['total_question_time'] ?>"
                    data-questions="<?= $row['total_allowed_questions'] ?>"
                    data-prefix="<?= $row['token_prefix'] ?>"
                    data-repeat="<?= $row['allow_question_repeat'] ?>">
                    Edit
                  </button>
                </td>
              </tr>
            <?php endwhile; ?>
          </tbody>
        </table>
      </div>
    </section>
  </div>
</div>

<!-- Modal -->
<div class="modal fade" id="addExamModal" tabindex="-1" role="dialog" aria-labelledby="addExamModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <form method="POST" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Create New Exam</h5>
        <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="exam_id" id="exam_id">

        <div class="form-group">
          <label>Title *</label>
          <input type="text" name="title" class="form-control" required>
        </div>

        <div class="form-group">
          <label>Definition *</label>
          <textarea name="definition" class="form-control" rows="3" required></textarea>
        </div>

        <div class="form-group">
          <label>Exam Date *</label>
          <input type="date" name="date" class="form-control" required>
        </div>

        <div class="form-group">
          <label>Total Time (minutes) *</label>
          <input type="number" name="total_time" class="form-control" min="1" required>
        </div>

        <div class="form-group">
          <label>Total Question Time (optional)</label>
          <input type="number" name="question_time" class="form-control" min="0">
        </div>

        <div class="form-group">
          <label>Total Questions Allowed *</label>
          <input type="number" name="allowed_questions" class="form-control" min="1" required>
        </div>

        <div class="form-group">
          <label>Token Prefix (optional)</label>
          <input type="text" name="token_prefix" class="form-control" maxlength="5">
        </div>

        <div class="form-check mb-3">
          <input type="checkbox" name="allow_repeat" class="form-check-input" id="repeatCheck">
          <label class="form-check-label" for="repeatCheck">Allow Question Repeat</label>
        </div>

      </div>
      <div class="modal-footer">
        <button type="submit" class="btn btn-primary">Create Exam</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 () {
  $('#examTable').DataTable();

  $('.editBtn').click(function () {
    const btn = $(this);
    $('#exam_id').val(btn.data('id'));
    $('input[name="title"]').val(btn.data('title'));
    $('textarea[name="definition"]').val(btn.data('definition'));
    $('input[name="date"]').val(btn.data('date'));
    $('input[name="total_time"]').val(btn.data('time'));
    $('input[name="question_time"]').val(btn.data('qtime'));
    $('input[name="allowed_questions"]').val(btn.data('questions'));
    $('input[name="token_prefix"]').val(btn.data('prefix'));
    $('#repeatCheck').prop('checked', btn.data('repeat') == 1);

    $('#addExamModal .modal-title').text('Update Exam');
    $('#addExamModal button[type="submit"]').text('Update Exam');
    $('#addExamModal').modal('show');
  });

  $('#addExamModal').on('hidden.bs.modal', function () {
    $(this).find('form')[0].reset();
    $('#exam_id').val('');
    $('#addExamModal .modal-title').text('Create New Exam');
    $('#addExamModal button[type="submit"]').text('Create Exam');
  });
});
</script>
</body>
</html>
