<?php

namespace App\Imports;

use Maatwebsite\Excel\Concerns\ToModel;
use Session;

class ImportDepartment implements ToModel
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {   
        if ($row[0] != 'Department Name (required field)' && 
            $row[1] != 'Description' && 
            $row[2] != 'Page Break (Yes/No)' && 
            $row[3] != 'Status (Active/Inactive)' ) {

            if ($row[0] != ''){

                if ($row[2] == '' || $row[2] == 'Yes' || $row[2] == 'No') {

                    if ($row[3] == '' || $row[3] == 'Active' || $row[3] == 'Inactive'){
                        $department_data = Session::get('DepartmentData');
                        $exist_department_name = array_column($department_data, 0);

                        if (in_array($row[0], $exist_department_name)){
                            $row['status'] = 'duplicate';
                            $department_data[] = $row;

                            Session::put('DepartmentData', $department_data);
                        } else {
                            $row['status'] = true;
                            $department_data[] = $row;

                            Session::put('DepartmentData', $department_data);
                        }
                    } else {
                        throw new \Exception('Invalid Status.');
                    }
                } else {
                    throw new \Exception('Invalid Page break.');
                }
            } else {
                throw new \Exception('Department name is required.');
            }
        }

        return;
    }
}