<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Headers: Content-Type');

// Directory containing the template files
$templatesDir = __DIR__ . '/templates/';

// Check if templates directory exists
if (!is_dir($templatesDir)) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Templates directory not found'
    ]);
    exit;
}

try {
    // Get all JSON template files
    $templates = [];
    $files = scandir($templatesDir);
    
    foreach ($files as $file) {
        if (pathinfo($file, PATHINFO_EXTENSION) === 'json') {
            $templateName = pathinfo($file, PATHINFO_FILENAME);
            $filePath = $templatesDir . $file;
            
            // Read and decode the template file to get metadata
            $templateContent = file_get_contents($filePath);
            $templateData = json_decode($templateContent, true);
            
            if ($templateData !== null) {
                $templates[] = [
                    'name' => $templateName,
                    'display_name' => $templateData['display_name'] ?? $templateName,
                    'description' => $templateData['description'] ?? 'No description available',
                    'author' => $templateData['author'] ?? 'Unknown',
                    'version' => $templateData['version'] ?? '1.0',
                    'file_size' => filesize($filePath)
                ];
            }
        }
    }
    
    // Sort templates by display name
    usort($templates, function($a, $b) {
        return strcasecmp($a['display_name'], $b['display_name']);
    });
    
    echo json_encode([
        'success' => true,
        'count' => count($templates),
        'templates' => $templates
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Failed to list templates: ' . $e->getMessage()
    ]);
}
?>