<?php
declare(strict_types=1);

require_once __DIR__ . '/../../system/bootstrap.php';

header('Content-Type: application/json');

try {
    $stmt = $pdo->query("
        SELECT version, json_schema, created_at
        FROM md_templates
        WHERE active = 1
        ORDER BY created_at DESC
        LIMIT 1
    ");

    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        http_response_code(204);
        exit;
    }

    $template = json_decode($row['json_schema'], true, 512, JSON_THROW_ON_ERROR);

    echo json_encode([
        'meta' => [
            'version' => $row['version'],
            'created_at' => $row['created_at']
        ],
        'template' => $template
    ], JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);

} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode([
        'error' => 'Failed to load active template'
    ]);
}
