<?php
namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Csrf;
use App\Core\Permission;
use App\Models\Workshop;
use App\Models\WorkshopV5;

final class WorkshopV5Controller extends Controller
{
    public function show(): void
    {
        Auth::requireLogin();
        Permission::require('ateliers.view');

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

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

        $this->view('workshops_v5/show',[
            'pageTitle'=>'Fiche atelier',
            'workshop'=>$workshop,
        ]);
    }

    public function edit(): void
    {
        Auth::requireLogin();
        Permission::require('ateliers.edit');

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

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

        $this->view('workshops_v5/edit',[
            'pageTitle'=>'Modifier l’atelier',
            'workshop'=>$workshop,
            'publics'=>Workshop::publics(),
            'selectedPublics'=>WorkshopV5::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);
        }

        WorkshopV5::update(
            $id,
            [
                'libelle'=>trim($_POST['libelle']),
                'description'=>trim($_POST['description'] ?? ''),
                'type_atelier'=>$_POST['type_atelier'] ?? 'collectif',
                'duree_standard_minutes'=>
                    (int)($_POST['duree_standard_minutes'] ?? 0),
                'capacite_max'=>
                    (int)($_POST['capacite_max'] ?? 0),
                'public_ids'=>$publicIds,
                'motif'=>trim($_POST['motif'] ?? ''),
                'date_effet'=>$_POST['date_effet'] ?? null,
            ],
            (int)(Auth::user()['id'] ?? 0)
        );

        $_SESSION['success']='L’atelier a été modifié.';
        $this->redirect('/ateliers/voir?id='.$id);
    }

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

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

        WorkshopV5::changeStatus(
            $id,
            (string)($_POST['statut'] ?? ''),
            (int)(Auth::user()['id'] ?? 0),
            trim($_POST['motif'] ?? '')
        );

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

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

        $id=(int)($_POST['id'] ?? 0);
        $date=$_POST['date_effective'] ?? date('Y-m-d');
        $reason=trim($_POST['motif'] ?? '');

        if($reason===''){
            $_SESSION['error']='Le motif de fermeture est obligatoire.';
            $this->redirect('/ateliers/voir?id='.$id);
        }

        WorkshopV5::close(
            $id,
            $date,
            $reason,
            (int)(Auth::user()['id'] ?? 0)
        );

        $_SESSION['success']='L’atelier a été fermé.';
        $this->redirect('/ateliers/voir?id='.$id);
    }

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

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

        if($reason===''){
            $_SESSION['error']='Le motif d’archivage est obligatoire.';
            $this->redirect('/ateliers/voir?id='.$id);
        }

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

        $_SESSION['success']='L’atelier a été archivé.';
        $this->redirect('/ateliers/voir?id='.$id);
    }

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

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

        WorkshopV5::restore(
            $id,
            (int)(Auth::user()['id'] ?? 0)
        );

        $_SESSION['success']='L’atelier a été restauré en brouillon.';
        $this->redirect('/ateliers/voir?id='.$id);
    }

    public function history(): void
    {
        Auth::requireLogin();
        Permission::require('ateliers.view_history');

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

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

        $this->view('workshops_v5/history',[
            'pageTitle'=>'Historique atelier',
            'workshop'=>$workshop,
            'history'=>WorkshopV5::history($id),
        ]);
    }
}
