<?php
namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Csrf;
use App\Core\Permission;
use App\Models\WorkshopV51;

final class WorkshopV51Controller extends Controller
{
    public function edit(): void
    {
        Auth::requireLogin();
        Permission::require('ateliers.edit');

        $id=(int)($_GET['id'] ?? 0);
        $workshop=WorkshopV51::find($id);

        if(!$workshop){
            http_response_code(404);
            exit('Cours introuvable.');
        }

        $this->view('workshops_v51/edit',[
            'pageTitle'=>'Modifier le cours',
            'workshop'=>$workshop,
            'publics'=>WorkshopV51::publics(),
            'selectedPublics'=>WorkshopV51::publicIds($id),
        ]);
    }

    public function update(): void
    {
        Auth::requireLogin();
        Permission::require('ateliers.edit');
        Csrf::verify($_POST['_csrf'] ?? null);

        $id=(int)($_POST['id'] ?? 0);
        $publicIds=array_values(
            array_unique(
                array_filter(
                    array_map(
                        'intval',
                        $_POST['public_ids'] ?? []
                    )
                )
            )
        );

        if(
            trim($_POST['libelle'] ?? '')==='' ||
            !$publicIds
        ){
            $_SESSION['error']=
                'Le libellé et au moins un public sont obligatoires.';
            $this->redirect('/ateliers/modifier?id='.$id);
        }

        WorkshopV51::update($id,[
            'libelle'=>trim($_POST['libelle']),
            'type_atelier'=>$_POST['type_atelier'] ?? 'collectif',
            'description'=>trim($_POST['description'] ?? ''),
            'duree_standard_minutes'=>
                (int)($_POST['duree_standard_minutes'] ?? 0),
            'capacite_max'=>
                (int)($_POST['capacite_max'] ?? 0),
            'public_ids'=>$publicIds,
        ]);

        $_SESSION['success']='Le cours a été modifié.';
        $this->redirect('/ateliers');
    }

    public function archive(): void
    {
        Auth::requireLogin();
        Permission::require('ateliers.archive');
        Csrf::verify($_POST['_csrf'] ?? null);

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

        WorkshopV51::archive(
            $id,
            (int)(Auth::user()['id'] ?? 0)
        );

        $_SESSION['success']='Le cours a été archivé.';
        $this->redirect('/ateliers');
    }
}
