<?php

declare(strict_types=1);

session_start();

require_once '../../config.php';

require_once __DIR__ . '/../helpers.php';

if (!isset($_SESSION['user_id'])) { http_response_code(401); echo json_encode(['success' => false]); exit; }

header('Content-Type: application/json');

$conn     = getDBConnection();

$paperId  = (int) ($_POST['paper_id']   ?? 0);

$qId      = (int) ($_POST['question_id'] ?? 0);

$marks    = max(1, (int) ($_POST['marks'] ?? 1));

if (!$conn instanceof mysqli || $paperId <= 0 || $qId <= 0) {

    echo json_encode(['success' => false, 'message' => 'Invalid request']);

    exit;

}

$stmt = $conn->prepare(

    "UPDATE exam_paper_questions SET marks = ? WHERE paper_id = ? AND question_id = ?"

);

$stmt->bind_param('iii', $marks, $paperId, $qId);

$stmt->execute();

$stmt->close();

examsUpdatePaperTotalMarks($conn, $paperId);

$res   = $conn->query("SELECT total_marks FROM exam_papers WHERE id = {$paperId} LIMIT 1");

$total = $res ? (int) ($res->fetch_assoc()['total_marks'] ?? 0) : 0;

echo json_encode(['success' => true, 'total_marks' => $total]);

