<?php

namespace App\Imports;

use App\Models\Department;
use App\Models\Branch;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class ImportDepartment implements ToModel,WithHeadingRow 
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        $branch = (object)'';
        if(isset($row['branch_name']) && !empty($row['branch_name'])){
            // echo "1";
            $branch = Branch::select('id')->where(['name' => $row['branch_name']])->where(['status' => 'active'])->first();
            if(!$branch){
                session(['error' => 'No Branch Found In at least one record!']);
                return null;
            }
        }else{
            // echo "2";
            $branch->id = null;
        }

        // die('stop');

        $exist_data = Department::select('id')->where(['name' => $row['name'],'status' => 'active'])->first();
        
        $data = [];
        if($exist_data){
            session(['error' => 'Some Department is already available on records!']);
            // return null;
        }else{  
            $data = [
                'name' => $row['name'],
                'branch_id' => $branch->id,
                'email' => $row['email'],
                'number' => $row['number'],
                'authorised_person' => $row['authorised_person'],
                '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
            ];
        }

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