<?php

namespace App\Imports;

use App\Models\Product; // pastikan path sesuai model kamu
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Illuminate\Support\Collection;

class StockOpnameImport implements ToCollection, WithHeadingRow
{
    protected $results = [
        'successfulRows' => [],
        'failedRows' => [],
    ];

    public function collection(Collection $rows)
    {
        foreach ($rows as $row) {
            // Pastikan actual_qty ada
            if (empty($row['actual_qty'])) {
                continue;
            }

            $product = null;

            // Cari berdasarkan name_product
            if (!empty($row['name_product'])) {
                $product = Product::where('name', $row['name_product'])->first();
                if (!$product) {
                    $this->results['failedRows'][] = [
                        'row' => $row,
                        'error' => "Product with name '{$row['name_product']}' not found",
                    ];
                    continue;
                }
            }

            // Cari berdasarkan barcode
            elseif (!empty($row['barcode'])) {
                $product = Product::where('code', $row['barcode'])->first();
                if (!$product) {
                    $this->results['failedRows'][] = [
                        'row' => $row,
                        'error' => "Product with barcode '{$row['barcode']}' not found",
                    ];
                    continue;
                }
            } else {
                $this->results['failedRows'][] = [
                    'row' => $row,
                    'error' => 'Either name_product or barcode is required',
                ];
                continue;
            }

            $this->results['successfulRows'][] = [
                'product_id'     => $product->id,
                'product_name'   => $product->name,
                'qty'            => $product->qty,
                'actual_qty'     => $row['actual_qty'],
                'difference'     => $row['actual_qty'] - $product->qty,
                'unit'           => $product->unit,
            ];
        }
    }

    public function getResults()
    {
        return $this->results;
    }
}
