<?php
namespace App\Controllers;

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

final class AttendanceController extends Controller
{
    public function index(): void
    {
        Auth::requireLogin();
        Permission::require('presences.view');
        $organisationId = $this->organisationId();
        $date = (string)($_GET['date'] ?? date('Y-m-d'));
        $ownProfessor = Attendance::professorForUser((int)Auth::id());
        $professorId = $ownProfessor;
        if ($professorId <= 0 && isset($_GET['professeur'])) {
            $professorId = Attendance::professorByToken((string)$_GET['professeur'], $organisationId);
            if ($professorId <= 0) $this->notFound();
        }
        if (isset($_GET['professeur_id'])) $this->notFound();

        $this->view('attendance/index',[
            'pageTitle'=>'Présences & émargements',
            'date'=>$date,
            'professorId'=>$professorId,
            'professorToken'=>$professorId > 0
                ? Attendance::professorToken($professorId, $organisationId)
                : '',
            'workDays'=>Attendance::workDays($professorId,$date,$organisationId),
            'sessions'=>Attendance::sessions($date,$professorId,$organisationId),
            'groups'=>Attendance::groups($professorId,$organisationId),
        ]);
    }

    public function create(): void
    {
        Auth::requireLogin();
        Permission::require('presences.mark');
        Csrf::verify($_POST['_csrf']??null);
        $date = (string)($_POST['date_seance'] ?? '');
        $token = Attendance::create(
            (int)($_POST['groupe_id'] ?? 0),
            $date,
            $this->organisationId(),
            Attendance::professorForUser((int)Auth::id())
        );
        $this->redirect('/presences/feuille?seance='.rawurlencode($token));
    }

    public function sheet(): void
    {
        Auth::requireLogin();
        Permission::require('presences.view');
        $session = $this->session();
        $this->view('attendance/sheet',['pageTitle'=>'Feuille de présence']+Attendance::sheet($session));
    }

    public function mark(): void
    {
        Auth::requireLogin();
        Permission::require('presences.mark');
        Csrf::verify($_POST['_csrf']??null);
        $session = $this->session((string)($_POST['seance'] ?? ''));
        $ok = Attendance::mark(
            (int)$session['id'],
            (int)($_POST['participant_id'] ?? 0),
            (string)($_POST['statut'] ?? 'present'),
            trim((string)($_POST['motif'] ?? '')),
            trim((string)($_POST['observation'] ?? '')),
            (int)(Auth::user()['id']??0) ?: null
        );
        if (!$ok) $this->notFound();
        $this->redirect('/presences/feuille?seance='.rawurlencode((string)$session['public_token']));
    }

    public function validate(): void
    {
        Auth::requireLogin();
        Permission::require('presences.validate');
        Csrf::verify($_POST['_csrf']??null);
        $session = $this->session((string)($_POST['seance'] ?? ''));
        Attendance::validate((int)$session['id'],(int)(Auth::user()['id']??0) ?: null);
        $this->redirect('/presences/feuille?seance='.rawurlencode((string)$session['public_token']));
    }

    private function session(?string $token = null): array
    {
        if (isset($_GET['id']) || isset($_POST['seance_id'])) $this->notFound();
        $session = Attendance::resolveSession(
            (string)($token ?? ($_GET['seance'] ?? '')),
            $this->organisationId(),
            Attendance::professorForUser((int)Auth::id())
        );
        if (!$session) $this->notFound();
        return $session;
    }

    private function organisationId(): int
    {
        return (int)(Auth::user()['organisation_id'] ?? 1);
    }

    private function notFound(): never
    {
        http_response_code(404);
        exit('Ressource introuvable.');
    }
}
