<?php

namespace App\Observers;

use App\Models\StockTransaction;
use App\Models\ProductStock;
use App\Models\Product;

class StockTransactionObserver
{
    public function created(StockTransaction $stockTransaction): void
    {
        $this->syncProductStock($stockTransaction);
    }

    public function updated(StockTransaction $stockTransaction): void
    {
        $this->syncProductStock($stockTransaction);
    }

    public function deleted(StockTransaction $stockTransaction): void
    {
        $this->syncProductStock($stockTransaction);
    }

    private function syncProductStock(StockTransaction $trx)
    {
        if (!$trx->product_id || !$trx->branch_id) return;

        // 1. Hitung Total Aktual dari SEMUA history transaksi
        $realStock = StockTransaction::where('product_id', $trx->product_id)
            ->where('branch_id', $trx->branch_id)
            ->sum('actual_quantity');

        // 2. Update Stok Master per Cabang
        ProductStock::updateOrCreate(
            ['product_id' => $trx->product_id, 'branch_id' => $trx->branch_id],
            ['quantity' => $realStock]
        );

        // 3. Update Stok Global Product
        $globalStock = ProductStock::where('product_id', $trx->product_id)->sum('quantity');
        Product::where('id', $trx->product_id)->update(['stock_qty' => $globalStock]);
    }
}