<?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;
use App\Models\ProfessorPro;
use App\Models\MemberProfile;
use App\Services\EnrollmentConfirmationService;
use App\Services\EnrollmentAiAssistant;

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

    public function create(): void
    {
        Auth::requireLogin();
        Permission::require('demandes_inscription.create');
        $id=(int)($_GET['membre_id'] ?? 0);
        $member=MemberProfile::find($id);
        if(!$member){
            http_response_code(404);
            exit('Membre introuvable.');
        }
        $this->view('members/request_form',[
            'pageTitle'=>'Demande d’inscription',
            'member'=>$member,
            'annualFile'=>EnrollmentRequest::activeAnnualFile(
                $this->org(),
                (int)($member['client_id'] ?? 0)
            ),
            'disciplines'=>DisciplinePlanning::disciplinesForRequest($this->org()),
        ]);
    }

    public function store(): void
    {
        Auth::requireLogin();
        Permission::require('demandes_inscription.create');
        Csrf::verify($_POST['_csrf'] ?? null);
        $memberId=(int)($_POST['membre_id'] ?? 0);
        try{
            $member=MemberProfile::find($memberId);
            if(!$member || empty($member['client_id'])){
                throw new \RuntimeException('Le membre n’est pas correctement rattaché à un adhérent.');
            }
            EnrollmentRequest::createDiscipline([
                'organisation_id'=>$this->org(),
                'membre_id'=>$memberId,
                'discipline_id'=>(int)($_POST['discipline_id'] ?? 0),
                'adherent_id'=>(int)$member['client_id'],
                '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']='Demande ajoutée à la file d’attente de la discipline. Elle n’active pas automatiquement l’année et ne crée aucune facturation.';
        }catch(\Throwable $error){
            $_SESSION['form_errors']=[$error->getMessage()];
        }
        $this->redirect('/clients/voir?id='.(int)($member['client_id'] ?? 0).'#demandes-inscription');
    }

    public function index(): void
    {
        Auth::requireLogin();
        Permission::requireAny('demandes_inscription.view','demandes_inscription.review');
        $status=trim((string)($_GET['statut'] ?? ''));
        $allowed=['','a_etudier','file_attente','creneau_propose','validee','refusee','abandonnee'];
        if(!in_array($status,$allowed,true)){
            $status='';
        }
        $requests=EnrollmentRequest::waitingList($this->org(),$status);
        if(!Permission::canViewFullProfessorRh()){
            $professorId=ProfessorPro::professorForUser((int)Auth::id());
            $disciplineIds=array_map(
                static fn(array $row): int => (int)$row['id'],
                $professorId ? ProfessorPro::disciplines($professorId) : []
            );
            $requests=array_values(array_filter(
                $requests,
                static fn(array $row): bool => in_array((int)($row['discipline_id'] ?? 0),$disciplineIds,true)
            ));
        }
        $this->view('enrollment_requests/index',[
            'pageTitle'=>'Files d’attente',
            'requests'=>$requests,
            'selectedStatus'=>$status,
        ]);
    }

    public function review(): void
    {
        Auth::requireLogin();
        Permission::require('demandes_inscription.review');
        $request=EnrollmentRequest::find((int)($_GET['id'] ?? 0),$this->org());
        if(!$request){
            http_response_code(404);
            exit('Demande introuvable.');
        }
        $this->view('enrollment_requests/review',[
            'pageTitle'=>'Valider la demande',
            'request'=>$request,
            'slots'=>DisciplinePlanning::slotsForDiscipline(
                $this->org(),
                (int)$request['discipline_id']
            ),
        ]);
    }

    public function validateRequest(): void
    {
        Auth::requireLogin();
        Permission::require('demandes_inscription.validate');
        Csrf::verify($_POST['_csrf'] ?? null);
        try{
            $result=EnrollmentRequest::validateSlot(
                (int)$_POST['id'],
                $this->org(),
                (int)$_POST['slot_id'],
                (int)Auth::id()
            );
            $mail=EnrollmentConfirmationService::send($result,(int)Auth::id());
            $_SESSION['success']='Inscription validée, place occupée, agenda et facturation alimentés. '.$mail;
        }catch(\Throwable $error){
            $_SESSION['form_errors']=[$error->getMessage()];
            $this->redirect('/demandes-inscription/etudier?id='.(int)$_POST['id']);
        }
        $this->redirect('/demandes-inscription');
    }
    public function aiAssistant(): void
    {
        Auth::requireLogin();
        Permission::require('demandes_inscription.review');
        $this->view('enrollment_requests/ai_assistant',[
            'pageTitle'=>'Assistant IA d’affectation',
            'suggestions'=>EnrollmentAiAssistant::suggestions($this->org()),
        ]);
    }

    public function createAiProposals(): void
    {
        Auth::requireLogin();
        Permission::require('demandes_inscription.review');
        Csrf::verify($_POST['_csrf'] ?? null);
        $selected=(array)($_POST['suggestions'] ?? []);$created=0;
        try{
            foreach(EnrollmentAiAssistant::suggestions($this->org()) as $row){
                $key=(int)$row['request_id'].'-'.(int)($row['slot_id']??0);
                if(!isset($selected[$key]) || empty($row['slot_id']) || (int)$row['score']<1)continue;
                DisciplinePlanning::proposeStudent($this->org(),(int)$row['professeur_id'],(int)$row['slot_id'],(int)$row['request_id'],(int)Auth::id(),'Suggestion INSCRIPTION-006 — score '.(int)$row['score'].'/100 : '.implode(', ',$row['reasons']));
                $created++;
            }
            $_SESSION['success']=$created.' proposition(s) IA transmise(s) au circuit de validation Direction.';
        }catch(\Throwable $e){$_SESSION['error']=$e->getMessage();}
        $this->redirect('/demandes-inscription/assistant-ia');
    }

}
