<?php
namespace App\Models;
use App\Core\Database;use RuntimeException;
final class Enrollment {
 private static function table(string $t): bool { $s=Database::connection()->prepare("SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=:t");$s->execute(['t'=>$t]);return (int)$s->fetchColumn()>0; }
 private static function col(string $t,string $c): bool { $s=Database::connection()->prepare("SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=:t AND COLUMN_NAME=:c");$s->execute(['t'=>$t,'c'=>$c]);return (int)$s->fetchColumn()>0; }
 private static function source(): ?string { foreach(['membres','membres_famille','family_members','client_membres'] as $t) if(self::table($t)&&self::col($t,'id')&&self::col($t,'nom')&&self::col($t,'prenom')) return $t; return null; }
 public static function member(int $id): ?array { $t=self::source(); if(!$t)return null; $s=Database::connection()->prepare("SELECT id,nom,prenom".(self::col($t,'date_naissance')?",date_naissance":"")." FROM `$t` WHERE id=:id LIMIT 1");$s->execute(['id'=>$id]);$r=$s->fetch(); if($r)$r['source_table']=$t; return $r?:null; }
 public static function workshops(): array { return Database::connection()->query("SELECT a.id,a.code,a.libelle,COALESCE(p.code,'') pole_code,COALESCE(p.libelle,'') pole_libelle FROM ateliers a LEFT JOIN disciplines d ON d.id=a.discipline_id LEFT JOIN poles p ON p.id=d.pole_id WHERE 1=1".(self::col('ateliers','deleted_at')?" AND a.deleted_at IS NULL":"").(self::col('ateliers','actif')?" AND a.actif=1":"")." ORDER BY p.libelle,a.libelle")->fetchAll(); }
 public static function groups(int $atelierId): array { $s=Database::connection()->prepare("SELECT g.id,g.code,g.libelle,g.capacite_max,COUNT(gp.id) nb_participants FROM groupes_cours g LEFT JOIN groupe_participants gp ON gp.groupe_id=g.id AND gp.deleted_at IS NULL AND gp.statut='actif' WHERE g.atelier_id=:a".(self::col('groupes_cours','deleted_at')?" AND g.deleted_at IS NULL":"")." GROUP BY g.id,g.code,g.libelle,g.capacite_max ORDER BY g.libelle");$s->execute(['a'=>$atelierId]);return $s->fetchAll(); }
 public static function create(int $memberId,int $atelierId,?int $groupId,array $d,int $userId): int { $m=self::member($memberId); if(!$m)throw new RuntimeException('Membre introuvable.'); $s=Database::connection()->prepare("SELECT a.*,COALESCE(p.code,'') pole_code FROM ateliers a LEFT JOIN disciplines di ON di.id=a.discipline_id LEFT JOIN poles p ON p.id=di.pole_id WHERE a.id=:id LIMIT 1");$s->execute(['id'=>$atelierId]);$a=$s->fetch(); if(!$a)throw new RuntimeException('Atelier introuvable.'); if(in_array(strtoupper((string)$a['pole_code']),['MUS','MUSIQUE'],true)&&(int)($d['eligibility_ce1']??0)!==1)throw new RuntimeException('Le niveau CE1 minimum doit être confirmé pour la musique.'); $pdo=Database::connection();$pdo->beginTransaction(); try { $pdo->prepare("INSERT INTO inscriptions_cours(organisation_id,atelier_id,participant_source,participant_id,date_inscription,date_debut,date_fin,statut,eligibility_ce1,observations,created_by) VALUES(:o,:a,:s,:p,CURRENT_DATE,:dd,:df,'validee',:ce1,:obs,:u)")->execute(['o'=>$d['organisation_id']??1,'a'=>$atelierId,'s'=>$m['source_table'],'p'=>$memberId,'dd'=>$d['date_debut']?:date('Y-m-d'),'df'=>$d['date_fin']?:null,'ce1'=>$d['eligibility_ce1']===''?null:(int)$d['eligibility_ce1'],'obs'=>trim((string)$d['observations'])?:null,'u'=>$userId?:null]); $id=(int)$pdo->lastInsertId(); if($groupId) GroupParticipant::assign($groupId,$id,['date_entree'=>$d['date_debut']?:date('Y-m-d'),'statut'=>'actif','heure_debut'=>$d['heure_debut']??'','heure_fin'=>$d['heure_fin']??'','observations'=>$d['observations']??''],$userId,false); $pdo->commit(); return $id; } catch(\Throwable $e){$pdo->rollBack();throw $e;} }
}
