<?php
header('Content-Type: application/json; charset=UTF-8');
$root = rtrim((string)($_SERVER['DOCUMENT_ROOT'] ?? ''), '/\\');
if ($root === '' || !file_exists($root . '/config.php')) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Tenant configuration could not be loaded.']);
    exit;
}
require_once $root . '/config.php';
$filename = preg_replace('/[^A-Za-z0-9 _\-.]/', '', basename((string)($_REQUEST['filename'] ?? '')));
$templateDir = $root . '/images/lev_templates/';
$path = $templateDir . $filename;
if (!preg_match('/\.json$/i', $filename) || !is_file($path) || filesize($path) > 2 * 1024 * 1024) {
    http_response_code(404);
    echo json_encode(['success' => false, 'message' => 'Template not found.']);
    exit;
}
$data = file_get_contents($path);
json_decode((string)$data);
if ($data === false || json_last_error() !== JSON_ERROR_NONE) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Template is invalid.']);
    exit;
}
echo json_encode(['success' => true, 'data' => $data, 'templateUrl' => rtrim(TENANT_URL, '/') . '/images/lev_templates/' . rawurlencode($filename)]);
