<?php

namespace App\Http\Controllers\Purchases;




use App\Http\Controllers\OutonumController;


use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use Haruncpi\LaravelIdGenerator\IdGenerator;
use App\Models\Supplier;

use App\Models\orderSupplier;
use App\Models\Product;
use App\Models\modrequisation;
use App\Models\Tax;
use App\Models\POItemsList;
use App\Models\producttax;
//use App\Models\orderSupplier;


use App\Models\stores;
use App\Models\poStoreItemQty;
use App\Models\Unit;



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

use App\Events\PO_Complete;



use DB;
use Auth;

class PurchaseOrder extends Controller
{



    public function ControlNumber($ControlNum){
        $outonum = outonum::findorfail($ControlNum);
        $ControlNum = $outonum->prefix . str_pad($outonum->CurrentVal,8,"0",STR_PAD_LEFT);
        $outonum->CurrentVal = $outonum->CurrentVal + 1;
        $outonum->nextVal = $outonum->nextVal + 1;
        $outonum->update();
        return $ControlNum;
    }


    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //dd('Test');
        $orderSuppliers = DB::SELECT("select * from suppliers a,order_suppliers b  WHERE a.id = b.SupplierCtrlNum");


        return view('purchase.Order.index')->with('orderSuppliers',$orderSuppliers);
    }

    /**
     * Show the form for creating a new resource.
     */

    public function create(){
        $orderNumber = $this->ControlNumber('CON01');
        $newly = $this->create_new($orderNumber);
        return $newly;
    }






    public function create_new(String $orderNumber)
    {

    

        $POTotal = 0;
        $POTaxTotal = 0;
        $POItemGrandTotal = 0;

        $SupplierName = DB::table('order_suppliers')
                            ->SELECT('suppliers.name')
                            ->join('suppliers','suppliers.id','order_suppliers.SupplierCtrlNum')
                            ->WHERE('order_suppliers.orderCtrlNum',$orderNumber )->first();
        $Supplier = (is_null($SupplierName)?"":$SupplierName->name);
        
        
        $SupplierName = DB::table('order_suppliers')
                            ->SELECT('suppliers.name','order_suppliers.applydate', 'order_suppliers.currency')
                            ->join('suppliers','suppliers.id','order_suppliers.SupplierCtrlNum')
                            ->WHERE('order_suppliers.orderCtrlNum',$orderNumber )->first();
        $Supplier = (is_null($SupplierName)?"":$SupplierName->name);
        $applydate = (is_null($SupplierName)?"":$SupplierName->applydate);




        $currency = (is_null($SupplierName)?"":$SupplierName->currency);        
        
        
        

        $POItemsLists = POItemsList::all();
        /*
        $POItemsLists = DB::SELECT('SELECT a.POCtrlNum, a.ItemCtrlNum, a.TaxCtrlNum, a.quantity, a.ItemAmt,
                                            b.product_name product
                                    FROM PO_items_lists a,
                                    INNER JOIN products b ON a.ItemCtrlNum=b.id
                                    INNER JOIN taxes c on c.id = a.TaxCtrlNum ');*/
        $POItemsLists = DB::SELECT('SELECT a.id,a.POCtrlNum, a.ItemCtrlNum, c.name, a.quantity, a.ItemAmt,
                                            b.product_name product,c.slug,
                                            a.quantity * a.ItemAmt ItemGrossTotal,
                                            a.quantity * a.ItemAmt * (c.slug/100) ItemTaxAmount,
                                            (a.quantity * a.ItemAmt) + (a.quantity * a.ItemAmt * (c.slug/100)) ItemGrandTotal
                                    FROM PO_items_lists a
                                    INNER JOIN products b ON a.ItemCtrlNum = b.id
                                    INNER JOIN taxes c on c.id = a.TaxCtrlNum WHERE a.POCtrlNum = ?',[$orderNumber]);


        foreach($POItemsLists as $POItemsList){
            $POTotal += $POItemsList->ItemGrossTotal;
            $POTaxTotal += $POItemsList->ItemTaxAmount;
            $POItemGrandTotal += $POItemsList->ItemGrandTotal;
        }

        return view('purchase.Order.create',compact('orderNumber','Supplier','POTotal','POTaxTotal','POItemGrandTotal','applydate','currency'))
                    ->with('POItemsLists',$POItemsLists);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        $delItem = POItemsList::findorfail($id);
        $delItem->delete();
        return redirect()->route('order.create.list',$delItem->POCtrlNum);

    }

    public function SupplierList(Request $request, string $orderNumber)
    {
        $suppliers = Supplier::all();
        
         $applydate = $request->applyDate;
         $Currency =$request->Currency;
        return view('purchase.Order.SupplierList',compact('orderNumber','applydate','Currency'))
                                        ->with('suppliers',$suppliers);
    }

    public function SupplierListAssign(String $Supplier,String $POCtrlNum,$applydate,$currency){
        $orderSupplier = new orderSupplier();


        $orderSupplier->orderCtrlNum = $POCtrlNum;
        $orderSupplier->SupplierCtrlNum = $Supplier;
        
        $orderSupplier->applydate = $applydate;
        $orderSupplier->currency = $currency;

        $orderSupplier->save();
        return $newly = $this->create_new($POCtrlNum);
    }

    public function OrderItemList(String $orderNumber){


        $Products = Product::all();
/*
         $Products = DB::SELECT("select *
                                    from    modrequisations a,
                                            products b,
                                            order_suppliers c
                                    WHERE   a.ProductId = b.id
                                    AND     b.supplier_id = c.SupplierCtrlNum
                                    AND     c.orderCtrlNum = ?",[$orderNumber]);
*/


                                    /*
,
                                            order_suppliers c
                                    AND     b.supplierId =c.SupplierCtrlNum
                                    AND     c.orderCtrlNum = ?",[$orderNumber]

                                    */

        return view('purchase.Order.ProductList',compact('orderNumber'))
                                        ->with('Products',$Products);
    }



    public function OrderItemListByName(Request $request,String $orderNumber){

        $Products = Product::WHERE('product_code','LIKE',"%{$request->searchVal}%")->get();

        return view('purchase.Order.ProductList',compact('orderNumber'))->with('Products',$Products);
    }




    public function OrderItemSelect(String $POCtrlNum, String $Item){
        $Taxes = Tax::all();
        $stores = stores::all();

        $producttax = producttax::WHERE('ProductId',$Item)->first();


        $Product = Product::findorfail($Item);
        
        
        
        $unit = Unit::find($Product->BuyingUnit);
        
        $ProductTaxes = Tax::findorfail($Product->tax_id);
        $requisationItemQty = modrequisation::WHERE('ProductId',$Item)->sum('Quantity');


        return view('purchase.Order.OrderItemCreate',compact('POCtrlNum','Item','requisationItemQty','Product','ProductTaxes','stores','unit'))->with('Product',$Product)
                                        ->with('taxes',$Taxes);
    }

    public function OrderItemStore(Request $request,String $POCtrlNum, String $Item){
        //dd($request->store);
        $POItemsList = new POItemsList();

        $poStoreItemQty = new poStoreItemQty();
        
        
        $POItemsList->POCtrlNum = $POCtrlNum;
        $POItemsList->ItemCtrlNum = $Item;
        $POItemsList->TaxCtrlNum = $request->tax;
        $POItemsList->quantity = $request->Quantity;
        $POItemsList->ItemAmt = $request->Amount;
        $POItemsList->EntryUser = Auth::User()->id;




        $poStoreItemQty->Store = $request->store;
        $poStoreItemQty->POCtrlNum = $POCtrlNum;
        $poStoreItemQty->ItemCtrlNum = $Item;
        $poStoreItemQty->quantity = $request->Quantity;




        $orderSupplier = orderSupplier::find($POCtrlNum);

        if(POItemsList::WHERE('POCtrlNum',$POCtrlNum)->WHERE('ItemCtrlNum',$Item)->exists()){
            DB::SELECT("UPDATE PO_items_lists SET quantity = quantity + ? WHERE  POCtrlNum = ? AND ItemCtrlNum = ? ",[$request->Quantity,$POCtrlNum,$Item,]);
        } else {
            $POItemsList->save();
        }

            DB::SELECT("UPDATE modrequisations
                        SET     Quantity = Quantity - ?
                        WHERE   ProductId  = ?
                        AND     supplierId = ? ",[$request->Quantity,$Item,$orderSupplier->SupplierCtrlNum]);




        $poStoreItemQty->save();


        return redirect()->route('order.create.list',$POCtrlNum);
        //return redirect()->route('order.create')->withInput(<[array data>]);

    }


    public function complete(String $ControlNum){

            event (new PO_Complete($ControlNum));

       return redirect()->route('order.index');
    }

    public function OrderItemCancel(String $ControlNum){
        DB::SELECT("DELETE from order_suppliers WHERE orderCtrlNum = ?",[$ControlNum]);
        DB::SELECT("DELETE from PO_items_lists WHERE POCtrlNum = ?",[$ControlNum]);
        return redirect()->route('order.index');
    }


}
