<?php

namespace App\Imports;

use App\Models\RSA;
use App\Models\Carmodel;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class ImportRSA implements ToModel ,WithHeadingRow
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function startRow(): int
    {
        return 6;
    }
    
    public function model(array $row)
    {
        $Car_model = (object)'';
        if(isset($row['car_model']) && !empty($row['car_model'])){
            $Car_model = Carmodel::select('id')->where(['name' => $row['car_model']])->first();
            if(!$Car_model){
                session(['error' => 'No Car Model Found In at least one record!']);
                return null;
            }
        }else{
            $Car_model->id = null;
        }

        $exist_data = RSA::select('id')->where(['name' => $row['name'],'status' => 'active'])->first();
        
        $data = [];
        if($exist_data){
            session(['error' => 'Some RSA is already available on records!']);
            // return null;
        }else{  
            $data = [
                'name' => $row['name'],
                'car_model' => $Car_model->id,
                'years' => $row['year'],
                'amount'          => isset($row['amount']) ? $row['amount'] : null,
                'profit'          => isset($row['profit']) ? $row['profit'] : null,
                'gst_percentage'  => isset($row['gst']) ? $row['gst'] : null,
                'gst'             => isset($row['gst_amount']) ? $row['gst_amount'] : null,
                'total_profit'    => isset($row['total_profit']) ? $row['total_profit'] : null,
                'status' => 'active',
                'created_at' => date('Y-m-d H:i:s'),
                'created_by' => auth()->user()->id,
                'updated_at' => date('Y-m-d H:i:s'),
                'updated_by' => auth()->user()->id
            ];
        }

        $insurance = [];
        if(!empty($data)){
             $insurance = RSA::create($data);
        }        
        return $insurance; 
    }
}
