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

$baseDir = __DIR__;
$templateDir = $baseDir . '/templates/';
$templates = [];
$response = ['success' => false, 'templates' => [], 'message' => ''];

if (is_dir($templateDir)) {
    // Scan the directory
    $files = scandir($templateDir);
    if ($files !== false) {
        foreach ($files as $file) {
            // Check if it's a file and ends with .json
            if (is_file($templateDir . $file) && strtolower(pathinfo($file, PATHINFO_EXTENSION)) === 'json') {
                $templates[] = $file;
            }
        }
        natcasesort($templates);
        $response['success'] = true;
        $response['templates'] = $templates;
    } else {
        $response['message'] = 'Error: Could not scan templates directory.';
        // error_log("Failed to scan directory $templateDir");
    }
} else {
    $response['message'] = 'Error: Templates directory not found.';
    // error_log("Templates directory not found at $templateDir");
}

echo json_encode($response);
?>
