<?php

namespace App\Imports;

use App\Models\Bed;
use App\Models\BedGroup;
use App\Models\BedType;
use App\Models\Building;
use App\Models\Floor;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;

class BedsImport implements  ToModel , WithStartRow
{
    protected $request;
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function __construct(Request $request)
    {
        $this->request = $request;
    }
    public function model(array $row)
    {
        ini_set('max_execution_time', 500);
        $data = \Session::get('beds_import') ?? [];

        if (empty($row[0])) {
            return null;
        }

        $company  = $this->request->input(['company_id']);
        $bedType  = BedType::firstOrCreate(['name' => $row[2]]);
        $bedGroup = BedGroup::firstOrCreate(['name' => $row[3]]);
        $floor    = Floor::firstOrCreate(['name' => $row[5]]);
        $building = Building::firstOrCreate(['name' => $row[6]]);


        $existingRecord = Bed::where('name', $row[0])->first();

        if ($existingRecord) {
            $data['errorImport'] = $data['errorImport'] + 1;
            \Session::put('beds_import', $data);

            return null;
        }

        $data['successImport'] =  $data['successImport'] + 1;

        \Session::put('beds_import', $data);

        return new Bed([
            'name'          => $row[0],
            'company_id'    => $company ??  null,
            // 'patient_id' => $row[1] ?: NULL,
            'bed_type_id'   => $bedType->id ?? null,
            'bed_group_id'  => $bedGroup->id ?: NULL,
            'room_id'       => $row[4],
            'floor_id'      => $floor->id ?: NULL,
            'building_id'   => $building->id ?: NULL,
        ]);
    }

    public function startRow(): int
    {
        return 2;
    }
}
