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

use App\Core\{Auth,Controller,Csrf,Permission};
use App\Models\{ProfessorPro,ProfessorRemoteWork};

final class ProfessorRemoteWorkController extends Controller
{
    private function org():int{return (int)(Auth::user()['organisation_id']??1);}
    private function own():int{
        $q=\App\Core\Database::connection()->prepare("SELECT id FROM professeurs WHERE utilisateur_id=? AND organisation_id=? AND deleted_at IS NULL LIMIT 1");
        $q->execute([(int)Auth::id(),$this->org()]);return (int)$q->fetchColumn();
    }
    private function professor():int{
        $asked=(int)($_POST['professeur_id']??0);
        $token=trim((string)($_GET['professeur']??''));
        if($token!==''){
            $q=\App\Core\Database::connection()->prepare(
                "SELECT id FROM professeurs
                 WHERE public_token=? AND organisation_id=? AND deleted_at IS NULL LIMIT 1"
            );
            $q->execute([$token,$this->org()]);
            $asked=(int)$q->fetchColumn();
        }elseif($_SERVER['REQUEST_METHOD']==='GET' && isset($_GET['id'])){
            throw new \RuntimeException('Cette ancienne adresse n’est plus autorisée.');
        }
        if($asked>0&&Permission::canViewFullProfessorRh())return $asked;
        $own=$this->own();if($own>0)return $own;
        throw new \RuntimeException('Aucun professeur n’est rattaché à ce compte.');
    }
    private function url(int $id,string $month=''):string{
        $q=\App\Core\Database::connection()->prepare("SELECT public_token FROM professeurs WHERE id=? AND organisation_id=? AND deleted_at IS NULL LIMIT 1");
        $q->execute([$id,$this->org()]);$token=(string)$q->fetchColumn();
        return '/professeurs-pro/teletravail?professeur='.rawurlencode($token).($month!==''?'&mois='.rawurlencode($month):'');
    }
    private function month(int $id):string{return ProfessorRemoteWork::displayMonth($this->org(),$id,(string)($_GET['mois']??$_POST['mois']??''));}
    public function index():void{
        Auth::requireLogin();$id=$this->professor();$professor=ProfessorPro::find($id);$month=$this->month($id);
        $directionMode=(($_GET['mode']??'')==='direction')&&Permission::canViewFullProfessorRh();
        $this->view('professors_pro/remote_work',['pageTitle'=>'Télétravail','professor'=>$professor,'items'=>ProfessorRemoteWork::all($this->org(),$id,$month),'month'=>$month,'canManage'=>$directionMode]);
    }
    public function grant():void{
        Auth::requireLogin();Permission::require('professeurs.disciplines.manage');Csrf::verify($_POST['_csrf']??null);$id=(int)($_POST['professeur_id']??0);
        try{$count=ProfessorRemoteWork::grant($this->org(),$id,$_POST,(int)Auth::id());$_SESSION['success']=$count>1?$count.' plages annualisées hors vacances ont été ajoutées.':'La plage ponctuelle a été accordée.';}catch(\Throwable$e){$_SESSION['error']=$e->getMessage();}
        $fromPlanning=str_contains((string)($_SERVER['HTTP_REFERER']??''),'/professeurs-pro/planning');
        if($fromPlanning){
            $q=\App\Core\Database::connection()->prepare("SELECT public_token FROM professeurs WHERE id=? AND organisation_id=?");
            $q->execute([$id,$this->org()]);
            $this->redirect('/professeurs-pro/planning?professeur='.rawurlencode((string)$q->fetchColumn()).'&mode=direction');
        }
        $this->redirect($this->url($id).'&mode=direction');
    }
    public function requestChange():void{
        Auth::requireLogin();Permission::require('professeurs.disciplines.manage');Csrf::verify($_POST['_csrf']??null);$id=(int)($_POST['professeur_id']??0);
        try{$id=ProfessorRemoteWork::requestChange($this->org(),(int)($_POST['remote_work_id']??0),$_POST,(int)Auth::id());$_SESSION['success']='La modification du créneau a été envoyée au professeur pour validation.';}catch(\Throwable$e){$_SESSION['error']=$e->getMessage();}
        $this->redirect($this->url($id,(string)($_POST['mois']??'')).'&mode=direction');
    }
    public function decideChange():void{
        Auth::requireLogin();Csrf::verify($_POST['_csrf']??null);$id=$this->professor();
        try{ProfessorRemoteWork::decideChange($this->org(),$id,(int)($_POST['remote_work_id']??0),($_POST['decision']??'')==='accepter',(string)($_POST['commentaire']??''),(int)Auth::id());$_SESSION['success']='Votre décision sur la modification du créneau a été enregistrée.';}catch(\Throwable$e){$_SESSION['error']=$e->getMessage();}
        $this->redirect($this->url($id,(string)($_POST['mois']??'')));
    }
    public function submit():void{
        Auth::requireLogin();Csrf::verify($_POST['_csrf']??null);
        $adminTest=Permission::canViewFullProfessorRh()&&Permission::can('professeurs.disciplines.manage')&&($_POST['mode']??'')==='direction';
        $id=$adminTest?(int)($_POST['professeur_id']??0):$this->professor();
        try{ProfessorRemoteWork::submit($this->org(),$id,(int)($_POST['remote_work_id']??0),(string)($_POST['taches_effectuees']??''),$adminTest);$_SESSION['success']=$adminTest?'Le compte rendu de test a été enregistré et envoyé dans le circuit de validation.':'Le compte rendu a été envoyé à la Direction.';}catch(\Throwable$e){$_SESSION['error']=$e->getMessage();}
        $this->redirect($this->url($id,(string)($_POST['mois']??'')).($adminTest?'&mode=direction':''));
    }
    public function decide():void{
        Auth::requireLogin();Permission::require('professeurs.disciplines.manage');Csrf::verify($_POST['_csrf']??null);$id=(int)($_POST['professeur_id']??0);
        try{$id=ProfessorRemoteWork::decide($this->org(),(int)($_POST['remote_work_id']??0),($_POST['decision']??'')==='valider',(string)($_POST['commentaire']??''),(int)Auth::id());$_SESSION['success']='La décision de la Direction a été enregistrée.';}catch(\Throwable$e){$_SESSION['error']=$e->getMessage();}
        $this->redirect($this->url($id,(string)($_POST['mois']??'')).'&mode=direction');
    }
}
