<?php
namespace App\Models;
use App\Core\Database;
final class ProfessorContract{
 public static function professor(int $id):?array{$s=Database::connection()->prepare("SELECT id,code_professeur,nom,prenom FROM professeurs WHERE id=:id AND deleted_at IS NULL LIMIT 1");$s->execute(['id'=>$id]);return $s->fetch()?:null;}
 public static function forProfessor(int $id,bool $includeArchived=false):array{$where=$includeArchived?'':" AND c.deleted_at IS NULL AND c.statut<>'archive'";$s=Database::connection()->prepare("SELECT c.*,t.code type_code,t.libelle type_libelle,t.icone type_icone,t.couleur type_couleur,COALESCE(c.compte_anciennete_override,t.compte_anciennete) compte_anciennete_effectif FROM contrats_professeurs c JOIN types_contrats_professeurs t ON t.id=c.type_contrat_id WHERE c.professeur_id=:id".$where." ORDER BY (c.statut='archive' OR c.deleted_at IS NOT NULL),c.date_debut DESC,c.id DESC");$s->execute(['id'=>$id]);return $s->fetchAll();}
 public static function canViewArchived(int $userId):bool{$s=Database::connection()->prepare("SELECT COUNT(*) FROM utilisateur_roles ur INNER JOIN roles r ON r.id=ur.role_id AND r.actif=1 AND r.deleted_at IS NULL WHERE ur.utilisateur_id=:id AND (LOWER(REPLACE(REPLACE(r.code,'-','_'),' ', '_')) IN ('direction','administration','administrateur','administrateurs','admin','super_admin','superadmin') OR LOWER(r.libelle) IN ('direction','administration','administrateur','administrateurs','admin','super administrateur','super admin','super-admin'))");$s->execute(['id'=>$userId]);return (int)$s->fetchColumn()>0;}
 public static function find(int $id):?array{$s=Database::connection()->prepare("SELECT * FROM contrats_professeurs WHERE id=:id AND deleted_at IS NULL LIMIT 1");$s->execute(['id'=>$id]);return $s->fetch()?:null;}
 public static function save(array $d,?int $id=null):void{
  if($id){
   $update=$d;
   // professeur_id et created_by ne figurent pas dans la requête UPDATE.
   // PDO refuse les paramètres nommés supplémentaires lorsque les requêtes
   // préparées natives sont actives (HY093).
   unset($update['professeur_id'],$update['created_by']);
   $update['id']=$id;
   Database::connection()->prepare("UPDATE contrats_professeurs SET type_contrat_id=:type_contrat_id,numero_contrat=:numero_contrat,date_debut=:date_debut,date_fin=:date_fin,fonction=:fonction,volume_heures=:volume_heures,unite_heures=:unite_heures,contrat_principal=:contrat_principal,compte_anciennete_override=:compte_anciennete_override,statut=:statut,observations=:observations WHERE id=:id")->execute($update);
   self::refreshFutureCalendar((int)$d['professeur_id']);
   return;
  }
  Database::connection()->prepare("INSERT INTO contrats_professeurs(professeur_id,type_contrat_id,numero_contrat,date_debut,date_fin,fonction,volume_heures,unite_heures,contrat_principal,compte_anciennete_override,statut,observations,created_by) VALUES(:professeur_id,:type_contrat_id,:numero_contrat,:date_debut,:date_fin,:fonction,:volume_heures,:unite_heures,:contrat_principal,:compte_anciennete_override,:statut,:observations,:created_by)")->execute($d);
  self::refreshFutureCalendar((int)$d['professeur_id']);
 }
 private static function refreshFutureCalendar(int $professorId):void{
  $pdo=Database::connection();$q=$pdo->prepare("SELECT p.organisation_id,y.id FROM professeurs p JOIN annees_scolaires y ON y.organisation_id=p.organisation_id AND y.active=1 WHERE p.id=? LIMIT 1");$q->execute([$professorId]);$row=$q->fetch();
  if(!$row)return;
  $slots=$pdo->prepare("SELECT COUNT(*) FROM cda_professor_slots WHERE professeur_id=? AND annee_scolaire_id=? AND statut='valide' AND deleted_at IS NULL");$slots->execute([$professorId,(int)$row['id']]);
  if((int)$slots->fetchColumn()>0)ProfessorYear::generate((int)$row['organisation_id'],$professorId,(int)$row['id'],0);
 }
 public static function archive(int $id):void{$contract=self::find($id);Database::connection()->prepare("UPDATE contrats_professeurs SET statut='archive',deleted_at=CURRENT_TIMESTAMP WHERE id=:id")->execute(['id'=>$id]);if($contract)self::refreshFutureCalendar((int)$contract['professeur_id']);}
}
