<?php

namespace App\Jobs;

use App\Models\CuttingSchoolYear;
use App\Models\MoyenneDecoupageMatiere;
use App\Models\MoyenneAnnuelleTrimestre;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

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

    protected $student, $matter, $year;

    public function __construct($student, $matter, $year)
    {
        $this->student = $student;
        $this->matter = $matter;
        $this->year = $year;
    }


    public function handle(): void
    {
        $dts = getClassement($this->getMoyenne());
        foreach($dts as $item){ 
            $exist = MoyenneAnnuelleTrimestre::where('inscription_id', $item['id'])->where('level_matter_id', $this->matter)->where('school_year_id', $this->year)->first();
            if($exist){
                $exist->update([
                    'rang_annuel' => $item['rang'],
                    'moyenne_annuel' => $item['moyen']
                ]); 
            }
        }
    }


    private function getMoyenne() {
        $table = [];
        foreach ($this->student as $item) {
            $table[] = [
                'id' => $item->id,
                'sexe' => $item->sexe,
                'moyen' => $this->moyenne($item->id)
            ];
        }
        return $table;
    }


    private function moyenne($item) {
        $cutting = $this->getCutting();
        $coef = 0; $nbre = 0; $exist = false;
        foreach($cutting as $val){
            $query = $this->getVal($item, $val->id);
            if($query && $query != 'nc'){
                $nbre += ($query * $val->cutting->valeur); // Moyenne multipliée par le coefficient du decoupage
                $coef += $val->cutting->valeur;
                $exist = true;
            }
        }
        $moyen = $exist ? ($nbre ? number_format(($nbre / $coef), 2, '.', ' '):'0'):'nc';
        return $exist ? ($moyen < 10 ? '0'.$moyen:$moyen):$moyen;
    }


    private function getVal($id1, $id2) {
        $val = MoyenneDecoupageMatiere::where('inscriptif_id', $id1)->where('discipline_level_id', $this->matter)->where('cutting_school_year_id', $id2)->first();
        return $val ? $val->moyenne:null;
    }


    private function getCutting() {
        $dts = CuttingSchoolYear::where('school_year_id', $this->year)->get();
        return $dts;
    }
}
