<?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();
if (!$conn instanceof mysqli) { echo json_encode([]); exit; }
$className = trim((string) ($_POST['class_name'] ?? ''));
$term = trim((string) ($_POST['term'] ?? ''));
$academicYear = trim((string) ($_POST['academic_year'] ?? ''));
$status = trim((string) ($_POST['status'] ?? ''));
$paperId = (int) ($_POST['id'] ?? 0);
$sql = "SELECT ep.*, s.subject_name, COUNT(epq.id) AS question_count
        FROM exam_papers ep
        LEFT JOIN subjects s ON ep.subject_id = s.id
        LEFT JOIN exam_paper_questions epq ON ep.id = epq.paper_id
        WHERE 1=1";
$types = '';
$params = [];
foreach ([['ep.id',$paperId > 0 ? (string) $paperId : ''],['ep.class_name',$className],['ep.term',$term],['ep.academic_year',$academicYear],['ep.status',$status]] as [$field,$value]) {
    if ($value !== '') { $sql .= " AND {$field} = ?"; $types .= 's'; $params[] = $value; }
}
$sql .= " GROUP BY ep.id ORDER BY ep.created_at DESC";
$stmt = $conn->prepare($sql);
if ($types !== '') { $stmt->bind_param($types, ...$params); }
$stmt->execute();
$result = $stmt->get_result();
$rows = [];
while ($row = $result->fetch_assoc()) { $rows[] = $row; }
$stmt->close();
echo json_encode($rows);
