<?php
declare(strict_types=1);
session_start();
require_once '../../config.php';
if (!isset($_SESSION['user_id'])) { http_response_code(401); echo json_encode([]); exit; }
header('Content-Type: application/json');
$conn = getDBConnection();
$paperId = (int) ($_POST['paper_id'] ?? 0);
if (!$conn instanceof mysqli || $paperId <= 0) { echo json_encode([]); exit; }
$stmt = $conn->prepare("SELECT epq.*, eq.question, eq.question_type, eq.difficulty, eq.ai_generated,
                               CASE
                                   WHEN eq.ai_generated = 1 THEN 'AI'
                                   WHEN eq.created_by IS NULL THEN 'Imported'
                                   ELSE 'Manual'
                               END AS source,
                               s.subject_name
                        FROM exam_paper_questions epq
                        INNER JOIN exam_questions eq ON epq.question_id = eq.id
                        LEFT JOIN subjects s ON eq.subject_id = s.id
                        WHERE epq.paper_id = ?
                        ORDER BY epq.order_no ASC, epq.id ASC");
$stmt->bind_param('i', $paperId);
$stmt->execute();
$result = $stmt->get_result();
$rows = [];
while ($row = $result->fetch_assoc()) { $rows[] = $row; }
$stmt->close();
echo json_encode($rows);
