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

require_once 'config.php';

try {
    // Récupérer toutes les formations
    $stmt = $pdo->query("
        SELECT f.*, 
               (SELECT COUNT(*) FROM formation_matiere fm WHERE fm.id_formation = f.id_formation) as nb_matieres
        FROM formation f 
        ORDER BY f.id_formation DESC
    ");
    $formations = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Ajouter les détails des matières pour chaque formation
    foreach ($formations as &$formation) {
        $stmt2 = $pdo->prepare("
            SELECT m.* 
            FROM matieres m
            JOIN formation_matiere fm ON m.id_matiere = fm.id_matiere
            WHERE fm.id_formation = ?
            LIMIT 5
        ");
        $stmt2->execute([$formation['id_formation']]);
        $formation['matieres_apercu'] = $stmt2->fetchAll(PDO::FETCH_ASSOC);
    }
    
    echo json_encode([
        'success' => true,
        'formations' => $formations
    ]);
    
} catch(PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Erreur: ' . $e->getMessage()
    ]);
}
?>