<?php
declare(strict_types=1);
namespace App\Controllers;

use App\Core\{Auth,Controller,Csrf,Permission};
use App\Models\{DirectionTask,ProfessorPlanningEvent};

final class DirectionPlanningController extends Controller
{
    private function org():int{return (int)(Auth::user()['organisation_id']??1);}
    private function requireDirection():void
    {
        Auth::requireLogin();
        if(!Permission::canViewFullProfessorRh()||!Permission::can('professeurs.disciplines.manage')){
            http_response_code(403);exit('Accès réservé à la Direction.');
        }
    }
    public function tasks():void
    {
        $this->requireDirection();
        $this->view('direction/tasks',[
            'pageTitle'=>'Tâches à valider',
            'tasks'=>DirectionTask::all($this->org())
        ]);
    }
    public function meetings():void
    {
        $this->requireDirection();
        ProfessorPlanningEvent::ensureStorage();
        $this->view('direction/meetings',[
            'pageTitle'=>'Réunions des professeurs',
            'professors'=>ProfessorPlanningEvent::activeProfessors($this->org()),
            'meetings'=>ProfessorPlanningEvent::meetingsForDirection($this->org())
        ]);
    }
    public function createMeeting():void
    {
        $this->requireDirection();Csrf::verify($_POST['_csrf']??null);
        $ids=array_values(array_filter(array_map('intval',(array)($_POST['professeur_ids']??[]))));
        try{
            ProfessorPlanningEvent::createMeeting($this->org(),$ids,$_POST,(int)Auth::id());
            $_SESSION['success']='La réunion a été ajoutée aux plannings des professeurs invités.';
        }catch(\Throwable $e){$_SESSION['error']=$e->getMessage();}
        $this->redirect('/direction/reunions');
    }
    public function addMeetingGuests():void
    {
        $this->requireDirection();Csrf::verify($_POST['_csrf']??null);
        $token=strtolower(trim((string)($_POST['reunion']??'')));
        $ids=array_values(array_filter(array_map('intval',(array)($_POST['professeur_ids']??[]))));
        try{
            $count=ProfessorPlanningEvent::addGuests($this->org(),$token,$ids,(int)Auth::id());
            $_SESSION['success']=$count>0
                ?$count.' professeur'.($count>1?'s ont':' a').' été ajouté'.($count>1?'s':'').' à la réunion et au planning annuel.'
                :'Tous les professeurs sélectionnés étaient déjà invités.';
        }catch(\Throwable $e){$_SESSION['error']=$e->getMessage();}
        $this->redirect('/direction/reunions');
    }
}
