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

require_once 'config.php';

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($id <= 0) {
    echo json_encode(['success' => false, 'message' => 'ID invalide']);
    exit();
}

try {
    $stmt = $pdo->prepare("
        SELECT f.*, GROUP_CONCAT(DISTINCT m.nom_matiere SEPARATOR ', ') as matieres
        FROM formation f
        LEFT JOIN formation_matiere fm ON f.id_formation = fm.id_formation
        LEFT JOIN matieres m ON fm.id_matiere = m.id_matiere
        WHERE f.id_formation = ?
        GROUP BY f.id_formation
    ");
    $stmt->execute([$id]);
    $formation = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($formation) {
        echo json_encode(['success' => true, 'formation' => $formation]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Formation non trouvée']);
    }
} catch(PDOException $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>