<?php

namespace App\Listeners;

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

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

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

    /**
     * Handle the event.
     */
    public function handle(receiveorderitem $event): void
    {
 
        $Product = Product::findorfail($event->receivedOrder->ItemCtrlNum);
        $stocklevel = stocklevel::findorfail($event->receivedOrder->ItemCtrlNum);
        $stocklevel->Quantity = $stocklevel->Quantity + ($event->receivedOrder->ReceivedQty * $Product->factor);
        $stocklevel->update();

        $Quantity = $event->receivedOrder->ReceivedQty * $Product->factor;


      


        DB::SELECT("INSERT INTO StockValue(POCtrlNum,Item,ReceiveDate,factor,Quantity,amount)
                    SELECT  a.ControlNum,
                            b.ProductCtrlNum,
                            ?,
                            ?,
                            ?,
                            b.ItemAmt 
                    FROM    PO_headers a,
                            PO_details b 
                    WHERE   a.ControlNum = b.HeaderCtrlNum 
                    AND     a.ControlNum = ?
                    AND     b.ProductCtrlNum = ?
        
        ",[$event->receivedOrder->ApplyDate,$Product->factor,$Quantity,$event->receivedOrder->OrderCtrlNum,$event->receivedOrder->ItemCtrlNum,]);



        DB::SELECT("UPDATE req_order_track SET orderedQty = orderedQty - ? WHERE HeaderCtrlNum = ? AND ProductCtrlNum = ?",
                    [$event->receivedOrder->ReceivedQty,$event->receivedOrder->OrderCtrlNum,$event->receivedOrder->ItemCtrlNum]);

        DB::SELECT("DELETE FROM  req_order_track WHERE HeaderCtrlNum = ? AND ProductCtrlNum = ? AND orderedQty = 0 ",
                    [$event->receivedOrder->OrderCtrlNum,$event->receivedOrder->ItemCtrlNum,]);

    }
}
