<?php

namespace App\Jobs;

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 BonnusMoyenneAnnuelleMatiereJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $student, $matiere, $year;

    public function __construct($student, $matiere, $year)
    {
        $this->student = $student;
        $this->matiere = $matiere;
        $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->matiere)->where('school_year_id', $this->year)->first();
            if($exist){
                $exist->update([
                    'rang_annuel' => $item['rang'],
                    'moyenne_annuel' => $item['moyen']
                ]); 
            }
        }
    }


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


    private function calculMoyenne($item){
        $resut = MoyenneAnnuelleTrimestre::where('inscription_id', $item)->where('level_matter_id', $this->matiere)->where('school_year_id', $this->year)->first();
        return $this->moyenneObtenue($resut['moyenne_1'], $resut['moyenne_2'], $resut['moyenne_3']);
    }


    private function moyenneObtenue($moyenne1 = null, $moyenne2 = null, $moyenne3 = null)
    {
        $total = null; $coef = null;
        $total = ($this->verify($moyenne1) ? ($moyenne1 * 1):0) + ($this->verify($moyenne2) ? ($moyenne2 * 2):0) + ($this->verify($moyenne3) ? ($moyenne3 * 2):0);
        $coef = ($this->verify($moyenne1) ? 1:0) + ($this->verify($moyenne2) ? 2:0) + ($this->verify($moyenne3) ? 2:0);
        if($total && $coef){
            $moyen = $total ? number_format(($total / $coef), 2, '.', ' '):'nc';
        }
        return $total ? ($moyen < 10 ? '0'.$moyen:$moyen):'nc';
    }


    private function verify($valeur){
        return ($valeur != null && $valeur != 'nc') ? true:false;
    }
}

