<?php

namespace App\Imports;

use App\Models\Product;
use App\Models\Unit;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\SkipsOnFailure;
use Maatwebsite\Excel\Concerns\SkipsFailures;
use Illuminate\Support\Facades\Validator;

class ProductsImport implements ToModel, WithHeadingRow
{
    use SkipsFailures;

    protected $units;
    protected $existingNames;
    protected $existingBarcodes;
    protected $processedNames;
    protected $processedBarcodes;
    protected $versi;
    public $successfulRows = [];
    public $failedRows = [];

    public function __construct($versi = null)
    {
        $this->versi = $versi;
        $this->units = Unit::pluck('id')->toArray();
        $this->existingNames = Product::pluck('name')->toArray();
        $this->existingBarcodes = Product::pluck('code')->toArray();
        $this->processedNames = [];
        $this->processedBarcodes = [];
    }

    public function model(array $row)
    {
        $kategori = strtolower(trim($row['kategori'] ?? ''));
        if (in_array($kategori, ['produk', 'product', 'merchandise', 'barang dagangan', 'barang', 'item'])) {
            $row['kategori'] = 'product';
        } elseif (in_array($kategori, ['jasa', 'service'])) {
            $row['kategori'] = 'service';
        } elseif (in_array($kategori, ['bahan baku', 'raw material'])) {
            $row['kategori'] = 'product_materials';
        } elseif (in_array($kategori, ['barang jadi', 'finished goods'])) {
            $row['kategori'] = 'product_finished';
        }

        if ($this->versi && strtolower($this->versi) === 'pro') {
            if (in_array($row['kategori'] ?? '', ['product_materials', 'product_finished'], true)) {
                $this->failedRows[] = ['row' => $row, 'errors' => ['Kategori tidak didukung untuk versi Pro']];
                return null;
            }
        }

        // --- Normalisasi harga_khusus ---
        $hargaKhusus = strtolower(trim($row['harga_khusus'] ?? ''));
        if (!in_array($hargaKhusus, ['harga_contact', 'harga_grosir'])) {
            $row['harga_khusus'] = 'harga_contact';
        } else {
            $row['harga_khusus'] = $hargaKhusus;
        }

        $validator = Validator::make($row, [
            'satuan_dasar' => 'required|in:' . implode(',', $this->units),
            'kategori' => 'required|in:product,service',
            'harga_khusus' => 'required|in:harga_contact,harga_grosir',
            'nama_produk' => 'required|unique:products,name',
            'barcode' => 'nullable|unique:products,code',
        ]);

        if ($validator->fails()) {
            $this->failedRows[] = ['row' => $row, 'errors' => $validator->errors()->all()];
            return null;
        }

        // Validasi duplikat internal
        if (in_array(strtolower($row['nama_produk']), $this->processedNames)) {
            $this->failedRows[] = ['row' => $row, 'errors' => ['Duplicate product name in file']];
            return null;
        }

        if (isset($row['barcode']) && in_array($row['barcode'], $this->processedBarcodes)) {
            $this->failedRows[] = ['row' => $row, 'errors' => ['Duplicate barcode in file']];
            return null;
        }

        $this->processedNames[] = strtolower($row['nama_produk']);
        if (isset($row['barcode'])) {
            $this->processedBarcodes[] = $row['barcode'];
        }

        $this->successfulRows[] = $row;

        // Buat object Product manual
        $product = new Product();
        $product->name = $row['nama_produk'];
        $product->unit = $row['satuan_dasar'];
        $product->purchase_price = $row['harga_beli'] ?? 0;
        $product->selling_price = $row['harga_jual'];
        $product->producttype = $row['jenis_produk'] ?? 1;
        $product->code = $row['barcode'] ?? null;
        $product->category = $row['kategori'];
        $product->pricing_schema = $row['harga_khusus'];
        $product->qty = $row['kategori'] === 'service' ? 1000000 : 0;
        $product->product_image = null;
        $product->display_rack_v2 = $row['etalase'] ?? null;
        $product->qty_minimum = $row['jumlah_minimum'] ?? null;
        $product->profit_strategy = 'manual';
        $product->for_sale = 1;
        $product->for_purchase = 1;

        // Simpan ke database
        $product->save();

        return $product;
    }

    public function getResults()
    {
        return [
            'successfulRows' => $this->successfulRows,
            'failedRows' => $this->failedRows,
        ];
    }
}
