<?php

namespace App\Jobs;

use App\Models\MoyenneAnnuelleBilan;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

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

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

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $dts = getClassement($this->getMoyenne());
        foreach($dts as $item){
            $exist = MoyenneAnnuelleBilan::where('inscription_id', $item['id'])->where('libelle_bilan_id', $this->bilan)->where('school_year_id', $this->year)->first();
            if($exist){
               $exist->update([
                    'rang_annuel' => $item['rang'],
                    'bilan_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 = MoyenneAnnuelleBilan::where('inscription_id', $item)->where('libelle_bilan_id', $this->bilan)->where('school_year_id', $this->year)->first();
        return $this->moyenneObtenue($resut['bilan_1'], $resut['bilan_2'], $resut['bilan_3']);
    }


    private function moyenneObtenue($bilan1 = null, $bilan2 = null, $bilan3 = null)
    {
        $total = null; $coef = null;
        $total = ($this->verify($bilan1) ? ($bilan1 * 1):0) + ($this->verify($bilan2) ? ($bilan2 * 2):0) + ($this->verify($bilan3) ? ($bilan3 * 2):0);
        $coef = ($this->verify($bilan1) ? 1:0) + ($this->verify($bilan2) ? 2:0) + ($this->verify($bilan3) ? 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;
    }
}
