<?php

namespace App\Jobs;

use App\Models\Classe;
use App\Models\MoyenneSubMatter;
use App\Jobs\MoyenneFrenshCycle1Job;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

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

    protected $data, $classe, $matter, $cutting;
    public function __construct($data, $classe, $matter, $cutting)
    {
        $this->data = $data;
        $this->classe = $classe;
        $this->matter = $matter;
        $this->cutting = $cutting;
    }


    public function handle(): void
    {
        $i = 0; $dts = $this->data;
        while($i < sizeof($dts)) {
            $data = getClassement($dts[$i]);
            $this->setMoyenne($data, $i+1);
            $i++;
        }

        // Calcul de la Moyenne de Français 
        MoyenneFrenshCycle1Job::dispatch($this->classe, $this->matter, $this->cutting)->delay(now()->addSeconds(1));
    }


    private function setMoyenne($data, $i){
        foreach($data as $item) {
            $exist = MoyenneSubMatter::where('inscription_id', $item['id'])->where('sub_matter_id', $i)->where('cutting_school_year_id', $this->cutting)->first();
            if($exist) {
                $exist->update([
                    'rang' => $item['rang'],
                    'moyenne' => $item['moyen']
                ]);
            }
            else{
                $this->saveMoyenne($item['id'], $item['rang'], $item['moyen'], $i);
            }
        }
    }

    private function saveMoyenne($item, $rang, $moyen, $sub) {
        MoyenneSubMatter::create([
            'rang' => $rang,
            'moyenne' => $moyen,
            'sub_matter_id' => $sub,
            'inscription_id' => $item,
            'coefficient' => $this->coeff($sub),
            'cutting_school_year_id' => $this->cutting
        ]);
    }

    private function coeff($sub) {
        $class = Classe::find($this->classe);
        if(in_array($class['level_id'], [12, 13]) && $sub == 1){
            $coef = 2;
        }
        return $coef ?? 1;
    }
}
