<?php

namespace App\Imports;

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

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

        $Department = (object)'';
        if(isset($row['department']) && !empty($row['department'])){
            $Department = Department::select('id')->where(['name' => $row['department']])->first();
            if(!$Department){
                session(['error' => 'No Department Found In at least one record!']);
                return null;
            }
        }else{
            $Department->id = null;
        }

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

            $data = [
                'team_name' => $row['name'],
                'branch_name' => $branch->id,
                'department' => $Department->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
            ];
        }

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

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