<?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);
$results = json_decode((string) ($_POST['results'] ?? '[]'), true);
if (!$conn instanceof mysqli || $paperId <= 0 || !is_array($results)) { echo json_encode(['success'=>false,'saved_count'=>0,'errors'=>['Invalid payload']]); exit; }
$saved = 0;
$errors = [];
$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)");
foreach ($results as $index => $row) {
    $studentId = (int) ($row['student_id'] ?? 0);
    $scoreRaw = $row['score'] ?? null;
    $remarks = trim((string) ($row['remarks'] ?? ''));
    if ($studentId <= 0) { $errors[] = "Row " . ($index + 1) . ": invalid student"; continue; }
    $score = ($scoreRaw === '' || $scoreRaw === null) ? null : (float) $scoreRaw;
    $grade = $score === null ? null : examsGetGrade($conn, $score);
    $stmt->bind_param('iidssi', $paperId, $studentId, $score, $grade, $remarks, $markedBy);
    if ($stmt->execute()) { $saved++; } else { $errors[] = "Row " . ($index + 1) . ': ' . $stmt->error; }
}
$stmt->close();
echo json_encode(['success'=>true,'saved_count'=>$saved,'errors'=>$errors]);
