<?php

namespace App\Imports;

use App\Models\Classe;
use App\Models\PrimaryNote;
use App\Models\LevelPrimaryMatters;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\OnFailure;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class NotePrimaireImport implements ToArray, WithHeadingRow 
{

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

    /**
    * @param Collection $collection
    */
    public function array(array $data)
    {
        $class = Classe::where('id', $this->classe)->first();
        $matter = $this->getMatters($class['level_id']);
        foreach($data as $item){
            $eval = explode('_', $item['id']);
            if($eval[0] == $class['id'] && $eval[2] == $this->evaluated){
                $i = 0; 
                while($i < sizeof($matter)){
                    $this->saveItem($eval[1], $eval[2], explode('-',$matter[$i])[0], $item[explode('-',$matter[$i])[1]]);
                    $i++;
                }
            }
        }
    }


    private function getMatters($levelId)
    {
        $matters = LevelPrimaryMatters::where('level_id', $levelId)->get();
        $table = [
            'Lecture' => 'lecture',
            'Ecriture' => 'ecriture',
            'Français (Expression ecrite + Orthographe)' => 'francais_expression_ecrite_orthographe',
            'Dictée' => 'dictee',
            'Dessin' => 'dessin',
            'Poésie/Chant' => 'poesiechant',
            'Mathématique' => 'mathematique',
            'Exploitation de texte' => 'exploitation_de_texte',
            'Eveil au milieu' => 'eveil_au_milieu',
            'EDHC' => 'edhc',
            'Copie' => 'copie',
            'Expression ecrite' => 'expression_ecrite'
        ];
        $tabs = [];
        foreach($matters as $matter){
            $tabs[] = $matter->id.'-'.$table[$matter->primary_matter->libelle];
        }
        return $tabs;
    }


    private function saveItem($student, $evaluated, $matter, $note)
    {
        $exist = $this->verifyItem($student, $evaluated, $matter);
        if($exist){
            $exist->update([
                'note' => blank($note) ? 'nc':($note <= 9 ? '0'.$note:$note),
            ]);
        }
        else{
            PrimaryNote::create([
                'inscription_id' => $student,
                'evaluated_level_id' => $evaluated,
                'level_primary_matter_id' => $matter,
                'note' => blank($note) ? 'nc':($note <= 9 ? '0'.$note:$note),
            ]);
        }
    }


    private function verifyItem($student, $evaluated, $matter)
    {
        $exist = PrimaryNote::where('inscription_id', $student)->where('evaluated_level_id', $evaluated)->where('level_primary_matter_id', $matter)->first();
        return $exist ?? null;
    }
}
