<?php

namespace App\Imports;

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

class ImportCNGKit 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 = CNGKit::select('id')->where(['name' => $row['name'],'amount' => $row['amount'],'company' => $row['company'],'kg' => $row['kg'],'status' => 'active'])->first();
                
        $data = [];
        if($exist_data){
            session(['error' => 'Some cng kit is already available on records!']);
        } else {
            $data = [
                'name' => $row['name'],
                'amount' => $row['amount'],
                'company' => $row['company'],
                'kg' => $row['kg'],
                '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
            ];
        }

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