<?php
/**
 * Return the active exam paper templates (system + this school's custom ones).
 */
declare(strict_types=1);
session_start();
require_once '../../config.php';
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$conn = getDBConnection();
if (!$conn instanceof mysqli) {
    echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    exit;
}

// Tolerate environments where the migration has not run yet.
$tableExists = $conn->query("SHOW TABLES LIKE 'exam_paper_templates'");
if (!$tableExists || $tableExists->num_rows === 0) {
    echo json_encode(['success' => true, 'templates' => []]);
    exit;
}

$templates = [];
$res = $conn->query(
    "SELECT id, name, description, level, structure, is_system
       FROM exam_paper_templates
      WHERE is_active = 1
      ORDER BY is_system DESC, name"
);
if ($res) {
    while ($row = $res->fetch_assoc()) {
        $structure = json_decode((string) $row['structure'], true);
        $templates[] = [
            'id'          => (int) $row['id'],
            'name'        => $row['name'],
            'description' => $row['description'],
            'level'       => $row['level'],
            'is_system'   => (int) $row['is_system'],
            'structure'   => is_array($structure) ? $structure : [],
        ];
    }
}

echo json_encode(['success' => true, 'templates' => $templates]);
