<?php

namespace App\Listeners;

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

use App\Models\PO_Header;
use App\Models\PO_Detail;

use DB;


class updatePO
{
    /**
     Create the event listener.

    public function __construct()
    {
        //
    }


     * Handle the event.
     */
    public function handle(PO_Complete $event): void
    {
            $ControlNum = $event->ControlNum;

            $y = 1;
            $x = 1;
            $PO_Header = new PO_Header();

            $orderDetails = DB::SELECT('SELECT  PO_items_lists.POCtrlNum,order_suppliers.SupplierCtrlNum,taxes.id, PO_items_lists.quantity, PO_items_lists.ItemCtrlNum,
                                                taxes.slug, PO_items_lists.quantity, PO_items_lists.ItemAmt, order_suppliers.applydate
                            FROM    PO_items_lists
                            INNER   JOIN    order_suppliers ON PO_items_lists.POCtrlNum = order_suppliers.orderCtrlNum
                            INNER   JOIN    taxes ON PO_items_lists.TaxCtrlNum = taxes.id
                            WHERE   POCtrlNum = ?',[ $ControlNum]);


            foreach($orderDetails as $orderDetail){
                
                 
                
                    $PO_Header->ControlNum = $ControlNum;
                    $PO_Header->Supplier   = $orderDetail->SupplierCtrlNum;
                    $PO_Header->ApplyDate = $orderDetail->applydate;
                    $PO_Header->Currency  = 'TZS';
                    $PO_Header->save();
                    if ($y == 1){
                        break;
                    }
            }

            if(PO_Header::WHERE('ControlNum',$ControlNum)->exists()){
                    foreach($orderDetails as $orderDetail){
                            $PO_Detail = new PO_Detail();
                            $PO_Detail->ControlNum = $x;
                            $PO_Detail->HeaderCtrlNum  = $ControlNum;
                            $PO_Detail->TaxCtrlNum  = $orderDetail->id;
                            $PO_Detail->TaxQty    = $orderDetail->slug;
                            $PO_Detail->ProductCtrlNum  = $orderDetail->ItemCtrlNum;
                            $PO_Detail->Qty  = $orderDetail->quantity;
                            $PO_Detail->ItemAmt  = $orderDetail->ItemAmt;
                            $PO_Detail->save();
                            $x += 1;
                    }
                    DB::SELECT("INSERT INTO req_order_track
                                SELECT ControlNum,HeaderCtrlNum,ProductCtrlNum,Qty orderedQty, 0 DelQty
                                FROM    PO_details
                                WHERE   HeaderCtrlNum = ?",[$ControlNum]);
            }

    }
}
