<?php

namespace App\Imports;

use App\Models\ExtandWarranty;
use App\Models\Carmodel;
use App\Models\Fuletype;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class ImportExtandWarranty implements ToModel, WithHeadingRow 
{
    /**
     * @param array $row
     *
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function model(array $row)
    {
        // Check if 'car_model' key exists and is not empty
        $carModel = null;
        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;
            }
        }

        $fuelType = null;
        if (isset($row['fule_type']) && !empty($row['fule_type'])) {
            $fuelType = Fuletype::select('id')->where(['title' => $row['fule_type']])->first();
            if (!$fuelType) {
                session(['error' => 'No Fuel Type Found In at least one record!']);
                return null;
            }
        }

        $existData = ExtandWarranty::where(['amount' => $row['amount'], 'status' => 'active'])->exists();

        if ($existData) {
            session(['error' => 'Some Extended Warranty is already available in records!']);
            // return null;
        }

        // Prepare data for creating a new record
        $data = [
            'years' => $row['years'],
            'car_model' => optional($carModel)->id,
            'fule_type' => optional($fuelType)->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' => now(),
            'created_by' => auth()->user()->id,
            'updated_at' => now(),
            'updated_by' => auth()->user()->id,
        ];

        $extendedWarranty = ExtandWarranty::create($data);

        return $extendedWarranty;
    }
}
