<?php

namespace App\Models;

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

class StockTransaction extends Model
{
    use HasFactory;

    protected $guarded = ['id'];

    protected $casts = [
        'input_quantity' => 'float',
        'actual_quantity' => 'float',
    ];

    /**
     * LOGIKA "MAGIC FIX" + "AUTO SYNC"
     * Ini adalah mesin otomatis yang menjamin stok selalu benar.
     */
    protected static function booted()
    {
        // 1. SAAT MAU DISIMPAN (Menghitung Konversi Satuan)
        static::saving(function ($transaction) {
            $product = Product::find($transaction->product_id);
            
            if ($product) {
                // Fallback jika input_unit kosong
                if (empty($transaction->input_unit)) {
                    $transaction->input_unit = $product->unit;
                }

                // Logika Konversi Satuan (Sak -> Kg)
                $conversionFactor = 1;
                $inputUnit = $transaction->input_unit; 

                if ($inputUnit === $product->buy_unit) {
                    $conversionFactor = $product->conversion_factor;
                } elseif ($inputUnit === $product->unit_3_name) {
                    $conversionFactor = $product->conversion_3_qty;
                } elseif ($inputUnit === $product->unit_4_name) {
                    $conversionFactor = $product->conversion_4_qty;
                }
                
                $conversionFactor = (float) $conversionFactor;

                // Hitung Actual Quantity (Nilai Murni)
                $transaction->actual_quantity = (float) $transaction->input_quantity * $conversionFactor;
            }
        });

        // 2. SETELAH DISIMPAN (Auto-Update Saldo Akhir)
        // Begitu transaksi masuk, dia langsung menghitung ulang saldo.
        static::saved(function ($transaction) {
            self::syncProductStock($transaction);
        });

        // 3. SETELAH DIHAPUS (Auto-Update Saldo Akhir)
        static::deleted(function ($transaction) {
            self::syncProductStock($transaction);
        });
    }

    // --- HELPER SINKRONISASI ---
    protected static function syncProductStock($transaction)
    {
        // 1. Hitung Total Stok Aktual dari Riwayat (SUM)
        // Ini menjamin saldo akhir selalu sama dengan total riwayat (Konsisten)
        $realStock = self::where('product_id', $transaction->product_id)
            ->where('branch_id', $transaction->branch_id)
            ->sum('actual_quantity');

        // 2. Update Tabel Saldo Akhir (ProductStock)
        \App\Models\ProductStock::updateOrCreate(
            [
                'product_id' => $transaction->product_id, 
                'branch_id' => $transaction->branch_id
            ],
            ['quantity' => $realStock]
        );

        // 3. Update Total Global (Product) - Optional jika Owner butuh lihat total semua cabang
        $globalStock = \App\Models\ProductStock::where('product_id', $transaction->product_id)
            ->sum('quantity');
            
        \App\Models\Product::where('id', $transaction->product_id)
            ->update(['stock_qty' => $globalStock]);
    }

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

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

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