<?php

namespace App\Imports;

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

class ImportExteriorcolor implements ToModel ,WithHeadingRow
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function startRow(): int
    {
        return 6;
    }
    
    public function model(array $row)
    {
        $Toneselection = (object)'';
        if(isset($row['tone_selection']) && !empty($row['tone_selection'])){
            $Toneselection = Colortone::select('id')->where(['name' => $row['tone_selection']])->first();
            if(!$Toneselection){
                /*session(['error' => 'No Branch Found In at least one record!']);
                return null;*/

                // echo "---";
                $crud = [
                    'name' => $row['tone_selection'],
                    '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
                ];
                $Toneselection = (object)'';
                     // DB::enableQueryLog();
                $Toneselection->id = Colortone::insertGetId($crud);     
                     // dd(DB::getQueryLog());           
            }
        }else{
            $Toneselection->id = null;
        }
        
        $exist_data = Exteriorcolor::select('id')->where(['name' => $row['name'],'tone_selection' => $Toneselection->id,'status' => 'active'])->first();
                
        $data = [];
        if($exist_data){
            session(['error' => 'Some Exteriorc olor is already available on records!']);
            // return null;
        }else{
            $data = [
                'name' => $row['name'],
                'tone_selection' => $Toneselection->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
            ];
        }

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

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