<?php

namespace App\Listeners;

use App\Models\Student;
use App\Models\StatutStudent;
use App\Models\PyramideStudent;
use App\Events\StatutPyramideEvent;

class StatutPyramideListener
{

    public function handle(StatutPyramideEvent $event): void
    {
        $this->updateStatut($event);
        $this->updatePyramide($event);
    }

    private function getSexeStudent($id){
        $student = Student::find($id);
        return $student->sexe;
    }

    private function getStatut($vals){
        return  StatutStudent::where('school_id', $vals->inscription->school_id)
        ->where('school_year_id', $vals->inscription->school_year_id)
        ->where('level_id', $vals->inscription->level_id)->first();
    }

    private function updateStatut($vals){
        $attribut = $this->getAffect($vals->inscription->student_id, $vals->inscription->affecte);
        $update = $this->getStatut($vals);
        $update ? $update->update([$attribut => $update[$attribut]-1]):null;
    }

    private function getPyramide($vals){

        $serie = $vals->inscription->serie_id ? $this->getSerie($vals->inscription->serie_id, $vals->inscription->level_id):null;
        return  PyramideStudent::where('school_id', $vals->inscription->school_id)
        ->where('school_year_id', $vals->inscription->school_year_id)
        ->where('level_id', $vals->inscription->level_id)
        ->where('serie_id', $serie)->first();
    }

    private function updatePyramide($vals){
        $attribut = $this->getRedouble($vals->inscription->student_id, $vals->inscription->redoublant);
        $update = $this->getPyramide($vals);
        $update->update([$attribut => $update[$attribut]-1]);
    }

    private function getAffect($id, $affect){
        $sexe = $this->getSexeStudent($id);
        return match (true){
            (ucwords($sexe) == 'F' && strtolower($affect) == 'oui') => 'nbre_affect_fille',
            (ucwords($sexe) == 'F' && strtolower($affect) == 'non') => 'nbre_non_affect_fille',
            (ucwords($sexe) == 'M' && strtolower($affect) == 'oui') => 'nbre_affect_garcon',
            (ucwords($sexe) == 'M' && strtolower($affect) == 'non') => 'nbre_non_affect_garcon',
        };
    }

    private function getRedouble($id, $doublant){
        $sexe = $this->getSexeStudent($id);
        return match (true){
            (ucwords($sexe) == 'F' && strtolower($doublant) == 'oui') => 'nbre_redoublant_fille',
            (ucwords($sexe) == 'F' && strtolower($doublant) == 'non') => 'nbre_non_redoublant_fille',
            (ucwords($sexe) == 'M' && strtolower($doublant) == 'oui') => 'nbre_redoublant_garcon',
            (ucwords($sexe) == 'M' && strtolower($doublant) == 'non') => 'nbre_non_redoublant_garcon',
        };
    }


    private function getSerie($serie, $level){
        if(in_array($level, ['15','16'])){ // 15 => 1ere, 16 => Tle
            $serie = in_array($serie, ['2','3']) ? '1':$serie; 
        }
        return $serie;
    }
}
