<?php
namespace App\Controllers;

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

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

        $this->view('workshops/index', [
            'pageTitle' => 'Cours et ateliers',
            'workshops' => Workshop::all(),
        ]);
    }

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

        $this->view('workshops/form', [
            'pageTitle' => 'Nouveau cours',
            'poles' => Workshop::poles(),
            'disciplines' => Workshop::disciplines(),
            'publics' => Workshop::publics(),
            'year' => Workshop::currentYear(),
        ]);
    }

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

        $year = Workshop::currentYear();
        $poleId = (int)($_POST['pole_id'] ?? 0);
        $disciplineId =
            (int)($_POST['discipline_id'] ?? 0);

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

        $libelle = trim($_POST['libelle'] ?? '');
        $errors = [];

        if (!$year) {
            $errors[] =
                'Aucune année scolaire active.';
        }

        if (!$poleId) {
            $errors[] =
                'Le pôle est obligatoire.';
        }

        if (!$disciplineId) {
            $errors[] =
                'La discipline est obligatoire.';
        }

        if (!$publicIds) {
            $errors[] =
                'Choisissez au moins un public : '
                . 'Enfant ou Adulte.';
        }

        if ($libelle === '') {
            $errors[] =
                'Le libellé du cours est obligatoire.';
        }

        $pole = null;
        foreach (Workshop::poles() as $row) {
            if ((int)$row['id'] === $poleId) {
                $pole = $row;
                break;
            }
        }

        $discipline = null;
        foreach (Workshop::disciplines() as $row) {
            if ((int)$row['id'] === $disciplineId) {
                $discipline = $row;
                break;
            }
        }

        if (
            $discipline &&
            (int)$discipline['pole_id'] !== $poleId
        ) {
            $errors[] =
                'La discipline ne correspond pas '
                . 'au pôle sélectionné.';
        }

        if ($errors) {
            $_SESSION['form_errors'] = $errors;
            $_SESSION['old'] = $_POST;
            $this->redirect('/ateliers/nouveau');
        }

        Workshop::create([
            'organisation_id' =>
                (int)(Auth::user()['organisation_id'] ?? 1),
            'annee_scolaire_id' =>
                (int)$year['id'],
            'pole_id' => $poleId,
            'discipline_id' => $disciplineId,
            'public_ids' => $publicIds,
            'pole_code' =>
                (string)($pole['code'] ?? ''),
            'discipline_code' =>
                (string)($discipline['code'] ?? ''),
            'libelle' => $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),
            'statut' =>
                $_POST['statut'] ?? 'brouillon',
        ]);

        $_SESSION['success'] =
            'Le cours a été créé avec ses publics.';

        $this->redirect('/ateliers');
    }
}
