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

header('Content-Type: text/plain; charset=utf-8');

// Auth check
if (!isset($_SESSION['staff_id'])) {
    http_response_code(403);
    echo "Unauthorized: no staff session.";
    exit;
}

// Collect POST safely
$class     = $_POST['class'] ?? '';
$term      = $_POST['term'] ?? '';
$session   = $_POST['session'] ?? '';
$subject   = $_POST['subject'] ?? '';    // this may be subject_id or subject_name
$exam_type = $_POST['exam_type'] ?? '';

// Basic validation
if ($class === '' || $term === '' || $session === '' || $subject === '' || $exam_type === '') {
    http_response_code(400);
    echo "Missing required filter(s). Received: "
        . "class=" . ($class === '' ? '[empty]' : $class) . ", "
        . "term=" . ($term === '' ? '[empty]' : $term) . ", "
        . "session=" . ($session === '' ? '[empty]' : $session) . ", "
        . "subject=" . ($subject === '' ? '[empty]' : $subject) . ", "
        . "exam_type=" . ($exam_type === '' ? '[empty]' : $exam_type);
    exit;
}

// Try to detect if subject is an ID (all digits) or a name
$subject_name = '';
if (ctype_digit((string)$subject)) {
    // subject is an id
    $sid = (int)$subject;
    $sstmt = $conn->prepare("SELECT subjects FROM school_subjects WHERE id = ?");
    $sstmt->bind_param("i", $sid);
    $sstmt->execute();
    $sr = $sstmt->get_result()->fetch_assoc();
    $sstmt->close();
    if (!$sr) {
        http_response_code(400);
        echo "Invalid subject id: $sid";
        exit;
    }
    $subject_name = $sr['subjects'];
} else {
    // treat subject as name directly
    $subject_name = $subject;
}

// Now perform the safe update: only rows with status = 'pending'
$update_sql = "
    UPDATE exam_group_results
    SET total = mcq_score,
        status = 'graded'
    WHERE class = ?
      AND term = ?
      AND session = ?
      AND subject = ?
      AND exam_type = ?
      AND status = 'pending'
";

$upd = $conn->prepare($update_sql);
if (!$upd) {
    http_response_code(500);
    echo "Prepare failed: " . $conn->error;
    exit;
}

$upd->bind_param("sssss", $class, $term, $session, $subject_name, $exam_type);

if (!$upd->execute()) {
    http_response_code(500);
    echo "Execute failed: " . $upd->error;
    $upd->close();
    exit;
}

$affected = $upd->affected_rows;
$upd->close();

echo "success|graded_rows=" . (int)$affected;
exit;
