<?php

namespace App\Imports;

use App\Models\AbsenceGet;
use App\Events\ConduiteEvent;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class ConduiteImport implements ToArray, WithHeadingRow
{
    protected $class, $cutting, $matter;
    public function __construct($class, $cutting, $matter)
    {
        $this->class = $class;
        $this->cutting = $cutting;
        $this->matter = $matter;
    }


    public function array(array $data)
    {
        $table = [];
        foreach($data as $item){
            list($class, $cutting, $id) = explode('_', $item['num']);
            if(($class == $this->class) && ($cutting == $this->cutting)){
                $table[] = [
                    'id' => $id,
                    'sexe' => $item['sexe'],
                    'moyen' => formatMoyenne($item['moyenne'])
                ];
                $this->getAbsence($id, $item['nbre_heure_justifie'], $item['nbre_heure_non_justifie']);
            }
        }
        
        event(new ConduiteEvent($table, $this->matter, $this->cutting));
    }


    private function getAbsence($id, $justify, $nonJustify){

        $exist = AbsenceGet::where('inscription_id', $id)->where('cutting_school_year_id', $this->cutting)->first();
        if($exist){
            $exist->update([
                'justify' => is_int($justify) ? $justify:0,
                'non_justify' => is_int($nonJustify) ? $nonJustify:0,
                'nbre_totals' => $this->totale($justify, $nonJustify)
            ]);
        }
        else{
            AbsenceGet::create([
                'justify' => is_int($justify) ? $justify:0,
                'non_justify' => is_int($nonJustify) ? $nonJustify:0,
                'nbre_totals' => $this->totale($justify, $nonJustify),
                'inscription_id' => $id,
                'cutting_school_year_id' => $this->cutting
            ]);
        }
    }


    private function totale($nmbre1, $nmbre2){
        $nbre1 = is_int($nmbre1) ? $nmbre1:0;
        $nbre2 = is_int($nmbre2) ? $nmbre2:0;
        return ($nbre1+$nbre2);
    }
}