<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Core\{Auth,Controller,Csrf,Permission};
use App\Models\ProfessorYear;

final class ProfessorYearController extends Controller
{
    private function org():int{return (int)(Auth::user()['organisation_id']??1);}
    private function directionMode():bool{
        return ($_GET['mode']??$_POST['mode']??'')==='direction'
            && Permission::canViewFullProfessorRh()
            && Permission::can('professeurs.disciplines.manage');
    }
    private function professor():int{
        $own=ProfessorYear::professorForUser((int)Auth::id());
        $asked=(int)($_GET['professeur_id']??$_POST['professeur_id']??0);
        if($asked&&$this->directionMode())return $asked;
        if($own)return $own;
        $preview=(int)($_SESSION['pedagogical_professor_id']??0);
        if(Permission::canViewFullProfessorRh()&&$preview>0&&(!$asked||$asked===$preview))return $preview;
        throw new \RuntimeException('Aucun professeur n’est rattaché à ce compte.');
    }
    public function index():void{
        Auth::requireLogin();$id=$this->professor();$years=ProfessorYear::years($this->org());
        $yearId=(int)($_GET['annee_scolaire_id']??($years[0]['id']??0));
        $this->view('professor_year/index',[
            'pageTitle'=>'Planning annuel',
            'years'=>$years,
            'canManage'=>$this->directionMode(),
            'hideNavigation'=>false,
        ]+ProfessorYear::data($this->org(),$id,$yearId));
    }
    public function generate():void{Auth::requireLogin();Permission::require('professeurs.disciplines.manage');Csrf::verify($_POST['_csrf']??null);$id=$this->professor();try{$n=ProfessorYear::generate($this->org(),$id,(int)$_POST['annee_scolaire_id'],(int)Auth::id());$_SESSION['success']=$n.' journée(s) de cours générée(s), hors vacances scolaires de zone B.';}catch(\Throwable$e){$_SESSION['error']=$e->getMessage();}$this->redirect('/professeurs/annee?professeur_id='.$id.'&annee_scolaire_id='.(int)$_POST['annee_scolaire_id']);}
    public function request():void{Auth::requireLogin();Csrf::verify($_POST['_csrf']??null);$id=$this->professor();ProfessorYear::requestChange($this->org(),$id,$_POST,(int)Auth::id());$_SESSION['success']='Demande transmise à la Direction. Le planning reste inchangé jusqu’à validation.';$this->redirect('/professeurs/annee?annee_scolaire_id='.(int)$_POST['annee_scolaire_id']);}
    public function decide():void{Auth::requireLogin();Permission::require('professeurs.disciplines.manage');Csrf::verify($_POST['_csrf']??null);ProfessorYear::decide((int)$_POST['request_id'],($_POST['decision']??'')==='valider',(int)Auth::id());$_SESSION['success']='La demande a été traitée.';$this->redirect($_SERVER['HTTP_REFERER']??'/professeurs-pro');}
}
