<?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\Planning\PlanningRepository;
use Throwable;

final class PlanningController extends Controller
{
    public function index(): void
    {
        Auth::requireLogin();
        Permission::require('axiom.planning.view');
        $repo = new PlanningRepository();
        $view = in_array($_GET['view'] ?? 'week', ['day','week','month'], true) ? (string)$_GET['view'] : 'week';
        $anchor = $this->validDate((string)($_GET['date'] ?? date('Y-m-d')));
        [$from,$to] = $repo->range($view, $anchor);
        $calendarId = max(0, (int)($_GET['calendar'] ?? 0));
        $this->view('axiom_planning/index', [
            'pageTitle' => 'AXIOM Planning Engine', 'viewMode'=>$view, 'anchor'=>$anchor,
            'from'=>$from, 'to'=>$to, 'calendarId'=>$calendarId,
            'calendars'=>$repo->calendars(), 'resources'=>$repo->resources(),
            'events'=>$repo->events($from,$to,$calendarId), 'absences'=>$repo->absences($from,$to),
            'conflicts'=>$repo->conflicts($from,$to),
            'canManage'=>Permission::can('axiom.planning.manage'),
            'flashSuccess'=>$_SESSION['axiom_planning_success']??null,
            'flashError'=>$_SESSION['axiom_planning_error']??null,
        ]);
        unset($_SESSION['axiom_planning_success'], $_SESSION['axiom_planning_error']);
    }
    public function saveCalendar(): void { $this->run(fn($r)=>$r->saveCalendar($_POST),'Agenda enregistré.'); }
    public function saveResource(): void { $this->run(fn($r)=>$r->saveResource($_POST),'Ressource enregistrée.'); }
    public function saveEvent(): void { $this->run(fn($r)=>$r->saveEvent($_POST,$this->userId()),'Événement enregistré.'); }
    public function deleteEvent(): void { $this->run(fn($r)=>$r->deleteEvent((int)($_POST['event_id']??0)),'Événement annulé.'); }
    public function saveAbsence(): void { $this->run(fn($r)=>$r->saveAbsence($_POST,$this->userId()),'Indisponibilité enregistrée.'); }
    private function run(callable $action,string $success): void
    {
        Auth::requireLogin(); Permission::require('axiom.planning.manage'); Csrf::verify($_POST['_csrf']??null);
        try { $action(new PlanningRepository()); $_SESSION['axiom_planning_success']=$success; }
        catch(Throwable $e){ $_SESSION['axiom_planning_error']=$e->getMessage(); }
        $this->redirect('/administration/axiom/planning');
    }
    private function validDate(string $date): string { $d=\DateTimeImmutable::createFromFormat('Y-m-d',$date); return $d&&$d->format('Y-m-d')===$date?$date:date('Y-m-d'); }
    private function userId(): ?int { return isset($_SESSION['user_id'])?(int)$_SESSION['user_id']:null; }
}
