<?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);
$questionId = (int) ($_POST['question_id'] ?? 0);
$marks = max(1, (int) ($_POST['marks'] ?? 1));
if (!$conn instanceof mysqli || $paperId <= 0 || $questionId <= 0) { echo json_encode(['success'=>false,'message'=>'Invalid request']); exit; }
$orderRes = $conn->prepare("SELECT COALESCE(MAX(order_no),0)+1 AS next_order FROM exam_paper_questions WHERE paper_id = ?");
$orderRes->bind_param('i', $paperId);
$orderRes->execute();
$nextRes = $orderRes->get_result();
$next = 1;
if ($row = $nextRes->fetch_assoc()) { $next = (int) $row['next_order']; }
$orderRes->close();
$stmt = $conn->prepare("INSERT IGNORE INTO exam_paper_questions (paper_id, question_id, marks, order_no) VALUES (?, ?, ?, ?)");
$stmt->bind_param('iiii', $paperId, $questionId, $marks, $next);
$stmt->execute();
$stmt->close();
examsUpdatePaperTotalMarks($conn, $paperId);
echo json_encode(['success'=>true,'message'=>'Question added to paper']);
