<?php

namespace App\Listeners;

use App\Models\Absence;
use App\Models\AbsenceGet;
use App\Events\AbsenceSavedEvent;

class AbsenceSavedListener
{

    /**
     * Handle the event.
     */
    public function handle(AbsenceSavedEvent $event): void
    {
        $nbre1 = $this->justify($event->student, $event->cutting);
        $nbre2 = $this->nonJustify($event->student, $event->cutting);
        AbsenceGet::create([
            'justify' => $nbre1,
            'non_justify' => $nbre2,
            'nbre_totals' => ($nbre1+$nbre2),
            'inscription_id' => $event->student,
            'cutting_school_year_id' => $event->cutting
        ]);
    }

    private function justify($student, $cutting){
        $nbre = Absence::where('inscription_id', $student)->where('cutting_school_year_id', $cutting)->where('justified', '1')->count();
        return $nbre;
    }

    private function nonJustify($student, $cutting){
        $nbre = Absence::where('inscription_id', $student)->where('cutting_school_year_id', $cutting)->where('justified', '0')->count();
        return $nbre;
    }
}
