<?php

namespace App\Observers;

use App\Models\DelayedGood;
use App\Models\WarehouseStock;

class DelayedGoodObserver
{
    /**
     * Handle the DelayedGood "saving" event.
     */
    public function saving(DelayedGood $delayedGood): void
    {
        $delayedGood->is_paid = $delayedGood->paid_amount >= $delayedGood->total_amount;

        if ($delayedGood->is_paid && ! $delayedGood->payment_date) {
            $delayedGood->payment_date = now();
        }

        if (! $delayedGood->is_paid) {
            $delayedGood->payment_date = null;
        }
    }

    /**
     * Handle the DelayedGood "created" event.
     */
    public function created(DelayedGood $delayedGood): void
    {
        if ($delayedGood->warehouse_id) {
            WarehouseStock::adjustStock(
                $delayedGood->warehouse_id,
                $delayedGood->unit_id,
                false,
                -$delayedGood->quantity
            );
        }
    }

    /**
     * Handle the DelayedGood "updated" event.
     */
    public function updated(DelayedGood $delayedGood): void
    {
        if ($delayedGood->isDirty(['warehouse_id', 'unit_id', 'quantity'])) {
            $oldWarehouseId = $delayedGood->getOriginal('warehouse_id');
            $oldUnitId = $delayedGood->getOriginal('unit_id');
            $oldQuantity = $delayedGood->getOriginal('quantity');

            if ($oldWarehouseId) {
                WarehouseStock::adjustStock($oldWarehouseId, $oldUnitId, false, $oldQuantity);
            }

            if ($delayedGood->warehouse_id) {
                WarehouseStock::adjustStock($delayedGood->warehouse_id, $delayedGood->unit_id, false, -$delayedGood->quantity);
            }
        }
    }

    /**
     * Handle the DelayedGood "deleted" event.
     */
    public function deleted(DelayedGood $delayedGood): void
    {
        if (! $delayedGood->isForceDeleting() && $delayedGood->warehouse_id) {
            WarehouseStock::adjustStock($delayedGood->warehouse_id, $delayedGood->unit_id, false, $delayedGood->quantity);
        }
    }

    /**
     * Handle the DelayedGood "restored" event.
     */
    public function restored(DelayedGood $delayedGood): void
    {
        if ($delayedGood->warehouse_id) {
            WarehouseStock::adjustStock($delayedGood->warehouse_id, $delayedGood->unit_id, false, -$delayedGood->quantity);
        }
    }
}
