<?php

namespace App\Imports;

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

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

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

                if ($row[2] == '' || $row[2] == 'Active' || $row[2] == 'Inactive') {

                    $primary_units_data = Session::get('PrimaryUnitsData');
                    $exist_primary_unit_name = array_column($primary_units_data, 0);

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

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

                        Session::put('PrimaryUnitsData', $primary_units_data);
                    }
                } else {
                    throw new \Exception('Invalid Status.');
                }
            } else {
                throw new \Exception('Primary Unit name is required.');
            }
        }

        return;
    }
}