<?php

namespace App\Imports;

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

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

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


    public function array(array $data)
    {
        foreach($data as $vals){
            list($class, $item, $evuled) = explode('_', $vals['id']);
            $note = Evaluation::find($evuled);
            if($this->compared($class, $evuled) && !$this->verify($item, $evuled)){
                $this->saved($vals['note'], $evuled, $item, $note['notee']);
            }
        }
    }

    
    private function verify($student, $evaled){
        $count = GetNote::where('inscription_id', $student)->where('evaluation_id', $evaled)->count();
        return $count;
    }


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


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

    private function not($note, $notee = 1){
        $nots = 'nc';
        if(!blank($note)){
            if(is_int($note)){
                $nots = ($note <= (20 * $notee)) ? ($note < 10 ? '0'.$note:$note):'nc';
            }
            else{
                $not = str_replace([' ', ','], ['', '.'], $note);
                $nots = floatval($not) ? 
                (($note <= (20 * $notee)) ? 
                ($note < 10 ? '0'.$note:$note):'nc'):
                'nc';
            }
        }
        return $nots;
    }

}
