<?php

namespace App\Jobs;

use App\Models\Classe;
use App\Models\LevelMatter;
use App\Models\MoyenneTrimestrielle;
use App\Models\MoyenneDecoupageMatiere;
use App\Jobs\DistinctionJob;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

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

    protected $student;
    protected $classId; 
    protected $decoupId;
    protected $school;

    /**
     * Create a new job instance.
     */
    public function __construct($student, $classId, $decoupId, $school)
    {
        $this->student = $student;
        $this->classId = $classId;
        $this->decoupId = $decoupId;
        $this->school = $school;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $dts = getClassement($this->getMoyenne($this->student));
        foreach($dts as $item){
            $exist = MoyenneTrimestrielle::where('inscription_id', $item['id'])->where('cutting_school_year_id', $this->decoupId)->where('school_id', $this->school)->first();
            if($exist){
                $exist->update([
                    'moyenne' => $item['moyen'], 
                    'rang' => $item['rang'],
                    'coeffs' => $item['coeff'],
                    'points' => $item['point'],
                ]);
            }
            else{
                $this->saveData($item['id'], $item['moyen'], $item['rang'], $item['coeff'], $item['point']);
            }
        }

        // Declanchement de Job -----------------
        if($this->school == 1){ // Groupe Scolaire La Rochelle id = 1
            DistinctionJob::dispatch($this->school, $this->decoupId)->delay(now()->addSeconds(1));
        }
    }


    protected function getMoyenne($students)
    {
        $tabeau = [];
        foreach ( $students as $item) {
            $val = $this->calculMoyenne($item->id);
            $tabeau[] = [
                'id' => $item->id,
                'sexe' => $item->sexe,
                'moyen' => $val['moyen'],
                'point' => $val['point'],
                'coeff' => $val['coeff']
            ];
        }
        return $tabeau;
    }


    protected function calculMoyenne($id)
    {
        $point = 0; $coefs = 0; $exist = false;
        $class = Classe::where('id', $this->classId)->first();
        $vals = MoyenneDecoupageMatiere::where('inscription_id', $id)->where('cutting_school_year_id', $this->decoupId)->get();
        foreach($vals as $val){
            $coef = $this->getCoeff($val['level_matter_id'], $class['level_id'], $class['serie_id'], $class['type']);
            if($val['moyenne'] != 'nc'){
                $point += ($val['moyenne'] * $coef); $coefs += $coef; $exist = true;
            }
        }
        $moyen = $exist ? ($point ? number_format(($point / $coefs), 2, '.', ' '):'0'):'nc';
        return ['point' => $point, 'coeff' => $coefs, 'moyen' => $exist ? ($moyen < 10 ? '0'.$moyen:$moyen):$moyen];
    }


    protected function getCoeff($matter, $level, $serie = null, $type)
    {
        $coeff = LevelMatter::where('id', $matter)->where('level_id', $level)->where('type', $type)->where('school_id', $this->school)->first();
        return $coeff->coefficient->valeur;
    }


    protected function saveData($student, $moyen, $rang, $coeff, $point)
    {
        MoyenneTrimestrielle::create([
            'rang' => $rang,
            'moyenne' => $moyen,
            'coeffs' => $coeff,
            'points' => $point,
            'inscription_id' => $student,
            'school_id' => $this->school,
            'cutting_school_year_id' => $this->decoupId
        ]);
    }
}
