<?php

namespace App\Imports;

use App\Models\IncentiveSlabDetail;
use App\Models\Product;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Illuminate\Http\Request;

class IncentiveSlabDetailsImport 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)
    {
        $incentive_slab = $this->request->input('incentive_slab');
        $product = Product::where(['name' => $row[0]])->first();
    
        if (!$product) {
            return;
        }
    
        $calculation_type = $row[2];
        $value = $row[3];
        $update = [];
        $update['calculation_type'] = $calculation_type;

        if ($calculation_type == 'percentage') {
            $update['percentage'] = $value;
            $update['price'] = '';
        } else {
            $update['price'] = $value;
            $update['percentage'] = '';
        }
    
        $incentiveSlabDetail = IncentiveSlabDetail::updateOrCreate(
            ['product_id' => $product->id, 'slab_id' => $incentive_slab],
            $update
        );
    
        return $incentiveSlabDetail;
    }

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