<?php
namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Csrf;
use App\Core\Permission;
use App\Core\PortalSimulation;
use App\Models\ProfessorPro;

final class ProfessorProController extends Controller
{
    private function organisationId(): int
    {
        return (int)(Auth::user()['organisation_id'] ?? 1);
    }

    private function ownProfessorId(): int
    {
        $stmt=\App\Core\Database::connection()->prepare(
            "SELECT id FROM professeurs
             WHERE utilisateur_id=? AND organisation_id=? AND deleted_at IS NULL
             LIMIT 1"
        );
        $stmt->execute([(int)Auth::id(),$this->organisationId()]);
        return (int)$stmt->fetchColumn();
    }

    private function pedagogicalProfessorId(): int
    {
        $own=$this->ownProfessorId();
        if($own>0) return $own;
        if (Permission::isSuperAdmin()) {
            $simulated = PortalSimulation::professorId();
            if ($simulated !== null) return $simulated;
            $_SESSION['error'] = 'Choisissez d’abord un professeur actif à tester.';
            $this->redirect('/espaces?espace=professeur');
            return 0;
        }
        $token=trim((string)($_GET['professeur'] ?? ''));
        $asked=0;
        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->organisationId()]);
            $asked=(int)$q->fetchColumn();
        }
        if($asked>0 && Permission::canViewFullProfessorRh()){
            $_SESSION['pedagogical_professor_id']=$asked;
            return $asked;
        }
        $preview=(int)($_SESSION['pedagogical_professor_id'] ?? 0);
        if($preview>0 && Permission::canViewFullProfessorRh()) return $preview;
        $_SESSION['error'] = 'L’espace Prof n’est pas disponible : aucun professeur actif n’est rattaché à ce compte.';
        unset($_SESSION['axiom_space'], $_SESSION['pedagogical_professor_id']);
        $this->redirect('/espaces');
        return 0;
    }

    public function index(): void
    {
        Auth::requireLogin();
        $id = $this->pedagogicalProfessorId();
        if ($id <= 0) {
            return;
        }
        $professor=ProfessorPro::find($id);
        $this->redirect('/professeurs-pro/voir?professeur='.rawurlencode((string)$professor['public_token']));
    }

    public function show(): void
    {
        Auth::requireLogin();
        $id=$this->pedagogicalProfessorId();
        if ($id <= 0) {
            return;
        }
        $professor=ProfessorPro::find($id);

        if(!$professor){
            http_response_code(404);
            exit('Professeur introuvable.');
        }

        $this->view('professors_pro/show',[
            'pageTitle'=>'Mon profil pédagogique',
            'professor'=>$professor,
            'disciplines'=>ProfessorPro::disciplines($id),
            'planning'=>\App\Models\DisciplinePlanning::professorData($this->organisationId(),$id),
        ]);
    }

    public function rhIndex(): void
    {
        Auth::requireLogin();
        if(!Permission::canViewFullProfessorRh()){http_response_code(403);exit('Accès RH refusé.');}
        $this->view('professors_pro/index',['pageTitle'=>'Dossiers RH professeurs','professors'=>ProfessorPro::all()]);
    }

    public function rhShow(): void
    {
        Auth::requireLogin();
        if(!Permission::canViewFullProfessorRh()){http_response_code(403);exit('Accès RH refusé.');}
        $id=(int)($_GET['id'] ?? 0);$professor=ProfessorPro::find($id);
        if(!$professor){http_response_code(404);exit('Professeur introuvable.');}
        $this->view('professors_pro/rh_show',[
            'pageTitle'=>'Dossier RH professeur','professor'=>$professor,
            'disciplines'=>ProfessorPro::disciplines($id),
            'contracts'=>ProfessorPro::contracts($id),'alerts'=>ProfessorPro::alerts($id),
        ]);
    }

    public function disciplines(): void
    {
        Auth::requireLogin();
        if($this->ownProfessorId()>0){
            http_response_code(403);
            exit('Un professeur ne peut pas ajouter, modifier ou retirer ses disciplines.');
        }
        Permission::require('professeurs.disciplines.manage');
        if(!Permission::canViewFullProfessorRh()){http_response_code(403);exit('Seule la Direction ou le service RH peut gérer les disciplines d’un professeur.');}

        $id=(int)($_GET['id'] ?? 0);
        $professor=ProfessorPro::find($id);

        if(!$professor){
            http_response_code(404);
            exit('Professeur introuvable.');
        }

        $selected=array_map(
            static fn(array $row): int => (int)$row['id'],
            ProfessorPro::disciplines($id)
        );

        $main=null;

        foreach(ProfessorPro::disciplines($id) as $row){
            if(!empty($row['principale'])){
                $main=(int)$row['id'];
                break;
            }
        }

        $this->view('professors_pro/disciplines',[
            'pageTitle'=>'Disciplines du professeur',
            'professor'=>$professor,
            'available'=>ProfessorPro::availableDisciplines(),
            'selected'=>$selected,
            'main'=>$main,
        ]);
    }

    public function saveDisciplines(): void
    {
        Auth::requireLogin();
        if($this->ownProfessorId()>0){
            http_response_code(403);
            exit('Un professeur ne peut pas ajouter, modifier ou retirer ses disciplines.');
        }
        Permission::require('professeurs.disciplines.manage');
        if(!Permission::canViewFullProfessorRh()){http_response_code(403);exit('Seule la Direction ou le service RH peut gérer les disciplines d’un professeur.');}
        Csrf::verify($_POST['_csrf'] ?? null);

        $id=(int)($_POST['professeur_id'] ?? 0);

        ProfessorPro::replaceDisciplines(
            $id,
            $_POST['disciplines'] ?? [],
            (int)($_POST['discipline_principale'] ?? 0) ?: null
        );

        $_SESSION['success']='Les disciplines du professeur ont été mises à jour.';
        $professor=ProfessorPro::find($id);
        $this->redirect('/professeurs-pro/voir?professeur='.rawurlencode((string)$professor['public_token']));
    }
}
