<?php
/**
 * AEEMCI — API de suivi du Congrès (centre de gestion).
 *
 * Lecture seule : inscrits (membres + partenaires) et mandataires désignés
 * par les organes. Protégé par la clé d'accès partagée du socle.
 *
 *   GET congres.php?action=liste
 *   → { success, data: { inscriptions: [...], mandataires: [...], montant_unitaire } }
 */

declare(strict_types=1);

require __DIR__ . '/_socle.php';

$pdo    = bd($config);
$action = (string) param('action', 'liste');

if ($action !== 'liste') {
    echec("Action inconnue : « $action ».", 404);
}

$inscriptions = $pdo->query(
    "SELECT id, reference, type_inscrit, matricule, nom, prenom, contact,
            TRIM(secretariat) AS secretariat, TRIM(sous_comite) AS sous_comite, TRIM(section) AS section,
            structure, mandat, montant, statut_paiement, paye_le, created_at,
            (sms_envoye_le IS NOT NULL) AS sms_envoye
       FROM congres_inscriptions
      ORDER BY COALESCE(paye_le, created_at) DESC, id DESC"
)->fetchAll();

$mandataires = $pdo->query(
    "SELECT m.id, m.niveau, m.organe_id, m.matricule, m.nom_complet, m.created_at,
            o.nom AS organe,
            CASE m.niveau WHEN 'SECRETARIAT' THEN o.nom WHEN 'SOUS_COMITE' THEN p.nom ELSE g.nom END AS secretariat,
            CASE m.niveau WHEN 'SECRETARIAT' THEN NULL WHEN 'SOUS_COMITE' THEN o.nom ELSE p.nom END AS sous_comite,
            CASE m.niveau WHEN 'SECTION' THEN o.nom ELSE NULL END AS section,
            i.reference, i.statut_paiement, i.paye_le
       FROM congres_mandataires m
       LEFT JOIN congres_organes o  ON o.id = m.organe_id
       LEFT JOIN congres_organes p  ON p.id = o.parent_id
       LEFT JOIN congres_organes g  ON g.id = p.parent_id
       LEFT JOIN congres_inscriptions i  ON i.matricule = m.matricule
      ORDER BY secretariat, sous_comite, section, m.id"
)->fetchAll();

foreach ($inscriptions as &$r) {
    $r['id'] = (int) $r['id'];
    $r['montant'] = (int) $r['montant'];
    $r['sms_envoye'] = (bool) $r['sms_envoye'];
}
unset($r);

succes([
    'inscriptions' => $inscriptions,
    'mandataires'  => $mandataires,
]);
