<?php
chdir('../');
session_start();
require_once('public/connection.php');

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

include('partials/header.php');
include('partials/navbar.php');
include('partials/sidebar.php');

// Handle single reset
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reset_single'])) {
    $student_id = (int) $_POST['student_id'];
    $exam_id = (int) $_POST['exam_id'];

    $conn->query("DELETE FROM student_exam_attempts WHERE student_id = $student_id AND exam_id = $exam_id");
    $conn->query("DELETE FROM student_exam_sessions WHERE student_id = $student_id AND exam_id = $exam_id");

    $_SESSION['swal'] = ['type' => 'success', 'message' => 'Student session and attempts successfully reset.'];
    header("Location: reset_exam.php?exam_id=" . urlencode($exam_id));
    exit;
}

// Handle bulk reset
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reset_bulk'])) {
    $exam_id = (int) $_POST['exam_id'];
    if (!empty($_POST['selected_students'])) {
        foreach ($_POST['selected_students'] as $student_id) {
            $student_id = (int)$student_id;
            $conn->query("DELETE FROM student_exam_attempts WHERE student_id = $student_id AND exam_id = $exam_id");
            $conn->query("DELETE FROM student_exam_sessions WHERE student_id = $student_id AND exam_id = $exam_id");
        }
        $_SESSION['swal'] = ['type' => 'success', 'message' => 'Selected students reset successfully.'];
    } else {
        $_SESSION['swal'] = ['type' => 'warning', 'message' => 'No students selected for reset.'];
    }

    header("Location: reset_exam.php?exam_id=" . urlencode($exam_id));
    exit;
}

// Get selected exam_id
$exam_id = $_GET['exam_id'] ?? 0;

// Get list of exams
$exams = $conn->query("SELECT e.id, s.subjects, e.class, e.exam_type FROM exams e LEFT JOIN school_subjects s ON e.subject_id = s.id ORDER BY e.class, s.subjects, e.exam_type");

// Get students with either attempts or sessions
$students = null;
if ($exam_id) {
    $stmt = $conn->prepare("
        SELECT DISTINCT st.*
        FROM students st
        JOIN (
            SELECT student_id FROM student_exam_attempts WHERE exam_id = ?
            UNION
            SELECT student_id FROM student_exam_sessions WHERE exam_id = ?
        ) AS e ON st.id = e.student_id
        ORDER BY st.lastname, st.firstname
    ");
    $stmt->bind_param("ii", $exam_id, $exam_id);
    $stmt->execute();
    $students = $stmt->get_result();
    $stmt->close();
}
?>

<!-- Content Wrapper -->
<div class="content-wrapper">
  <div class="content-header">
    <div class="container-fluid">
      <h1 class="m-0">Students Exam Reset</h1>
    </div>
  </div>

  <div class="content">
    <div class="container-fluid">
      <form method="get" class="mb-4">
        <div class="row">
          <div class="col-md-6">
            <select name="exam_id" onchange="this.form.submit()" class="form-control">
              <option value="">-- Select Exam --</option>
              <?php while ($exam = $exams->fetch_assoc()):
                $value = $exam['id'];
                $label = $exam['class'] . ' - ' . $exam['subjects'] . ' - ' . $exam['exam_type'];
              ?>
                <option value="<?= $value ?>" <?= $exam_id == $value ? 'selected' : '' ?>><?= htmlspecialchars($label) ?></option>
              <?php endwhile; ?>
            </select>
          </div>
        </div>
      </form>

      <?php if ($exam_id && $students && $students->num_rows > 0): ?>
        <form method="post" id="bulkResetForm">
          <input type="hidden" name="exam_id" value="<?= $exam_id ?>">
          <table class="table table-bordered table-striped">
            <thead class="thead-dark">
              <tr>
                <th><input type="checkbox" onclick="toggleSelectAll(this)"></th>
                <th>#</th>
                <th>Passport</th>
                <th>Reg Number</th>
                <th>Full Name</th>
                <th>Reset</th>
              </tr>
            </thead>
            <tbody>
              <?php $sn = 1; while ($student = $students->fetch_assoc()): ?>
                <tr>
                  <td><input type="checkbox" name="selected_students[]" value="<?= $student['id'] ?>"></td>
                  <td><?= $sn++ ?></td>
                  <td>
                    <?php if (!empty($student['passport'])): ?>
                      <img src="../../<?= htmlspecialchars($student['passport']) ?>" alt="Passport" width="40">
                    <?php else: ?>
                      N/A
                    <?php endif; ?>
                  </td>
                  <td><?= htmlspecialchars($student['reg_number']) ?></td>
                  <td><?= htmlspecialchars($student['firstname'] . ' ' . $student['lastname']) ?></td>
                  <td>
                    <form method="post" class="d-inline reset-single-form">
                      <input type="hidden" name="student_id" value="<?= $student['id'] ?>">
                      <input type="hidden" name="exam_id" value="<?= $exam_id ?>">
                      <button type="submit" name="reset_single" class="btn btn-sm btn-danger">Reset</button>
                    </form>
                  </td>
                </tr>
              <?php endwhile; ?>
            </tbody>
          </table>
          <button type="button" onclick="confirmBulkReset()" class="btn btn-danger mt-2">Reset Selected</button>
          <input type="hidden" name="reset_bulk" value="1">
        </form>
      <?php elseif ($exam_id): ?>
        <div class="alert alert-warning">No students found for this exam.</div>
      <?php endif; ?>
    </div>
  </div>
</div>

<!-- SweetAlert -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
function toggleSelectAll(source) {
  const checkboxes = document.querySelectorAll('input[name="selected_students[]"]');
  checkboxes.forEach(cb => cb.checked = source.checked);
}

// Confirm bulk reset
function confirmBulkReset() {
  const selected = document.querySelectorAll('input[name="selected_students[]"]:checked');
  if (selected.length === 0) {
    Swal.fire('No selection', 'Please select at least one student.', 'warning');
    return;
  }

  Swal.fire({
    title: 'Reset Selected Students?',
    text: 'This will permanently remove their session and attempt records.',
    icon: 'warning',
    showCancelButton: true,
    confirmButtonText: 'Yes, reset them!',
  }).then((result) => {
    if (result.isConfirmed) {
      document.getElementById('bulkResetForm').submit();
    }
  });
}

// Confirm individual reset
document.querySelectorAll('.reset-single-form').forEach(form => {
  form.addEventListener('submit', function (e) {
    e.preventDefault();
    Swal.fire({
      title: 'Reset This Student?',
      text: 'This will permanently remove their session and attempt records.',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: 'Yes, reset!',
    }).then((result) => {
      if (result.isConfirmed) {
        form.submit();
      }
    });
  });
});
</script>

<?php
// Display Swal alert from session
if (isset($_SESSION['swal'])) {
    $type = $_SESSION['swal']['type'];
    $message = $_SESSION['swal']['message'];
    echo "<script>Swal.fire({ icon: '$type', text: '$message' });</script>";
    unset($_SESSION['swal']);
}
include('partials/footer.php');
?>
