<?php

namespace App\Imports;

use App\Models\Teammaster;
use App\Models\Carmodel;
use App\Models\Branch;
use App\Models\Department;
use App\Models\CarExchangeProduct;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use DB;

class ImportCarExchangeProduct implements ToModel ,WithHeadingRow
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function startRow(): int
    {
        return 6;
    }
    public function model(array $row)
    {
        $car_exchange_category = (object)'';
        if(isset($row['category_name']) && !empty($row['category_name'])){
            $car_exchange_category = DB::table('car_exchange_category')->where(['name' => $row['category_name']])->first();
            if(!$car_exchange_category){
                session(['error' => 'No Category Name Found on records!']);
                return null;
            }
        }else{
            $car_exchange_category->id = null;
        }

        $exist_data = CarExchangeProduct::select('id')->where(['name' => $row['name'],'category_id' => $car_exchange_category->id,'status' => 'active'])->first();
                
        $data = [];
        if($exist_data){
            session(['error' => 'Some CarExchangeProduct is already available on records!']);
            // return null;
        }else{  

            $data = [
                'name' => $row['name'],
                'category_id' => $car_exchange_category->id,
                '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
            ];
        }
        // die($data);

        /*$insurance = CarExchangeProduct::create($data);
        return $insurance;*/

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