<?php

namespace App\Imports;

use App\Models\Teammaster;
use App\Models\Sublead;
use App\Models\Branch;
use App\Models\Department;
use App\Models\Interiorcolor;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use DB;

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

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

    
            $data = [
                'lead_id' => $Lead->id,
                'name' => $row['sub_lead_source'],
                '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 = [];
        if(!empty($data)){
              $insurance = Sublead::create($data);
        }                
        return $insurance;
    }
}
