<?php

namespace App\Imports;

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

class ImportCarExchange 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;
        }

        $car_exchange_product = (object)'';
        if(isset($row['product_name']) && !empty($row['product_name'])){
            $car_exchange_product = DB::table('car_exchange_product')->where(['name' => $row['product_name']])->first();
            if(!$car_exchange_product){
                session(['error' => 'No Product Name Found on records!']);
                return null;
            }
        }else{
            $car_exchange_product->id = null;
        }


        $exist_data = CarExchange::select('id')->where(['category_id' => $car_exchange_category->id,'product_id' => $car_exchange_category->id,'status' => 'active'])->first();
                
        $data = [];
        if($exist_data){
            session(['error' => 'Some CarExchange is already available on records!']);
            // return null;
        }else{  
            $data = [
                'category_id' => $car_exchange_category->id,
                'product_id' => $car_exchange_category->id,
                'engine_number' => $row['engine_number'],
                'chassis_number' => $row['chassis_number'],
                'price' => $row['price'],
                '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
            ];
        }

        /*echo "<pre>";
        print_r($data);
         die();*/

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

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