<?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);
$studentId = (int) ($_POST['student_id'] ?? 0);
$scoreRaw = $_POST['score'] ?? null;
$remarks = trim((string) ($_POST['remarks'] ?? ''));
if (!$conn instanceof mysqli || $paperId <= 0 || $studentId <= 0) { echo json_encode(['success'=>false,'message'=>'Invalid request']); exit; }
$score = ($scoreRaw === '' || $scoreRaw === null) ? null : (float) $scoreRaw;
$grade = $score === null ? null : examsGetGrade($conn, $score);
$markedBy = (int) $_SESSION['user_id'];
$stmt = $conn->prepare("INSERT INTO exam_results (paper_id, student_id, score, grade, remarks, marked_by)
                        VALUES (?, ?, ?, ?, ?, ?)
                        ON DUPLICATE KEY UPDATE score=VALUES(score), grade=VALUES(grade), remarks=VALUES(remarks), marked_by=VALUES(marked_by)");
$stmt->bind_param('iidssi', $paperId, $studentId, $score, $grade, $remarks, $markedBy);
$stmt->execute();
$stmt->close();
echo json_encode(['success'=>true,'message'=>'Result saved','grade'=>$grade]);
