<?php

namespace App\Listeners;

use App\Events\receiveorderitem;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use DB;

use App\Models\Product;

class storestockupdate
{
    /**
     * Create the event listener.
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     */
    public function handle(receiveorderitem $event): void
    {
        $Product = Product::find($event->receivedOrder->ItemCtrlNum);
        $productQty = $Product->factor * $event->receivedOrder->ReceivedQty;
        if(DB::table('storestocklevels')->select('*')->WHERE('StoreCtrlNum',auth()->user()->store)->WHERE('ItemCtrlNum',$event->receivedOrder->ItemCtrlNum)->exists()){
            DB::UPDATE("UPDATE  storestocklevels SET Quantity = Quantity + ? , updated_at = curdate() WHERE StoreCtrlNum = ? AND ItemCtrlNum = ?",[$productQty,auth()->user()->store,$event->receivedOrder->ItemCtrlNum]);
        } else {
            DB::INSERT("INSERT INTO storestocklevels(StoreCtrlNum,ItemCtrlNum,Quantity,created_at,updated_at) VALUES(?,?,?,curdate(),curdate())",[auth()->user()->store,$event->receivedOrder->ItemCtrlNum,$productQty]);
        }
    }
}
