<?php
// T07: display_errors removed for production safety
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);
?>

<?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');

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['mark_all_submit'])) {
    if (isset($_POST['marks']) && is_array($_POST['marks'])) {
        $totals = [];

        foreach ($_POST['marks'] as $student_id => $exams) {
            foreach ($exams as $exam_id => $questions) {
                $total = 0;
                foreach ($questions as $question_id => $score) {
                    if (!is_numeric($score)) continue;
                    $total += (float)$score;
                }

                $totals[] = [
                    'student_id'   => $student_id,
                    'exam_id'      => $exam_id,
                    'theory_score' => $total
                ];
            }
        }

        if (empty($totals)) {
            $_SESSION['msg']  = "No valid totals calculated. Please check the score inputs.";
            $_SESSION['type'] = "warning";
        } else {
            $conn->begin_transaction();
            $success = true;

            foreach ($totals as $entry) {
                $student_id   = $entry['student_id'];
                $exam_id      = $entry['exam_id'];
                $theory_score = $entry['theory_score'];

                // Get exam_group info
                $exam_sql = $conn->prepare("SELECT exam_group_id, class, subject_id, term, session FROM exams WHERE id = ?");
                $exam_sql->bind_param("i", $exam_id);
                $exam_sql->execute();
                $exam_info = $exam_sql->get_result()->fetch_assoc();
                $exam_sql->close();

                if (!$exam_info) {
                    $_SESSION['msg'] = "Exam ID $exam_id not found.";
                    $_SESSION['type'] = "error";
                    $success = false;
                    break;
                }

                $group_id   = $exam_info['exam_group_id'];
                $class      = $exam_info['class'];
                $subject_id = $exam_info['subject_id'];
                $term       = $exam_info['term'];
                $session    = $exam_info['session'];

                $subject_res = $conn->query("SELECT subjects FROM school_subjects WHERE id = $subject_id");
                $subject_row = $subject_res ? $subject_res->fetch_assoc() : null;
                $subject     = $subject_row ? $subject_row['subjects'] : '';

                // Check for existing exam_group_result
                $check = $conn->prepare("SELECT id, mcq_score FROM exam_group_results WHERE student_id = ? AND exam_group_id = ?");
                $check->bind_param("ii", $student_id, $group_id);
                $check->execute();
                $existing = $check->get_result()->fetch_assoc();
                $check->close();

                $mcq_score = $existing ? ($existing['mcq_score'] ?? 0.0) : 0.0;
                $total_score = $mcq_score + $theory_score;
                $status  = 'graded';
                $remarks = 'Manually marked by examiner';

                if ($existing) {
                    // Update existing row
                    $update = $conn->prepare("UPDATE exam_group_results SET theory_score = ?, total = ?, status = ?, remarks = ? WHERE id = ?");
                    $update->bind_param("ddssi", $theory_score, $total_score, $status, $remarks, $existing['id']);
                    if (!$update->execute()) {
                        $_SESSION['msg'] = "Update failed for student ID $student_id: " . $update->error;
                        $_SESSION['type'] = "error";
                        $success = false;
                        break;
                    }
                } else {
                    // Insert new row
                    $insert = $conn->prepare("INSERT INTO exam_group_results (student_id, class, term, session, subject, exam_group_id, mcq_score, theory_score, total, status, remarks) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                    $insert->bind_param(
                        "isssssdddss",
                        $student_id,
                        $class,
                        $term,
                        $session,
                        $subject,
                        $group_id,
                        $mcq_score,
                        $theory_score,
                        $total_score,
                        $status,
                        $remarks
                    );

                    if (!$insert->execute()) {
                        $_SESSION['msg'] = "Insert failed for student ID $student_id: " . $insert->error;
                        $_SESSION['type'] = "error";
                        $success = false;
                        break;
                    }
                }
            }

            if ($success) {
                $conn->commit();
                $_SESSION['msg']  = "All scores saved and updated.<br />Waiting for Migration!";
                $_SESSION['type'] = "success";
            } else {
                $conn->rollback();
                if (!isset($_SESSION['msg'])) {
                    $_SESSION['msg']  = "No changes were saved.";
                    $_SESSION['type'] = "error";
                }
            }
        }
    } else {
        $_SESSION['msg']  = "No marks submitted.";
        $_SESSION['type'] = "error";
    }

    // Redirect to prevent resubmission
    header("Location: " . $_SERVER['PHP_SELF'] . '?' . http_build_query($_GET));
    exit;
}
?>

<?php
// Fetch dropdowns
$classes_result = $conn->query("SELECT id, classes FROM classes");
$sessions_result = $conn->query("SELECT DISTINCT session FROM exams ORDER BY session DESC");
$terms = ['First Term', 'Second Term', 'Third Term'];

$filter_class = $_GET['class'] ?? '';
$filter_term = $_GET['term'] ?? '';
$filter_session = $_GET['session'] ?? '';
$filter_exam_id = $_GET['exam_id'] ?? '';

$where = [];
if (!empty($filter_class)) $where[] = "s.class = '" . $conn->real_escape_string($filter_class) . "'";
if (!empty($filter_term)) $where[] = "e.term = '" . $conn->real_escape_string($filter_term) . "'";
if (!empty($filter_session)) $where[] = "e.session = '" . $conn->real_escape_string($filter_session) . "'";
if (!empty($filter_exam_id)) $where[] = "e.id = '" . intval($filter_exam_id) . "'";
$where_sql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

// Fetch answers
$sql = "
    SELECT 
        ea.exam_group_result_id,
        ea.student_id,
        ea.answer_text,
        q.id AS question_id,
        q.question_text,
        q.question_image,
        q.marks AS max_marks,
        s.firstname,
        s.lastname,
        s.reg_number,
        s.class AS student_class,
        e.id AS exam_id,
        e.exam_type AS exam_title,
        e.term,
        e.session
    FROM exam_answers ea
    JOIN exam_group_results gr ON ea.exam_group_result_id = gr.id
    JOIN exams e ON e.exam_group_id = gr.exam_group_id AND e.exam_type IN ('ca1', 'ca2', 'exam')
    JOIN questions q ON ea.question_id = q.id
    JOIN students s ON ea.student_id = s.id
    $where_sql
    ORDER BY ea.exam_group_result_id, q.id
";

$results = $conn->query($sql);
?>

<div class="content-wrapper">
  <div class="content-header">
    <div class="container-fluid">
      <h1 class="m-0">Theory Answer Reviews</h1>
    </div>
  </div>

  <div class="content">
    <div class="container-fluid">
      <!-- Filter Form -->
      <form method="get" class="mb-4">
        <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="exam_id">Exam</label>
			  <select name="exam_id" id="exam_id" class="form-control">
				<option value="">-- Select Exam --</option>
				<!-- Will be populated via AJAX -->
			  </select>
			</div>
        </div>
        <div class="row mt-3">
          <div class="col-md-3">
            <button type="submit" class="btn btn-primary">Apply Filter</button>
          </div>
        </div>
      </form>

      <?php if (!empty($_GET['class']) || !empty($_GET['term']) || !empty($_GET['session']) || !empty($_GET['exam_id'])): ?>
  <?php if ($results && $results->num_rows > 0): ?>
        <form method="POST">
          <input type="hidden" name="mark_all_submit" value="1">
          <table class="table table-bordered table-striped">
              <thead>
                <tr>
                  <!-- <th>Student</th> --> <!-- Hidden -->
                  <th>Reg No.</th>
                  <th>Class</th>
                  <th>Exam Title</th>
                  <th>Term</th>
                  <th>Session</th>
                  <th>Question</th>
                  <th>Answer</th>
                  <th>Mark</th>
                </tr>
              </thead>
              <tbody>
                <?php $modalCount = 0; ?>
                <?php while ($row = $results->fetch_assoc()): ?>
                  <?php
                    $key = "marks[{$row['student_id']}][{$row['exam_id']}][{$row['question_id']}]";
                    $modalId = "answerModal_" . ++$modalCount;
                  ?>
                  <tr>
                    <!-- <td><?= htmlspecialchars($row['lastname'] . ' ' . $row['firstname']) ?></td> -->
                    <td><?= htmlspecialchars($row['reg_number']) ?></td>
                    <td><?= htmlspecialchars($row['student_class']) ?></td>
                    <td><?= htmlspecialchars($row['exam_title']) ?></td>
                    <td><?= htmlspecialchars($row['term']) ?></td>
                    <td><?= htmlspecialchars($row['session']) ?></td>
                    <td><?= nl2br(htmlspecialchars($row['question_text'])) ?></td>
                    <td>
                      <button type="button" class="btn btn-sm btn-primary" data-toggle="modal" data-target="#<?= $modalId ?>">
                        View
                      </button>
            
                      <!-- Modal -->
                      <div class="modal fade" id="<?= $modalId ?>" tabindex="-1" role="dialog" aria-labelledby="modalLabel_<?= $modalId ?>" aria-hidden="true">
                        <div class="modal-dialog modal-lg modal-dialog-scrollable" role="document">
                          <div class="modal-content">
                            <div class="modal-header">
                              <h5 class="modal-title" id="modalLabel_<?= $modalId ?>">Student Answer</h5>
                              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                              </button>
                            </div>
                            <div class="modal-body">
                              <?= nl2br(htmlspecialchars($row['answer_text'])) ?>
                            </div>
                          </div>
                        </div>
                      </div>
                    </td>
                    <td>
                      <input type="number" name="<?= $key ?>" class="form-control" value="0" min="0" max="<?= $row['max_marks'] ?>">
                    </td>
                  </tr>
                <?php endwhile; ?>
              </tbody>
            </table>
          <button type="submit" class="btn btn-success">Mark All & Submit</button>
        </form>
      <?php else: ?>
        <div class="alert alert-warning text-center">No answers found for selected filters.</div>
      <?php endif; ?>
      <?php endif; ?>
    </div>
  </div>
</div>

<script>
document.addEventListener("DOMContentLoaded", function () {
  function fetchExams() {
    const cls = document.getElementById("class").value;
    const term = document.getElementById("term").value;
    const session = document.getElementById("session").value;

    fetch("fetch_exams.php", {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: `class=${encodeURIComponent(cls)}&term=${encodeURIComponent(term)}&session=${encodeURIComponent(session)}`
    })
    .then(res => res.json())
    .then(data => {
      const examSelect = document.getElementById("exam_id");
      examSelect.innerHTML = '<option value="">-- Select Exam --</option>';
      data.forEach(exam => {
        const option = document.createElement("option");
        option.value = exam.id;
        option.textContent = `${exam.subject_name} (${exam.exam_type})`; // Use exam_type instead of title
        examSelect.appendChild(option);
      });
    });
  }

  document.getElementById("class").addEventListener("change", fetchExams);
  document.getElementById("term").addEventListener("change", fetchExams);
  document.getElementById("session").addEventListener("change", fetchExams);
});
</script>

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

