<?php
declare(strict_types=1);
session_start();
require_once '../../config.php';
if (!isset($_SESSION['user_id'])) { http_response_code(401); echo json_encode(['success'=>false,'message'=>'Unauthorized']); exit; }
header('Content-Type: application/json');
$conn = getDBConnection();
if (!$conn instanceof mysqli) { echo json_encode(['success'=>false,'message'=>'Database connection failed']); exit; }
// Ensure the section-blueprint column exists (idempotent).
$conn->query("ALTER TABLE exam_papers ADD COLUMN IF NOT EXISTS section_config TEXT DEFAULT NULL");
$id = (int) ($_POST['id'] ?? 0);
$title = trim((string) ($_POST['title'] ?? ''));
$subjectId = (int) ($_POST['subject_id'] ?? 0);
$className = trim((string) ($_POST['class_name'] ?? ''));
$term = trim((string) ($_POST['term'] ?? ''));
$academicYear = trim((string) ($_POST['academic_year'] ?? ''));
$duration = max(1, (int) ($_POST['duration_minutes'] ?? 60));
$totalMarks = max(0, (int) ($_POST['total_marks'] ?? 0));
$instructions = trim((string) ($_POST['instructions'] ?? ''));
$status = trim((string) ($_POST['status'] ?? 'draft'));
// Section blueprint: validate it is a JSON object before storing.
$sectionDecoded = json_decode((string) ($_POST['section_config'] ?? ''), true);
$sectionConfig = is_array($sectionDecoded) ? json_encode($sectionDecoded, JSON_UNESCAPED_UNICODE) : null;
$userId = (int) $_SESSION['user_id'];
if ($title === '' || $className === '' || $term === '' || $academicYear === '') { echo json_encode(['success'=>false,'message'=>'Required fields missing']); exit; }
if ($id > 0) {
    $stmt = $conn->prepare("UPDATE exam_papers SET title=?, subject_id=?, class_name=?, term=?, academic_year=?, duration_minutes=?, total_marks=?, instructions=?, section_config=?, status=? WHERE id=?");
    $stmt->bind_param('sisssiisssi', $title, $subjectId, $className, $term, $academicYear, $duration, $totalMarks, $instructions, $sectionConfig, $status, $id);
    $stmt->execute();
    $stmt->close();
} else {
    $stmt = $conn->prepare("INSERT INTO exam_papers (title, subject_id, class_name, term, academic_year, duration_minutes, total_marks, instructions, section_config, status, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param('sisssiisssi', $title, $subjectId, $className, $term, $academicYear, $duration, $totalMarks, $instructions, $sectionConfig, $status, $userId);
    $stmt->execute();
    $id = $conn->insert_id;
    $stmt->close();
}
echo json_encode(['success'=>true,'message'=>'Paper saved successfully','paper_id'=>$id]);
