<?php

namespace App\Jobs;

use App\Models\Classe;
use App\Models\LevelMatter;
use App\Models\MoyenneMatiere;
use App\Models\ApprovedMoyenne;
use App\Models\CuttingSchoolYear;
use App\Events\MoyenneMatiereEvent;
use App\Models\MoyenneDecoupageMatiere;
use App\Jobs\MoyenneAnnuelleMatiereJob;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class BonnusMoyenneMatiereJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $student, $matter, $decoupage, $classe;
    /**
     * Create a new job instance.
     */
    public function __construct($student, $matter, $decoupage, $classe = null)
    {
        $this->student = $student;
        $this->matter = $matter;
        $this->decoupage = $decoupage;
        $this->classe = $classe;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $cutting = CuttingSchoolYear::find($this->decoupage);
        foreach(getClassement($this->student) as $item){
            MoyenneMatiere::where('inscription_id', $item['id'])->where('level_matter_id', $this->matter)->where('cutting_school_year_id', $this->decoupage)->update([
                'moyenne' => $item['moyen'],
                'rang' => $item['rang']
            ]);
            if($this->classe){
                $this->updateMoyenne($item['id'], $item['moyen'], $item['rang']);
            }

            // Déclenchement de l’événement
            event(new MoyenneMatiereEvent($item['id'], $item['moyen'], $item['rang'], $this->getCoef(), $cutting->school_year_id, $cutting->cutting->libelle, $this->matter, $this->school()));
        }

        // Déclenchement de Job pour le calcul des moyennes Annuelles .................
        if($cutting->cutting->end != 'oui'){
            MoyenneAnnuelleMatiereJob::dispatch($this->student, $this->matter, $cutting->school_year_id)->delay(now()->addSeconds(1));
        }
    }



    private function getCoef()
    {
        $val = LevelMatter::find($this->matter);
        return $val->coefficient->valeur;
    }


    protected function school(){
        $class = Classe::find($this->classe);
        return $class->school_id;
    }

    protected function updateMoyenne($student, $moyen, $rang)
    {
        $val = ApprovedMoyenne::where('classe_id', $this->classe)->where('level_matter_id', $this->matter)->where('cutting_school_year_id', $this->decoupage)->count();
        if($val){
            MoyenneDecoupageMatiere::where('inscription_id', $student)->where('level_matter_id', $this->matter)->where('cutting_school_year_id', $this->decoupage)->update([
                'moyenne' => $moyen,
                'rang' => $rang
            ]);
        }
    }
}