<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class PurchaseItem extends Model
{
    protected $guarded = [];

    public function purchase(): BelongsTo
    {
        return $this->belongsTo(Purchase::class);
    }

    public function product(): BelongsTo
    {
        return $this->belongsTo(Product::class);
    }

    // --- LOGIKA OTOMATIS (STOK & UPDATE HARGA MODAL) ---
    protected static function booted()
    {
        // 1. SAAT ITEM DIBUAT (Restock)
        static::created(function ($item) {
            self::handleStockChange($item, 'in'); 
        });

        // 2. SAAT ITEM DIHAPUS (Batal Beli)
        static::deleted(function ($item) {
            self::handleStockChange($item, 'out'); 
        });

        // 3. [FIX BUG] SAAT ITEM DI-EDIT (Revisi)
        static::updated(function ($item) {
            // Cek jika ada perubahan pada quantity, satuan, atau nilai konversi
            if ($item->isDirty(['quantity', 'unit', 'conversion_value'])) {
                
                // A. KELUARKAN STOK LAMA (REVERT)
                // Kita ambil nilai lama sebelum diedit
                $oldConversion = $item->getOriginal('conversion_value') ?? 1;
                $oldQty = $item->getOriginal('quantity');
                $oldUnit = $item->getOriginal('unit');
                $oldQtyBase = $oldQty * $oldConversion;

                // Buat transaksi minus untuk membatalkan stok lama
                \App\Models\StockTransaction::create([
                    'branch_id'      => $item->purchase->branch_id,
                    'product_id'     => $item->product_id,
                    'type'           => 'correction', 
                    'input_quantity' => -1 * $oldQty, 
                    'input_unit'     => $oldUnit,
                    'actual_quantity'=> -1 * $oldQtyBase,
                    'user_id'        => auth()->id(),
                    'note'           => 'Revisi (Batal): ' . ($item->purchase->invoice_number ?? '-'),
                ]);

                // B. MASUKKAN STOK BARU (SESUAI EDITAN)
                self::handleStockChange($item, 'in', 'Revisi (Baru): ');
            }
        });
    }

    // --- HELPER FUNCTION AGAR KODE RAPI & DRY (Don't Repeat Yourself) ---
    protected static function handleStockChange($item, $type = 'in', $notePrefix = '')
    {
        if (!$item->purchase) return;

        $conversion = $item->conversion_value ?? 1;
        $qtyInBaseUnit = $item->quantity * $conversion;

        // Jika tipe 'out' (hapus), jadikan negatif
        $multiplier = ($type === 'out') ? -1 : 1;
        
        $finalInputQty = $item->quantity * $multiplier;
        $finalActualQty = $qtyInBaseUnit * $multiplier;

        // 1. Catat Transaksi Stok
        \App\Models\StockTransaction::create([
            'branch_id'      => $item->purchase->branch_id,
            'product_id'     => $item->product_id,
            'type'           => 'purchase',
            'input_quantity' => $finalInputQty,
            'input_unit'     => $item->unit,
            'actual_quantity'=> $finalActualQty,
            'user_id'        => auth()->id(), // Mengambil user yg sedang login
            'note'           => $notePrefix . 'Faktur: ' . ($item->purchase->invoice_number ?? '-'),
        ]);

        // 2. Update HPP (Hanya saat barang MASUK BARU / Created)
        // Catatan: Saat edit, update HPP otomatis dimatikan untuk mencegah bias perhitungan,
        // kecuali user menghapus barang lalu input ulang.
        if ($type === 'in' && $item->product && $item->wasRecentlyCreated) {
            $product = $item->product;
            
            // Hitung Stok Lama
            $currentTotalStock = \App\Models\ProductStock::where('product_id', $product->id)->sum('quantity');
            $oldPrice = $product->buy_price;

            // Hitung Harga Netto Baru per Satuan Dasar
            $netTotalPerItem = 0;
            if($item->quantity > 0) {
                 $netTotalPerItem = $item->total_price / $item->quantity; 
            }
            $newPricePerBase = $netTotalPerItem / ($conversion ?: 1);

            // Rumus Average Cost
            if (($currentTotalStock + $finalActualQty) > 0) {
                $newAveragePrice = (
                    ($currentTotalStock * $oldPrice) + 
                    ($finalActualQty * $newPricePerBase)
                ) / ($currentTotalStock + $finalActualQty);
                
                $product->buy_price = $newAveragePrice;
                $product->save();
            } elseif ($currentTotalStock == 0) {
                // Jika stok sebelumnya 0, langsung pakai harga baru
                $product->buy_price = $newPricePerBase;
                $product->save();
            }
        }
    }
}