<?php

namespace App\Imports;

use App\Models\GetNote;
use App\Models\Evaluation;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class ListClassStudentNoteImport implements ToArray, WithHeadingRow 
{
    protected $class;
    protected $eval;

    public function __construct($class, $eval)
    {
        $this->class = $class;
        $this->eval = $eval;
    }

    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function array(array $data)
    {
        foreach($data as $item){
            $dts = explode('_', $item['id']);
            $note = Evaluation::find($dts[2]);
            if($this->compareId($dts[0], $dts[2]) && !$this->verifyData($dts[1], $dts[2])){
                $this->saveNote($item['note'], $dts[2], $dts[1], $note['notee']);
            }
        }
    }
    
    private function verifyData($student, $evaluation){
        $count = GetNote::where('inscription_id', $student)->where('evaluation_id', $evaluation)->count();
        return $count;
    }


    private function compareId($classid, $evalId){
        return (($classid == $this->class) && ($evalId == $this->eval)) ? true:false;
    }


    private function saveNote($note, $eval, $student, $sure){
        GetNote::create([
            'evaluation_id' => $eval,
            'inscription_id' => $student,
            'note' => $this->valueNot($note, $sure)
        ]);
    }
    

    private function valueNot($note, $sure){
        $result = 'nc';
        if(isset($note)){
            $result = ($note > (20*$sure)) ? 'nc':($note <= 9 ? '0'.$note:$note);
        }
        return $result;
    }

}
