<?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');
include('partials/alert.php');

$classes_result = $conn->query("SELECT id, classes FROM classes");
$terms = ['First Term', 'Second Term', 'Third Term'];
$sessions_result = $conn->query("SELECT DISTINCT session FROM exam_group_results ORDER BY session DESC");
$subjects_result = $conn->query("SELECT id, subjects FROM school_subjects");

// ✅ Added assignment1 and assignment2
$exam_types = ['assignment1', 'assignment2', 'ca1', 'ca2', 'exam'];

$filter_class = $_GET['class'] ?? '';
$filter_term = $_GET['term'] ?? '';
$filter_session = $_GET['session'] ?? '';
$filter_subject = $_GET['subject_id'] ?? '';
$filter_exam_type = $_GET['exam_type'] ?? '';

$where = [];
if (!empty($filter_class)) $where[] = "r.class = '" . $conn->real_escape_string($filter_class) . "'";
if (!empty($filter_term)) $where[] = "r.term = '" . $conn->real_escape_string($filter_term) . "'";
if (!empty($filter_session)) $where[] = "r.session = '" . $conn->real_escape_string($filter_session) . "'";
if (!empty($filter_subject)) $where[] = "r.subject = (SELECT subjects FROM school_subjects WHERE id = '" . $conn->real_escape_string($filter_subject) . "')";
if (!empty($filter_exam_type)) $where[] = "r.exam_type = '" . $conn->real_escape_string($filter_exam_type) . "'";
$where_sql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

$sql = "
    SELECT 
        r.*, 
        s.firstname, s.lastname, s.othername, s.reg_number, s.class AS student_class
    FROM exam_group_results r
    JOIN students s ON r.student_id = s.id
    $where_sql
    ORDER BY r.student_id DESC
";
$results = $conn->query($sql);
?>

<div class="content-wrapper">
  <div class="content-header">
    <div class="container-fluid">
      <h1 class="m-0">Student Exam Results</h1>
    </div>
  </div>
    
  <div class="content">
    <div class="container-fluid">
      <form method="get" class="mb-3">
        <div class="row g-3">
          <div class="col-md-3">
            <label for="class">Class</label>
            <select name="class" id="class" class="form-control">
              <option value="">-- All Classes --</option>
              <?php while ($row = $classes_result->fetch_assoc()): ?>
                <option value="<?= $row['classes'] ?>" <?= ($row['classes'] == $filter_class) ? 'selected' : '' ?>>
                  <?= htmlspecialchars($row['classes']) ?>
                </option>
              <?php endwhile; ?>
            </select>
          </div>

          <div class="col-md-3">
            <label for="term">Term</label>
            <select name="term" id="term" class="form-control">
              <option value="">-- All Terms --</option>
              <?php foreach ($terms as $term): ?>
                <option value="<?= $term ?>" <?= ($term == $filter_term) ? 'selected' : '' ?>>
                  <?= htmlspecialchars($term) ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="col-md-3">
            <label for="session">Session</label>
            <select name="session" id="session" class="form-control">
              <option value="">-- All Sessions --</option>
              <?php while ($row = $sessions_result->fetch_assoc()): ?>
                <option value="<?= $row['session'] ?>" <?= ($row['session'] == $filter_session) ? 'selected' : '' ?>>
                  <?= htmlspecialchars($row['session']) ?>
                </option>
              <?php endwhile; ?>
            </select>
          </div>

          <div class="col-md-3">
            <label for="subject_id">Subject</label>
            <select name="subject_id" id="subject_id" class="form-control">
              <option value="">-- All Subjects --</option>
              <?php while ($row = $subjects_result->fetch_assoc()): ?>
                <option value="<?= $row['id'] ?>" <?= ($row['id'] == $filter_subject) ? 'selected' : '' ?>>
                  <?= htmlspecialchars($row['subjects']) ?>
                </option>
              <?php endwhile; ?>
            </select>
          </div>

          <div class="col-md-3">
            <label for="exam_type">Exam Type</label>
            <select name="exam_type" id="exam_type" class="form-control">
              <option value="">-- All Exam Types --</option>
              <?php
                // ✅ Display readable labels
                $labels = [
                    'assignment1' => 'Assignment 1',
                    'assignment2' => 'Assignment 2',
                    'ca1' => 'CA 1',
                    'ca2' => 'CA 2',
                    'exam' => 'Exam'
                ];
              ?>
              <?php foreach ($exam_types as $exam_type): ?>
                <option value="<?= $exam_type ?>" <?= ($exam_type == $filter_exam_type) ? 'selected' : '' ?>>
                  <?= htmlspecialchars($labels[$exam_type] ?? strtoupper($exam_type)) ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>
        </div>

        <div class="row mt-3 align-items-center">
          <div class="col-md-6">
            <button type="submit" class="btn btn-primary">Filter</button>
          </div> 
          <div class="mb-3">
            <a href="export_results_excel.php?<?= http_build_query($_GET) ?>" class="btn btn-success">
              <i class="fa fa-file-excel"></i> Export to Excel
            </a>
            <a href="export_results_pdf.php?<?= http_build_query($_GET) ?>" class="btn btn-danger">
              <i class="fa fa-file-pdf"></i> Print to PDF
            </a> 
          </div>  

          <div class="col-md-6 text-end">
            <?php if ($results && $results->num_rows > 0): ?>
    <button type="button"
        class="btn btn-warning me-2"
        id="gradeAllBtn"
        data-class="<?= htmlspecialchars($filter_class) ?>"
        data-term="<?= htmlspecialchars($filter_term) ?>"
        data-session="<?= htmlspecialchars($filter_session) ?>"
        data-subject="<?= htmlspecialchars($filter_subject) ?>"
        data-exam-type="<?= htmlspecialchars($filter_exam_type) ?>"
    >
        <i class="fa fa-check-circle"></i> Grade All Pending
    </button>
<?php endif; ?>

            <?php if (!empty($filter_class) || !empty($filter_term) || !empty($filter_session) || !empty($filter_subject) || !empty($filter_exam_type)): ?>
              <button type="button"
                class="btn btn-success float-end"
                id="migrateBtn"
                data-class="<?= htmlspecialchars($filter_class) ?>"
                data-term="<?= htmlspecialchars($filter_term) ?>"
                data-session="<?= htmlspecialchars($filter_session) ?>"
                data-subject="<?= htmlspecialchars($filter_subject) ?>"
                data-exam-type="<?= htmlspecialchars($filter_exam_type) ?>">
                <i class="fa fa-database"></i> Migrate Results
              </button>
            <?php endif; ?>
          </div>
        </div>
      </form>

      <?php if (!empty($_GET['class']) || !empty($_GET['term']) || !empty($_GET['session']) || !empty($_GET['subject_id']) || !empty($_GET['exam_type'])): ?>
        <?php if ($results && $results->num_rows > 0): ?>
          <h4>Student Exam Results</h4>
          <div class="table-responsive">
            <table class="table table-bordered table-striped" id="mytable">
              <thead class="table-light">
                <tr>
                  <th>Student</th>
                  <th>Reg. Number</th>
                  <th>Class</th>
                  <th>Subject</th>
                  <th>Term</th>
                  <th>Session</th>
                  <th>Exam Type</th>
                  <th>OBJ</th>
                  <th>Theory</th>
                  <th>Total</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
                <?php while ($row = $results->fetch_assoc()): ?>
                  <?php $name = $row['lastname'] . ' ' . $row['firstname'] . ' ' . $row['othername']; ?>
                  <tr>
                    <td><?= htmlspecialchars($name) ?></td>
                    <td><?= htmlspecialchars($row['reg_number']) ?></td>
                    <td><?= htmlspecialchars($row['student_class']) ?></td>
                    <td><?= htmlspecialchars($row['subject']) ?></td>
                    <td><?= htmlspecialchars($row['term']) ?></td>
                    <td><?= htmlspecialchars($row['session']) ?></td>
                    <td><?= htmlspecialchars($labels[$row['exam_type']] ?? strtoupper($row['exam_type'] ?? '-')) ?></td>
                    <td><?= htmlspecialchars($row['mcq_score'] ?? 0) ?></td>
                    <td><?= htmlspecialchars($row['theory_score'] ?? 0) ?></td>
                    <td><?= htmlspecialchars($row['total'] ?? 0) ?></td>
                    <td><?= htmlspecialchars($row['status'] ?? '-') ?></td>
                  </tr>
                <?php endwhile; ?>
              </tbody>
            </table>
          </div>
        <?php else: ?>
          <div class="alert alert-warning text-center">No exam results found for the selected filters.</div>
        <?php endif; ?>
      <?php endif; ?>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
  const migrateBtn = document.getElementById('migrateBtn');

  if (migrateBtn) {
    migrateBtn.addEventListener('click', function () {
      const cls = this.dataset.class;
      const term = this.dataset.term;
      const session = this.dataset.session;
      const subject = this.dataset.subject;
      const examType = this.dataset.examType;

      Swal.fire({
        title: 'Confirm Migration',
        text: 'Are you sure you want to migrate these results? This action cannot be undone.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, Migrate',
        cancelButtonText: 'Cancel',
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33'
      }).then((result) => {
        if (result.isConfirmed) {
          const url = `migrate_results.php?class=${encodeURIComponent(cls)}&term=${encodeURIComponent(term)}&session=${encodeURIComponent(session)}&subject_id=${encodeURIComponent(subject)}&exam_type=${encodeURIComponent(examType)}`;
          window.location.href = url;
        }
      });
    });
  }
});
</script>
<script>
document.addEventListener("DOMContentLoaded", function () {

    const gradeAllBtn = document.getElementById("gradeAllBtn");
    if (!gradeAllBtn) return;

    gradeAllBtn.addEventListener("click", function () {
        const cls = this.dataset.class || '';
        const term = this.dataset.term || '';
        const session = this.dataset.session || '';
        const subject = this.dataset.subject || '';
        const examType = this.dataset.examType || '';

        if (!cls || !term || !session || !subject || !examType) {
            Swal.fire("Missing Filters", "Please select all filters.", "warning");
            return;
        }

        Swal.fire({
            title: "Grade All Pending?",
            text: "This will compute total = mcq_score for all pending results.",
            icon: "warning",
            showCancelButton: true,
            confirmButtonText: "Yes, Grade All",
            showLoaderOnConfirm: true,
            preConfirm: () => {
                return fetch("grade_all_mcq.php", {
                    method: "POST",
                    headers: { "Content-Type": "application/x-www-form-urlencoded" },
                    body: new URLSearchParams({
                        class: cls,
                        term: term,
                        session: session,
                        subject: subject,
                        exam_type: examType
                    })
                })
                .then(async (response) => {
                    const text = (await response.text()).trim();
                    return { ok: response.ok, status: response.status, text };
                })
                .catch(err => ({ ok: false, status: 0, text: String(err) }));
            },
            allowOutsideClick: () => !Swal.isLoading()
        }).then((result) => {

            if (!result.isConfirmed) return;

            const res = result.value;
            console.log("Server Response:", res);

            // ✅ SUCCESS CHECK
            if (res.ok && res.text.startsWith("success|")) {

                let rows = 0;
                const parts = res.text.split("|");
                if (parts[1] && parts[1].startsWith("graded_rows=")) {
                    rows = parseInt(parts[1].replace("graded_rows=", "")) || 0;
                }

                Swal.fire({
                    icon: "success",
                    title: "Grading Completed",
                    text: `Successfully graded ${rows} result(s).`
                }).then(() => location.reload());

            } else {
                // ❌ ERROR HANDLER
                Swal.fire({
                    icon: "error",
                    title: "Error",
                    html: `<b>Status:</b> ${res.status}<br><b>Message:</b><br>${res.text}`
                });
            }

        });
    });
});
</script>




<?php include('partials/footer.php'); ?>
