<?php
namespace App\Controllers;

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

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

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

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

        $this->view('workshops/manage',[
            'pageTitle'=>'Modifier le cours',
            'workshop'=>$workshop,
            'publics'=>WorkshopManagement::publics(),
            'disciplines'=>WorkshopManagement::disciplines(),
            'selectedPublics'=>
                WorkshopManagement::selectedPublicIds($id),
        ]);
    }

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

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

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

        $discipline=WorkshopManagement::discipline($disciplineId);
        if(!$discipline){
            $_SESSION['error']='La discipline sélectionnée est invalide.';
            $this->redirect('/ateliers/modifier?id='.$id);
        }

        WorkshopManagement::update($id,[
            'libelle'=>trim($_POST['libelle']),
            'discipline_id'=>$disciplineId,
            'pole_id'=>(int)$discipline['pole_id'],
            'type_atelier'=>$_POST['type_atelier'] ?? 'collectif',
            'description'=>trim($_POST['description'] ?? ''),
            'duree'=>(int)($_POST['duree_standard_minutes'] ?? 0),
            'capacite'=>(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);

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

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