<?php
/**
 * Script para listar proyectos generados
 */

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

$response = [
    'success' => false,
    'projects' => [],
    'message' => ''
];

try {
    $baseDir = dirname(__DIR__);
    $projectsDir = dirname($baseDir) . '/crono-projects';
    
    if (!file_exists($projectsDir)) {
        $response['success'] = true;
        $response['message'] = 'No hay proyectos aún';
        echo json_encode($response);
        exit;
    }
    
    $projects = [];
    $dirs = scandir($projectsDir);
    
    foreach ($dirs as $dir) {
        if ($dir === '.' || $dir === '..') {
            continue;
        }
        
        $projectPath = $projectsDir . '/' . $dir;
        
        if (!is_dir($projectPath)) {
            continue;
        }
        
        // Leer metadata del proyecto
        $metadataPath = $projectPath . '/project-metadata.json';
        
        if (file_exists($metadataPath)) {
            $metadata = json_decode(file_get_contents($metadataPath), true);
            
            $projects[] = [
                'slug' => $dir,
                'name' => $metadata['name'] ?? $dir,
                'date' => $metadata['date'] ?? '',
                'distances' => $metadata['distances'] ?? [],
                'created' => isset($metadata['created']) ? date('d/m/Y', strtotime($metadata['created'])) : 'Desconocido',
                'url' => '../crono-projects/' . $dir . '/index.html'
            ];
        } else {
            // Si no hay metadata, crear entrada básica
            $projects[] = [
                'slug' => $dir,
                'name' => ucfirst(str_replace('-', ' ', $dir)),
                'date' => '',
                'distances' => [],
                'created' => date('d/m/Y', filemtime($projectPath)),
                'url' => '../crono-projects/' . $dir . '/index.html'
            ];
        }
    }
    
    // Ordenar por fecha de creación (más reciente primero)
    usort($projects, function($a, $b) {
        return strcmp($b['created'], $a['created']);
    });
    
    $response['success'] = true;
    $response['projects'] = $projects;
    
} catch (Exception $e) {
    $response['message'] = $e->getMessage();
}

echo json_encode($response);
?>
