<?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\DisciplinePlanning;
use App\Models\EnrollmentRequest;

final class FamilyEnrollmentController extends Controller
{
    public function index(): void
    {
        Auth::requireLogin();
        $clientId=$this->clientId();
        $this->view('family_enrollments/index',[
            'pageTitle'=>'Mes inscriptions',
            'requests'=>EnrollmentRequest::forClient($clientId),
        ]);
    }

    public function create(): void
    {
        Auth::requireLogin();
        $clientId=$this->clientId();
        $members=EnrollmentRequest::portalMembers($this->org(),$clientId);
        if(!$members){
            $_SESSION['error']='Aucun membre actif n’est rattaché à votre dossier.';
            $this->redirect('/mon-espace/inscriptions');
        }
        $this->view('family_enrollments/form',[
            'pageTitle'=>'Nouvelle préinscription',
            'members'=>$members,
            'disciplines'=>DisciplinePlanning::disciplinesForRequest($this->org()),
        ]);
    }

    public function store(): void
    {
        Auth::requireLogin();
        Csrf::verify($_POST['_csrf']??null);
        $clientId=$this->clientId();
        $memberId=(int)($_POST['membre_id']??0);
        if(!EnrollmentRequest::portalMemberOwnedBy($this->org(),$clientId,$memberId)){
            $this->deny();
        }
        try{
            EnrollmentRequest::createDiscipline([
                'organisation_id'=>$this->org(),
                'membre_id'=>$memberId,
                'discipline_id'=>(int)($_POST['discipline_id']??0),
                'adherent_id'=>$clientId,
                'disponibilites'=>trim((string)($_POST['disponibilites']??''))?:null,
                'commentaire_famille'=>trim((string)($_POST['commentaire_famille']??''))?:null,
                'instrument_loan_type'=>in_array((string)($_POST['instrument_loan_type']??'none'),['none','individual','collective'],true)
                    ? (string)$_POST['instrument_loan_type'] : 'none',
                'created_by'=>(int)Auth::id()?:null,
            ]);
            $_SESSION['success']='Votre préinscription a été transmise. Elle reste sans facturation jusqu’à la validation d’un créneau par la Direction.';
            $this->redirect('/mon-espace/inscriptions');
        }catch(\Throwable $e){
            $_SESSION['form_errors']=[$e->getMessage()];
            $_SESSION['old']=$_POST;
            $this->redirect('/mon-espace/inscriptions/nouvelle');
        }
    }

    public function cancel(): void
    {
        Auth::requireLogin();
        Csrf::verify($_POST['_csrf']??null);
        try{
            EnrollmentRequest::cancelFromPortal((int)($_POST['id']??0),$this->org(),$this->clientId(),(int)Auth::id());
            $_SESSION['success']='La demande a été annulée.';
        }catch(\Throwable $e){
            $_SESSION['error']=$e->getMessage();
        }
        $this->redirect('/mon-espace/inscriptions');
    }

    private function clientId(): int
    {
        if(!Permission::isFamilyPortalIdentity())$this->deny();
        $id=(int)(Permission::familyPortalClientId()??0);
        if($id<=0)$this->deny();
        return $id;
    }
    private function org(): int{return (int)(Auth::user()['organisation_id']??1);}
    private function deny(): never{http_response_code(403);exit('Accès refusé.');}
}
