<?php
use App\Core\Csrf;
$h=static fn($v)=>htmlspecialchars((string)$v,ENT_QUOTES,'UTF-8');
$monthNames=[1=>'Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'];
$eventsByDay=[];
foreach($events as $event)$eventsByDay[$event['date_evenement']][]=$event;
$months=[];
$cursor=(new DateTimeImmutable($year['date_debut']))->modify('first day of this month');
$last=(new DateTimeImmutable($year['date_fin']))->modify('first day of this month');
while($cursor<=$last){$months[]=$cursor;$cursor=$cursor->modify('+1 month');}
?>
<link rel="stylesheet" href="/public/assets/css/cda-professor-year-9653.css?v=9.6.89">
<link rel="stylesheet" href="/public/assets/css/cda-professor-year-9689.css?v=9.6.89">
<main class="yc">
 <a class="yc-back" href="/public/professeurs-pro/voir?id=<?=(int)$professor['id']?>">← Retour à la fiche professeur</a>
 <header class="yc-hero"><div><span>ANNÉE SCOLAIRE <?=$h($year['libelle'])?></span><h1>Calendrier de <?=$h($professor['prenom'].' '.$professor['nom'])?></h1><p>Les cours, réunions, rattrapages et plages de télétravail sont réunis dans ce calendrier.</p></div><form method="get"><input type="hidden" name="professeur_id" value="<?=(int)$professor['id']?>"><?php if($canManage):?><input type="hidden" name="mode" value="direction"><?php endif?><select name="annee_scolaire_id" onchange="this.form.submit()"><?php foreach($years as$y):?><option value="<?=$y['id']?>" <?=$y['id']==$year['id']?'selected':''?>><?=$h($y['libelle'])?></option><?php endforeach?></select></form></header>
 <section class="yc-stats"><article><b><?=number_format($plannedHours,2,',',' ')?> h</b><span>planifiées</span></article><article><b><?=number_format($workedHours,2,',',' ')?> h</b><span>réalisées</span></article><article><b><?=count($eventsByDay)?></b><span>jours travaillés</span></article></section>
 <?php if($canManage&&!$events):?><form method="post" action="/public/professeurs/annee/generer" class="yc-generate"><?=Csrf::field()?><input type="hidden" name="professeur_id" value="<?=$professor['id']?>"><input type="hidden" name="annee_scolaire_id" value="<?=$year['id']?>"><button>Générer le calendrier depuis le planning validé</button></form><?php endif?>
 <?php if($events):?><section class="yc-legend"><span><i class="course"></i>Cours</span><span><i class="remote-work"></i>Télétravail</span><span><i class="meeting"></i>Réunion / événement</span><span><i class="catchup"></i>Rattrapage</span><span><i class="pending"></i>Demande en attente</span></section><?php endif?>
 <section class="yc-months">
 <?php foreach($months as$month):
   $first=(int)$month->format('N');$days=(int)$month->format('t');?>
   <article class="yc-month">
    <h2><?=$monthNames[(int)$month->format('n')].' '.$month->format('Y')?></h2>
    <div class="yc-week"><span>L</span><span>M</span><span>M</span><span>J</span><span>V</span><span>S</span><span>D</span></div>
    <div class="yc-grid">
     <?php for($blank=1;$blank<$first;$blank++):?><span class="yc-blank"></span><?php endfor?>
     <?php for($day=1;$day<=$days;$day++):$date=$month->format('Y-m-').str_pad((string)$day,2,'0',STR_PAD_LEFT);$items=$eventsByDay[$date]??[];$types=array_column($items,'type_evenement');$kinds=[];if(in_array('cours',$types,true))$kinds[]='course';if(in_array('teletravail',$types,true))$kinds[]='remote-work';if(array_intersect($types,['reunion','evenement']))$kinds[]='meeting';if(in_array('rattrapage',$types,true))$kinds[]='catchup';?>
      <?php if($items):?><button type="button" class="yc-day <?=implode(' ',$kinds)?>" data-date="<?=$date?>" data-events="<?=$h(json_encode($items,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES))?>"><b><?=$day?></b><small><?=count($items)?> élément<?=count($items)>1?'s':''?></small></button><?php else:?><span class="yc-day off"><b><?=$day?></b></span><?php endif?>
     <?php endfor?>
    </div>
   </article>
 <?php endforeach?>
 <?php if(!$events):?><div class="yc-empty"><b>Calendrier annuel non généré</b><p>La Direction doit valider le planning prévisionnel. Le calendrier apparaîtra ensuite automatiquement.</p></div><?php endif?>
 </section>
 <?php if($requests):?><section class="yc-requests"><h2>Demandes de modification</h2><?php foreach($requests as$request):?><article><div><b><?=date('d/m/Y',strtotime($request['created_at']))?> · <?=$h(ucfirst($request['type_demande']))?></b><span><?=$h($request['motif'])?></span></div><em class="<?=$h($request['statut'])?>"><?=$h(str_replace('_',' ',$request['statut']))?></em><?php if($canManage&&$request['statut']==='en_attente'):?><form method="post" action="/public/professeurs/annee/decider"><?=Csrf::field()?><input type="hidden" name="request_id" value="<?=(int)$request['id']?>"><button name="decision" value="valider">Valider</button><button name="decision" value="refuser">Refuser</button></form><?php endif?></article><?php endforeach?></section><?php endif?>
</main>
<dialog id="yc-detail"><form method="dialog"><button class="close" aria-label="Fermer">×</button><h2></h2><div class="yc-detail-events"></div><footer><a class="attendance">Présences du jour</a><button>Fermer</button></footer></form></dialog>
<dialog id="yc-request"><form method="post" action="/public/professeurs/annee/demande"><?=Csrf::field()?><input type="hidden" name="professeur_id" value="<?=(int)$professor['id']?>"><input type="hidden" name="annee_scolaire_id" value="<?=(int)$year['id']?>"><input type="hidden" name="event_id"><header><h2>Demander une modification</h2><button type="button" data-close>×</button></header><p class="original"></p><label>Action<select name="type_demande"><option value="deplacement">Déplacer ce cours</option><option value="annulation">Annuler ce cours</option><option value="rattrapage">Prévoir un rattrapage</option></select></label><div class="yc-form-row"><label>Nouvelle date<input type="date" name="date_proposee"></label><label>Début<input type="time" name="heure_debut_proposee"></label><label>Fin<input type="time" name="heure_fin_proposee"></label></div><label>Motif<textarea name="motif" required></textarea></label><small>Le calendrier ne changera qu’après validation de la Direction.</small><button class="submit">Envoyer à la Direction</button></form></dialog>
<script>
const detail=document.querySelector('#yc-detail'),request=document.querySelector('#yc-request');
const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
document.querySelectorAll('.yc-day[data-events]').forEach(button=>button.addEventListener('click',()=>{
 const events=JSON.parse(button.dataset.events),date=button.dataset.date;
 detail.querySelector('h2').textContent=new Date(date+'T12:00:00').toLocaleDateString('fr-FR',{weekday:'long',day:'numeric',month:'long',year:'numeric'});
 detail.querySelector('.yc-detail-events').innerHTML=events.map((event,index)=>{
   const remote=event.type_evenement==='teletravail';
   const detailText=remote
     ? (event.taches_effectuees?'Compte rendu : '+esc(event.taches_effectuees):(event.consignes_direction?'Consignes : '+esc(event.consignes_direction):'Compte rendu à compléter'))
     : (event.students?.length?event.students.map(esc).join(', '):'Aucun élève affecté');
   const action=remote
     ? `<a class="yc-event-action" href="/public/professeurs-pro/teletravail?id=<?=(int)$professor['id']?><?=$canManage?'&mode=direction':''?>&mois=${encodeURIComponent(event.date_evenement.slice(0,7))}">Ouvrir le télétravail</a>`
     : `<button type="button" data-request="${index}">Demander un changement</button>`;
   return `<article class="${remote?'remote-work':''}"><div><b>${esc(event.discipline_libelle||event.type_evenement)}</b><span>${esc(event.heure_debut.slice(0,5))}–${esc(event.heure_fin.slice(0,5))}${event.salle_libelle?' · '+esc(event.salle_libelle):''}</span><small>${detailText}</small></div>${action}</article>`;
 }).join('');
 detail.querySelector('.attendance').href='/public/presences?professeur=<?=rawurlencode((string)$professor['public_token'])?>&date='+date;
 detail.querySelectorAll('[data-request]').forEach(change=>change.onclick=()=>{const event=events[Number(change.dataset.request)];request.querySelector('[name=event_id]').value=event.id;request.querySelector('[name=date_proposee]').value=event.date_evenement;request.querySelector('[name=heure_debut_proposee]').value=event.heure_debut.slice(0,5);request.querySelector('[name=heure_fin_proposee]').value=event.heure_fin.slice(0,5);request.querySelector('.original').textContent=(event.discipline_libelle||event.type_evenement)+' · '+event.date_evenement+' · '+event.heure_debut.slice(0,5)+'–'+event.heure_fin.slice(0,5);detail.close();request.showModal()});
 detail.showModal();
}));
request.querySelector('[data-close]').onclick=()=>request.close();
</script>
