<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Core\Auth;
use App\Core\Controller;
use App\Core\Csrf;
use App\Core\Permission;
use App\Reference\ReferenceRepository;
use App\Reference\ReferenceService;
use Throwable;
final class ReferenceController extends Controller
{
    private ReferenceRepository $repository; private ReferenceService $service;
    public function __construct(){ Auth::requireLogin();Permission::requireAny('parametres.poles.manage','parametres.disciplines.manage','parametres.publics.manage','parametres.types_cours.manage');$this->repository=new ReferenceRepository();$this->service=new ReferenceService($this->repository); }
    public function index(): void { Auth::requireLogin();Permission::requireAny('parametres.poles.manage','parametres.disciplines.manage','parametres.publics.manage','parametres.types_cours.manage');$types=$this->repository->types();$selected=null;$values=[];$edited=null;$code=trim((string)($_GET['type']??''));if($code==='tarifs'){header('Location: /public/tarifs');exit;}if($code!==''){$selected=$this->repository->typeByCode($code);if($selected)$values=$this->repository->values((int)$selected['id'],true);}if($selected&&in_array($code,['salles','poles','disciplines'],true)&&!empty($_GET['edit'])){$candidate=$this->repository->value((int)$_GET['edit']);if($candidate&&(int)$candidate['type_id']===(int)$selected['id'])$edited=$candidate;} $this->view('reference/index',['pageTitle'=>'Référentiels AXIOM','types'=>$types,'selected'=>$selected,'values'=>$values,'edited'=>$edited,'stats'=>$this->repository->stats(),'history'=>$this->repository->history(12),'flash'=>$_SESSION['reference_flash']??null]);unset($_SESSION['reference_flash']); }
    public function saveType(): void { Auth::requireLogin();Csrf::verify($_POST['_csrf']??null);try{$this->service->saveType(!empty($_POST['id'])?(int)$_POST['id']:null,$_POST);$this->flash('success','Référentiel enregistré.');}catch(Throwable $e){$this->flash('error',$e->getMessage());}$this->redirect('/administration/axiom/referentiels'); }
    public function saveValue(): void { Auth::requireLogin();Csrf::verify($_POST['_csrf']??null);$typeId=(int)($_POST['type_id']??0);$typeCode=(string)($_POST['type_code']??'');try{if($typeCode==='salles'){$activities=array_values(array_intersect(['musique','theatre','dessin'],array_map('strval',(array)($_POST['room_activities']??[]))));if(!$activities)throw new \InvalidArgumentException('Choisissez au moins une activité pour la salle.');$_POST['metadata']=json_encode(['activities'=>$activities],JSON_UNESCAPED_UNICODE);$_POST['icon']=implode(' ',array_map(static fn(string $a):string=>['musique'=>'🎵','theatre'=>'🎭','dessin'=>'🎨'][$a],$activities));}if($typeCode==='poles'){$kind=(string)($_POST['pole_kind']??'');$choices=['structure'=>['🏛️','#334155'],'theatre'=>['🎭','#7c3aed'],'musique'=>['🎵','#2563eb'],'arts'=>['🎨','#ea580c'],'autre'=>['✨','#0f766e']];if(!isset($choices[$kind]))throw new \InvalidArgumentException('Choisissez le type de pôle.');$_POST['icon']=$choices[$kind][0];$_POST['color']=$choices[$kind][1];$_POST['metadata']=json_encode(['pole_kind'=>$kind],JSON_UNESCAPED_UNICODE);}$id=$this->service->saveValue($typeId,!empty($_POST['id'])?(int)$_POST['id']:null,$_POST);if($typeCode==='disciplines'){$this->repository->synchronizeDisciplineDuration($id,(int)($_POST['duree_individuelle_minutes']??30),(int)($_POST['duree_collective_minutes']??60));}$message=$typeCode==='salles'?'Salle enregistrée.':($typeCode==='poles'?'Pôle enregistré.':($typeCode==='disciplines'?'Discipline et durées enregistrées.':'Valeur enregistrée.'));$this->flash('success',$message);}catch(Throwable $e){$this->flash('error',$e->getMessage());}$this->redirect('/administration/axiom/referentiels?type='.rawurlencode($typeCode)); }
    public function archiveValue(): void { Auth::requireLogin();Csrf::verify($_POST['_csrf']??null);$this->repository->archiveValue((int)($_POST['id']??0));$this->flash('success','Valeur archivée.');$this->redirect('/administration/axiom/referentiels?type='.rawurlencode((string)($_POST['type_code']??''))); }
    public function restoreValue(): void { Auth::requireLogin();Csrf::verify($_POST['_csrf']??null);$this->repository->restoreValue((int)($_POST['id']??0));$this->flash('success','Valeur restaurée.');$this->redirect('/administration/axiom/referentiels?type='.rawurlencode((string)($_POST['type_code']??''))); }
    private function flash(string $type,string $message): void { $_SESSION['reference_flash']=['type'=>$type,'message'=>$message]; }
}
