<?php

namespace App\Imports;

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

class ImportTestItem implements ToModel
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        if ($row[0] != 'Test Name (required)' && 
            $row[1] != 'Test Type (TEST_ITEM, TEST_COMMENT_FOR_TECHNICIAN, TEST_LABEL)' && 
            $row[2] != 'Test Unit (required)' && 
            $row[3] != 'Result Input Type (NUMBER, TEXT, TIME, SUMMER_NOTE, IMAGE, PDF)' && 
            $row[4] != 'Status (Active/Inactive)' ) {

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

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

            		if ($row[1] == '' || $row[1] == 'TEST_ITEM' || $row[1] == 'TEST_COMMENT_FOR_TECHNICIAN' || $row[1] == 'TEST_LABEL') {

            			if ($row[3] == '' || 
            				$row[3] == 'NUMBER' || 
            				$row[3] == 'TEXT' || 
            				$row[3] == 'TIME' || 
            				$row[3] == 'SUMMER_NOTE' || 
            				$row[3] == 'IMAGE' || 
            				$row[3] == 'PDF') {

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

			                    $test_items_data = Session::get('TestItemsData');
			                    $exist_test_item_name = array_column($test_items_data, 0);

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

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

			                        Session::put('TestItemsData', $test_items_data);
			                    }
			                } else {
			                    throw new \Exception('Invalid Status.');
			                }
		                } else {
			                throw new \Exception('Invalid Result Input Type.');
			            }

	                } else {
		                throw new \Exception('Invalid Test Type.');
		            }
                } else {
	                throw new \Exception('Test Unit is required.');
	            }
            } else {
                throw new \Exception('Test Name is required.');
            }
        }

        return;
    }
}