<?php

namespace App\Imports;

use Maatwebsite\Excel\Concerns\ToModel;
use Illuminate\Support\Facades\Log;
use Session;

class ImportPackage implements ToModel
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {

        if ($row[0] != 'Package Name (required field)' && 
            $row[1] != 'Department Name (required field)' && 
            $row[2] != 'Sample Type (required field)' && 
            $row[3] != 'Short Name' && 
            $row[4] != 'Package Code' && 
            $row[5] != 'Priority' && 
            $row[6] != 'Page Break (Yes/No)' && 
            $row[7] != 'Status (Active/Inactive)' ) {

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

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

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

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

                            if ($row[5] == '' || is_int($row[5])){

                                if ($row[7] == '' || $row[7] == 'Active' || $row[7] == 'Inactive'){
                                    $package_data = Session::get('PackageData');
                                    $exist_package_name = array_column($package_data, 0);

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

                                        Session::put('PackageData', $package_data);

                                    } else {
                                        $row['status'] = true;
                                        $package_data[] = $row;

                                        Session::put('PackageData', $package_data);
                                    }
                                } else {
                                    throw new \Exception('Invalid Status.');
                                }
                            } else {
                                throw new \Exception('Invalid Priority.');
                            }
                        } else {
                            throw new \Exception('Invalid Page break.');
                        }
                    } else {
                        throw new \Exception('Sample Type is required.');
                    }
                } else {
                    throw new \Exception('Department name is required.');
                }
            } else {
                throw new \Exception('Package name is required.');
            }
        }

        return;
    }
}