<?php

namespace App\Listeners;

use App\Events\stockadjustment;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

use App\Models\Product;
use App\Models\stocklevel;

use DB;
class adjUpdateStockLevel
{
    /**
     * Create the event listener.
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     */
    public function handle(stockadjustment $event): void
    {

        $product = Product::find($event->adjustStock->product);
        $stocklevel = stocklevel::find($event->adjustStock->product);
        //dd($event->adjustStock->unit);
        //dd($stocklevel);

        if ( intval($event->adjustStock->unit) == $product->BuyingUnit){
            /*
                if adjusting against buying unit multiply by factor
            */
            if ($event->adjustStock->type == -1){
                $stocklevel->Quantity = $stocklevel->Quantity  - ($event->adjustStock->quantity * $product->factor);
            }
            if ($event->adjustStock->type ==  1){
                $stocklevel->Quantity = $stocklevel->Quantity  + ($event->adjustStock->quantity * $product->factor);
            }
        }

        if (intval($event->adjustStock->unit) == $product->SellingUnit){
            if ($event->adjustStock->type == -1){
                $stocklevel->Quantity = $stocklevel->Quantity - $event->adjustStock->quantity;
            }
            if ($event->adjustStock->type ==  1){
                $stocklevel->Quantity = $stocklevel->Quantity  + $event->adjustStock->quantity;
            }
        }
     
        $stocklevel->update();
    }
}
