<?php

namespace App\Imports;

use App\Models\MarksEntry;
use Maatwebsite\Excel\Concerns\ToModel;

class MarksEntryImport implements ToModel
{
    private $extraData;
    public function __construct($extraData)
    {
        $this->extraData = $extraData;
    }
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        static $firstRow = true;

        // Skip the first row
        if ($firstRow) {
            $firstRow = false;
            return null;
        }
        if(!empty($this->extraData['subject_part_id'])){
            MarksEntry::where('roll', $row['1'])
            ->where('session',$row['0'])
            ->where('class_id', $this->extraData['class_id'])
            ->where('exam_id', $this->extraData['exam_id'])
            ->where('group_id', $this->extraData['group_id'])
            ->where('subject_id', $this->extraData['subject_id'])
            ->where('subject_part_id',$this->extraData['subject_part_id'])
            ->delete();
        }else{
            MarksEntry::where('roll', $row['1'])
            ->where('session',$row['0'])
            ->where('class_id', $this->extraData['class_id'])
            ->where('exam_id', $this->extraData['exam_id'])
            ->where('group_id', $this->extraData['group_id'])
            ->where('subject_id', $this->extraData['subject_id'])
            ->delete();
        }

        return new MarksEntry([
            'session'=> $row['0'],
            'roll' => $row['1'],
            'cq' => $row['2'],
            'mcq' => $row['3'],
            'practical' => $row['4'],
            'class_id'=> $this->extraData['class_id'],
            'exam_id'=> $this->extraData['exam_id'],
            'group_id' => $this->extraData['group_id'],
            'subject_id' => $this->extraData['subject_id'],
            'subject_part_id' => $this->extraData['subject_part_id'],
        ]);
    }
}
