<?php
declare(strict_types=1);
namespace App\Controllers;

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

final class EnrollmentOptimizationController extends Controller
{
    private function org(): int{return (int)(Auth::user()['organisation_id']??1);}

    public function index(): void
    {
        Auth::requireLogin();
        Permission::require('demandes_inscription.validate');
        $this->view('enrollment_optimization/index',[
            'pageTitle'=>'Optimisation des groupes et créneaux',
            'analysis'=>EnrollmentOptimizer::analyse($this->org()),
        ]);
    }

    public function propose(): void
    {
        Auth::requireLogin();
        Permission::require('demandes_inscription.validate');
        Csrf::verify($_POST['_csrf']??null);
        $selected=array_map('intval',(array)($_POST['selected']??[]));
        $slots=(array)($_POST['slot']??[]);$assignments=[];
        foreach($selected as $requestId){if(isset($slots[$requestId]))$assignments[$requestId]=(int)$slots[$requestId];}
        try{
            if(!$assignments)throw new \RuntimeException('Sélectionnez au moins une proposition.');
            $count=EnrollmentOptimizer::createProposals($this->org(),$assignments,(int)Auth::id());
            $_SESSION['success']=$count.' proposition(s) transmise(s) pour validation. Aucune inscription ni facturation n’a été créée.';
        }catch(\Throwable $e){$_SESSION['error']=$e->getMessage();}
        $this->redirect('/demandes-inscription/optimisation');
    }
}
