<?php

namespace App\Imports;

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

class ImportMcp implements ToModel ,WithHeadingRow
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function startRow(): int
    {
        return 6;
    }
    public function model(array $row)
    {
        /*echo "<pre>";
        print_r($row);
        die('s');*/

        $Carmodel = (object)'';
        if(isset($row['car_model']) && !empty($row['car_model'])){
            $Carmodel = Carmodel::select('id')->where(['name' => $row['car_model']])->first();
            if(!$Carmodel){
                session(['error' => 'No Car Model Found on records!']);
                return null;
            }
        }else{
            $Carmodel->id = null;
        }

        $exist_data = Mcp::select('id')->where(['name' => $row['name'],'status' => 'active'])->first();
        
        $data = [];
        if($exist_data){
            session(['error' => 'Some Mcp is already available on records!']);
            // return null;
        }else{ 


            $data = [
                'name' => $row['name'],
                'car_model' => $Carmodel->id,
                '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
            ];
        }

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

       /* $insurance = Mcp::create($data);
        return $insurance;*/
    }
}
