<?php

namespace App\Imports;

use App\Models\Product;
use App\Models\ProductPrice;
use App\Models\Category;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class ProductsImport implements ToCollection, WithHeadingRow
{
    public function collection(Collection $rows)
    {
        foreach ($rows as $row) {
            // Lewati jika nama produk kosong
            if (!isset($row['name']) || empty($row['name'])) continue;

            DB::transaction(function () use ($row) {
                
                // 1. LOGIC KATEGORI
                $categoryId = null;
                if (!empty($row['category'])) {
                    $cat = Category::firstOrCreate([
                        'name' => trim($row['category'])
                    ]);
                    $categoryId = $cat->id;
                }

                // --- HELPER KHUSUS PEMBERSIH ANGKA ---
                $cleanDecimal = function($val) {
                    return (isset($val) && $val !== '') ? $val : null;
                };
                
                $buyPrice = (isset($row['buy_price']) && $row['buy_price'] !== '') ? $row['buy_price'] : 0;
                // -------------------------------------

                // 2. SIAPKAN DATA DASAR
                $commonData = [
                    'name'              => $row['name'],
                    'category_id'       => $categoryId,
                    'is_active'         => 1,
                    'unit'              => $row['unit'] ?? 'Pcs',
                    'buy_price'         => $buyPrice,
                    'buy_unit'          => $row['buy_unit'] ?? null,
                    'conversion_factor' => $cleanDecimal($row['conversion_factor'] ?? null),
                    'unit_3_name'       => $row['unit_3_name'] ?? null,
                    'conversion_3_qty'  => $cleanDecimal($row['conversion_3_qty'] ?? null),
                    'unit_4_name'       => $row['unit_4_name'] ?? null,
                    'conversion_4_qty'  => $cleanDecimal($row['conversion_4_qty'] ?? null),
                ];

                $targetProduct = null;

                // 3. CEK: APAKAH INI VARIAN?
                if (!empty($row['variant_name'])) {
                    // === LOGIC PRODUK VARIAN ===
                    
                    // A. Cari atau Buat Induk
                    // PENTING: Induk TIDAK BOLEH punya variant_group_id agar muncul di List
                    $parent = Product::firstOrCreate(
                        ['name' => $row['name'], 'variant_name' => null], 
                        array_merge($commonData, [
                            'sku' => null, // Induk varian biasanya tidak butuh SKU fisik
                            'variant_group_id' => null // FORCE NULL AGAR MUNCUL DI LIST
                        ])
                    );

                    // B. Tentukan Group ID untuk Anak (Pakai format: VAR-ID_INDUK)
                    $groupId = 'VAR-' . $parent->id;

                    // C. Siapkan SKU Anak
                    // Loop sampai nemu yang belum ada (Paling Aman)
                    if (empty($row['sku'])) {
                        do {
                            $sku = 'BRG' . date('ymd') . mt_rand(1000, 9999);
                        } while (Product::where('sku', $sku)->exists());
                    } else {
                        $sku = $row['sku'];
                    }
                    
                    // D. Buat Anak (Varian)
                    $targetProduct = Product::updateOrCreate(
                        [
                            'variant_group_id' => $groupId, 
                            'variant_name' => $row['variant_name']
                        ],
                        array_merge($commonData, [
                            'sku' => $sku,
                            'variant_group_id' => $groupId, // Hanya anak yang pegang ID Group
                            'variant_name' => $row['variant_name']
                        ])
                    );

                } else {
                    // === LOGIC PRODUK BIASA (SIMPLE) ===
                    $sku = $row['sku'] ?? 'BRG' . date('ymd') . mt_rand(1000, 9999);
                    
                    $targetProduct = Product::updateOrCreate(
                        ['name' => $row['name'], 'variant_name' => null],
                        array_merge($commonData, [
                            'sku' => $sku,
                            'variant_group_id' => null // Pastikan NULL
                        ])
                    );
                }

                // 4. ALOKASI CABANG (Penting agar user non-owner bisa lihat)
                if (isset($row['branch_ids']) && $row['branch_ids'] !== '') {
                    $branchIds = explode(',', $row['branch_ids']);
                    $targetProduct->branches()->sync($branchIds);
                } else {
                    $user = auth()->user();
                    if ($user && $user->branch_id) {
                        $targetProduct->branches()->syncWithoutDetaching([$user->branch_id]);
                    }
                }

                // 5. SIMPAN HARGA MATRIX
                ProductPrice::where('product_id', $targetProduct->id)->delete();

                $p = function($val) { return (isset($val) && $val !== '') ? $val : 0; };

                // Level 1 User
                $this->insertPriceRow($targetProduct->id, '1_user', $p($row['tier1_l1']??0), $p($row['tier1_l2']??0), $p($row['tier1_l3']??0), $p($row['tier1_l4']??0));
                // Level 2 User
                $this->insertPriceRow($targetProduct->id, '2_user', $p($row['tier2_l1']??0), $p($row['tier2_l2']??0), $p($row['tier2_l3']??0), $p($row['tier2_l4']??0));
                // Level 3 User
                $this->insertPriceRow($targetProduct->id, '3_user', $p($row['tier3_l1']??0), $p($row['tier3_l2']??0), $p($row['tier3_l3']??0), $p($row['tier3_l4']??0));
            });
        }
    }

    private function insertPriceRow($productId, $customerLevel, $p1, $p2, $p3, $p4)
    {
        if (!empty($p1)) ProductPrice::create(['product_id' => $productId, 'level' => $customerLevel, 'unit_level' => 1, 'amount' => $p1]);
        if (!empty($p2)) ProductPrice::create(['product_id' => $productId, 'level' => $customerLevel, 'unit_level' => 2, 'amount' => $p2]);
        if (!empty($p3)) ProductPrice::create(['product_id' => $productId, 'level' => $customerLevel, 'unit_level' => 3, 'amount' => $p3]);
        if (!empty($p4)) ProductPrice::create(['product_id' => $productId, 'level' => $customerLevel, 'unit_level' => 4, 'amount' => $p4]);
    }
}