<?php

namespace App\Imports;

use App\Models\MultiUnit;
use App\Models\Product;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class MultiUnitsImport implements ToModel, WithHeadingRow
{
    protected $validProductIds;
    protected $processedCombinations;
    protected $successfulRows;
    protected $failedRows;

    public function __construct(&$successfulRows, &$failedRows)
    {
        $this->validProductIds = Product::pluck('id')->toArray();
        $this->processedCombinations = [];
        $this->successfulRows = &$successfulRows;
        $this->failedRows = &$failedRows;
    }

    /**
     * @param array $row
     *
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function model(array $row)
    {
        if (!in_array($row['product_id'], $this->validProductIds)) {
            $this->failedRows[] = [
                'row_data' => $row,
                'error' => 'Invalid product ID',
            ];
            return null;
        }

        if (empty($row['multi_unit_1'])) {
            $this->failedRows[] = [
                'row_data' => $row,
                'error' => 'multi_unit_1 is empty',
            ];
            return null;
        }

        $successfulUnits = [];
        $failedUnits = [];

        foreach ($row as $key => $value) {
            if (preg_match('/^multi_unit_\d+$/', $key) && !empty($value)) {
                $multiUnitData = explode('#', $value);

                if (count($multiUnitData) >= 5) {
                    if (!is_numeric($multiUnitData[1]) || !is_numeric($multiUnitData[2]) || !is_numeric($multiUnitData[3])) {
                        $failedUnits[] = [
                            'unit' => $value,
                            'error' => 'Invalid numeric values',
                        ];
                        continue;
                    }

                    $combinationKey = $row['product_id'] . '_' . $multiUnitData[0];

                    if (
                        !in_array($combinationKey, $this->processedCombinations) &&
                        !MultiUnit::where('product_id', $row['product_id'])
                            ->where('multi_unit', $multiUnitData[0])
                            ->exists()
                    ) {
                        $barcode = !empty($multiUnitData[4]) ? $multiUnitData[4] : null;

                        MultiUnit::create([
                            'product_id' => $row['product_id'],
                            'multi_unit' => $multiUnitData[0],
                            'multi_qty' => $multiUnitData[1],
                            'multi_purchase_price' => $multiUnitData[2],
                            'multi_selling_price' => $multiUnitData[3],
                            'multi_code' => $barcode,
                            'multi_sub_unit' => 1,
                        ]);

                        $this->processedCombinations[] = $combinationKey;
                        $successfulUnits[] = [
                            'unit' => $value,
                            'status' => 'Successfully added',
                        ];
                    } else {
                        $failedUnits[] = [
                            'unit' => $value,
                            'error' => 'Insufficient data',
                        ];
                    }
                } else {
                    $failedUnits[] = [
                        'unit' => $value,
                        'error' => 'Insufficient data',
                    ];
                }
            }
        }

        if (!empty($successfulUnits) || !empty($failedUnits)) {
            $this->successfulRows[] = [
                'row_data' => $row,
                'successful_units' => $successfulUnits,
                'failed_units' => $failedUnits,
            ];
        }

        return null;
    }
}
