<?php

namespace App\Observers;

use App\Models\FeedDelivery;
use Illuminate\Support\Facades\DB;

class FeedDeliveryObserver
{
    /**
     * Handle the FeedDelivery "created" event.
     */
    public function created(FeedDelivery $feedDelivery): void
    {
        $feedDelivery->feed()->decrement('stock', $feedDelivery->quantity);
    }

    /**
     * Handle the FeedDelivery "updating" event.
     */
    public function updating(FeedDelivery $feedDelivery): void
    {
        if ($feedDelivery->isDirty('quantity')) {
            $oldQuantity = $feedDelivery->getOriginal('quantity');
            $newQuantity = $feedDelivery->quantity;

            $diff = $newQuantity - $oldQuantity;

            $feedDelivery->feed()->decrement('stock', $diff);
        }

        if ($feedDelivery->isDirty('feed_id')) {
            $oldFeedId = $feedDelivery->getOriginal('feed_id');
            $newFeedId = $feedDelivery->feed_id;

            DB::table('feeds')->where('id', $oldFeedId)->increment('stock', $feedDelivery->getOriginal('quantity'));

            DB::table('feeds')->where('id', $newFeedId)->decrement('stock', $feedDelivery->quantity);
        }
    }

    /**
     * Handle the FeedDelivery "deleted" event.
     */
    public function deleted(FeedDelivery $feedDelivery): void
    {
        $feedDelivery->feed()->increment('stock', $feedDelivery->quantity);
    }

    /**
     * Handle the FeedDelivery "restored" event.
     */
    public function restored(FeedDelivery $feedDelivery): void
    {
        $feedDelivery->feed()->decrement('stock', $feedDelivery->quantity);
    }
}
