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

$baseDir = __DIR__;
$templateDir = $baseDir . '/templates/';
$response = ['success' => false, 'data' => null, 'message' => 'An unknown error occurred.'];

// Get filename from GET or POST (adjust as needed)
$filename = null;
if (isset($_GET['filename'])) {
    $filename = $_GET['filename'];
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
     $input = json_decode(file_get_contents('php://input'), true);
     if (isset($input['filename'])) {
         $filename = $input['filename'];
     }
}


if ($filename !== null) {
    // --- Security: Sanitize filename ---
    $filename = preg_replace('/[^A-Za-z0-9 _\-\.]/', '', basename(str_replace(['/', '\\'], '', $filename)));
    // --- End Security ---

    $filePath = $templateDir . $filename;

    if (empty($filename)) {
         $response['message'] = 'Error: No filename provided.';
    } elseif (strtolower(substr($filename, -5)) !== '.json') {
         $response['message'] = 'Error: Invalid file type requested.';
    } elseif (file_exists($filePath) && is_readable($filePath)) {
        $jsonData = file_get_contents($filePath);
        $decoded = $jsonData !== false && strlen($jsonData) <= 2 * 1024 * 1024 ? json_decode($jsonData) : null;
        if ($jsonData !== false && strlen($jsonData) <= 2 * 1024 * 1024 && ($decoded !== null || trim($jsonData) === 'null') && json_last_error() === JSON_ERROR_NONE) {
            $response['success'] = true;
            $response['data'] = $jsonData; // Send raw JSON string back
            $response['message'] = 'Template loaded.';
        } else {
             $response['message'] = 'Error: Could not read template file.';
             // error_log("Failed to read file $filePath");
        }
    } else {
         $response['message'] = 'Error: Template file not found or not readable.';
         // error_log("File not found or not readable: $filePath");
    }
} else {
    $response['message'] = 'Error: No filename specified.';
}

echo json_encode($response);
?>
