<?php
// Enable all error reporting during development (turn off in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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'   => (int)$student_id,
                    'exam_id'      => (int)$exam_id,
                    'theory_score' => (float)$total
                ];
            }
        }

        if (empty($totals)) {
            $_SESSION['msg']  = "No valid totals calculated. Please check the score inputs.";
            $_SESSION['type'] = "warning";
        } else {
            // Start transaction
            $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 safely
                $exam_sql = $conn->prepare("SELECT exam_group_id, class, subject_id, term, session FROM exams WHERE id = ?");
                if (!$exam_sql) {
                    $_SESSION['msg'] = "DB prepare failed: " . $conn->error;
                    $_SESSION['type'] = "error";
                    $success = false;
                    break;
                }
                $exam_sql->bind_param("i", $exam_id);
                $exam_sql->execute();
                $exam_info_res = $exam_sql->get_result();
                $exam_info = $exam_info_res ? $exam_info_res->fetch_assoc() : null;
                $exam_sql->close();

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

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

                // Fetch subject name (defensive)
                $subject = '';
                if ($subject_id > 0) {
                    $subject_res = $conn->query("SELECT subjects FROM school_subjects WHERE id = " . $subject_id);
                    if ($subject_res) {
                        $subject_row = $subject_res->fetch_assoc();
                        $subject = $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 = ?");
                if (!$check) {
                    $_SESSION['msg'] = "DB prepare failed: " . $conn->error;
                    $_SESSION['type'] = "error";
                    $success = false;
                    break;
                }
                $check->bind_param("ii", $student_id, $group_id);
                $check->execute();
                $existing_res = $check->get_result();
                $existing = $existing_res ? $existing_res->fetch_assoc() : null;
                $check->close();

                $mcq_score = $existing ? (float)($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 - bind params must be variables (not array expressions)
                    $existing_id = (int)$existing['id'];
                    $update = $conn->prepare("UPDATE exam_group_results SET theory_score = ?, total = ?, status = ?, remarks = ? WHERE id = ?");
                    if (!$update) {
                        $_SESSION['msg'] = "DB prepare failed: " . $conn->error;
                        $_SESSION['type'] = "error";
                        $success = false;
                        break;
                    }
                    $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;
                    }
                    $update->close();
                } else {
                    // Insert new row
                    // types: student_id(i), class(s), term(s), session(s), subject(s), exam_group_id(i),
                    //        mcq_score(d), theory_score(d), total(d), status(s), remarks(s)
                    $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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                    if (!$insert) {
                        $_SESSION['msg'] = "DB prepare failed: " . $conn->error;
                        $_SESSION['type'] = "error";
                        $success = false;
                        break;
                    }

                    $types = "issssidddss"; // i s s s s i d d d s s
                    // ensure variable types are exactly those expected
                    $sid = (int)$student_id;
                    $cls = (string)$class;
                    $trm = (string)$term;
                    $sess = (string)$session;
                    $subj = (string)$subject;
                    $gid = (int)$group_id;
                    $mcq = (float)$mcq_score;
                    $th  = (float)$theory_score;
                    $tot = (float)$total_score;
                    $st  = (string)$status;
                    $rem = (string)$remarks;

                    $insert->bind_param(
                        $types,
                        $sid,
                        $cls,
                        $trm,
                        $sess,
                        $subj,
                        $gid,
                        $mcq,
                        $th,
                        $tot,
                        $st,
                        $rem
                    );

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

            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;
}

// Fetch dropdowns (defensive checks)
$classes_result = $conn->query("SELECT id, classes FROM classes");
if ($classes_result === false) {
    // handle/alert DB error or set an empty result
    $classes_result = new class {
        public function fetch_assoc(){ return null; }
    };
}
$sessions_result = $conn->query("SELECT DISTINCT session FROM exams ORDER BY session DESC");
if ($sessions_result === false) {
    $sessions_result = new class {
        public function fetch_assoc(){ return null; }
    };
}

$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 = "
   -- Step 1: subquery to get latest exam_group_result_id per student/exam_group
WITH latest AS (
    SELECT 
        student_id,
        exam_group_id,
        MAX(id) AS latest_id
    FROM exam_group_results
    GROUP BY student_id, exam_group_id
)

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 latest l ON ea.exam_group_result_id = l.latest_id
JOIN exam_group_results gr ON gr.id = l.latest_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()): ?>
                <?php if ($row === null) break; /* defensive */ ?>
                <option value="<?= htmlspecialchars($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="<?= htmlspecialchars($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()): ?>
                <?php if ($row === null) break; /* defensive */ ?>
                <option value="<?= htmlspecialchars($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>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
                    // Defensive defaults to avoid undefined index issues
                    $student_id = $row['student_id'] ?? 0;
                    $exam_id    = $row['exam_id'] ?? 0;
                    $question_id= $row['question_id'] ?? 0;
                    $key = "marks[{$student_id}][{$exam_id}][{$question_id}]";
                    $modalId = "answerModal_" . ++$modalCount;
                  ?>
                  <tr>
                    <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="<?= htmlspecialchars($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})`;
        examSelect.appendChild(option);
      });
    })
    .catch(err => {
      console.error('Error fetching exams', err);
    });
  }

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

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