<?php

namespace App\Imports;

use App\Models\Coating;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use DB;

class ImportCoating implements ToModel ,WithHeadingRow
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function startRow(): int
    {
        return 6;
    }
    
    public function model(array $row)
    {        
        $exist_data = Coating::select('id')->where(['name' => $row['name'],'amount' => $row['amount'],'status' => 'active'])->first();
                
        $data = [];
        if($exist_data){
            session(['error' => 'Some coating is already available on records!']);
        } else {
            $data = [
                'name' => $row['name'],
                'amount' => $row['amount'],
                'status' => 'active',
                'created_at' => date('Y-m-d H:i:s'),
                'created_by' => auth()->user()->id,
                'updated_at' => date('Y-m-d H:i:s'),
                'updated_by' => auth()->user()->id
            ];
        }

        $coating = [];
        if(!empty($data)){
             $coating = Coating::create($data);
        }        
        return $coating;      
    }
}
