<?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 CapitalImport implements ToCollection, WithHeadingRow
{
    protected $results = [
        'successfulRows' => [],
        'failedRows' => [],
    ];

    public function collection(Collection $rows)
    {
        if (!isset($rows->first()['id_produk'])) {
            $this->results['failedRows'][] = [
                'row' => [],
                'error' => 'Column id_produk is required but missing in the import file'
            ];
            return;
        }

        foreach ($rows as $row) {
            if (empty($row['qty'])) {
                continue;
            }

            // Validasi ID produk
            if (!is_numeric($row['id_produk']) || $row['id_produk'] <= 0) {
                $this->results['failedRows'][] = [
                    'row' => $row,
                    'error' => 'Invalid product ID'
                ];
                continue;
            }

            // Ambil produk dari database
            $product = Product::find($row['id_produk']);

            if (!$product) {
                $this->results['failedRows'][] = [
                    'row' => $row,
                    'error' => 'Product not found'
                ];
                continue;
            }

            // Ambil purchase_price dari produk
            $purchase_price = $product->purchase_price ?? 0;

            $this->results['successfulRows'][] = [
                'product_id' => $row['id_produk'],
                'qty' => $row['qty'],
                'purchase_price' => $purchase_price,
                'total' => $purchase_price * $row['qty'],
            ];
        }
    }

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