<?php

namespace App\Http\Controllers\Inventory;

use App\Product;
use App\Purchase;
use App\Supplier;
use App\TempData;
use App\Quotation;
use App\Requisition;
use App\QuotationProduct;
use App\PurchaseProduct;
use App\Mail\PurchaseOrder;
use App\RequisitionProduct;
use App\Goodsin;
use App\GoodsinProduct;
use App\NewRequisition;
use App\NewRequisitionProduct;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;

class InventoryPurchaseController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }
    public function index(){
        $requisitions = NewRequisition::with('quotations')->where(get_where())->whereNotNull('check_user_id')->orderBy('requisition_id','desc')->get();
        return view('inventory.purchase.pending-purchase-requisition',compact('requisitions'));
    }

    public function approved(){
        return view('inventory.purchase.approved-history');
    }



    /* quotation making  start */
    public function makeQuotation($id){
        $suppliers = Supplier::all();
        $invoice_requisition = NewRequisition::query()->findOrFail($id);
        if($invoice_requisition == null){
            return view('errors.404');
        }

        $quotations = NewRequisitionProduct::query()->whereNotNull('user_id')->where('new_requisition_id',$id)->get();
        return view('inventory.purchase.add-quotation-inventory-requisition',compact('quotations','invoice_requisition','suppliers'));
    }
    /* quotation making end */

    /*  Change Quotation Supplier  start */
    public function changeQuotationSupplier($data){

        $new_requisition_id = explode('&',$data)[0];
        $supplier_id = explode('&',$data)[1];
        $quotation_id = explode('&',$data)[2];

        /* Check if same requisition has the repeated supplier or not*/
        $check = Quotation::where(['requisition_id'=>$new_requisition_id,'supplier_id'=>$supplier_id])->first();
        if($check != null){
            session()->flash('error','Repeated supplier found for the same requisition');
        }else{

            /*MRR check (if it has PO, then if it has mrr, then can't change supplier) */
            $past_supplier_id = Quotation::find($quotation_id)->supplier_id;
            $goodsin_check = GoodsinProduct::where(['requisition_id'=>$new_requisition_id,'supplier_id'=>$past_supplier_id])->first();

            if($goodsin_check != null){
                session()->flash('error','This PO has MRR, so you can not change the supplier');
            }else{
                Quotation::find($quotation_id)->update(['supplier_id'=>$supplier_id]);
                QuotationProduct::where('quotation_id',$quotation_id)->update(['supplier_id'=>$supplier_id]);
                Purchase::where(['requisition_id'=>$new_requisition_id])->where('supplier_id',$past_supplier_id)->update(['supplier_id'=>$supplier_id]);
                PurchaseProduct::where(['requisition_id'=>$new_requisition_id])->where('supplier_id',$past_supplier_id)->update(['supplier_id'=>$supplier_id]);

                session()->flash('success','Supplier Successfully Changed');
            }
            
        }
        return back();

    }
    /*  Change Quotation Supplier end */


    /* quotation store start */
    public function storeQuotation(Request $request, $id){
//        dd($request->all());
        $supplier_id = $request->get('supplier_id');
        if ($supplier_id === '0'){
            return redirect()->route('inventory.quotation.add',$id)->with('error','Please Select Supplier');
        }
        /* quotation invoice store start */
        $price=$qty=0;

        // foreach ($request->get('requisition_product_id') as $key => $requisition_id){
        //     $price+=$request->price[$key];
        // }
        $invoice_quotation = Quotation::where([['supplier_id', $request->get('supplier_id')],['requisition_id',$id]])->first();
        //CS No creation
        if($invoice_quotation != null){
            $invoice_quotation->update([
                'requisition_id'=>$id,
                'supplier_id'=>$request->get('supplier_id'),
                'user_id'=>Auth::id(),
                'price'=>$price,
                'note'=>$request->note,
                'qty'=>1,
            ]);
        }else{
                $invoice_quotation = Quotation::query()->create([
                    'requisition_id'=>$id,
                    'supplier_id'=>$request->get('supplier_id'),
                    'user_id'=>Auth::id(),
                    'price'=>$price,
                    'note'=>$request->note,
                    'qty'=>1,
                ]);
            }
        /* quotation invoice store End */

        /* quotation store start */
        foreach ($request->get('requisition_product_id') as $key=>$requisition_id){
            $quotationProduct = QuotationProduct::where([['quotation_id',$invoice_quotation->id],['requisition_id', $id],['supplier_id',$request->get('supplier_id')],["requisition_product_id",$requisition_id]])->latest()->first();
            if($quotationProduct != null){
                if($request->price[$key] > 0){
                    $price += $request->price[$key];
                    $quotationProduct->update([
                        'quotation_id'=>$invoice_quotation->id,
                        'requisition_id'=>$id,
                        'supplier_id'=>$request->get('supplier_id'),
                        "requisition_product_id"=>$requisition_id,
                        'user_id'=>Auth::id(),
                        'price'=>$request->price[$key],
                        'product_id' => NewRequisitionProduct::find($requisition_id)->product_id,
                        'product_remarks' =>$request->product_remarks[$key],
                        'qty'=>$request->quotation_qty[$key],
                    ]);
                }else{
                    $price += $quotationProduct->price;
                }
                
            }else{
                if($request->price[$key] > 0){
                    $price += $request->price[$key];
                    $data = [
                        'quotation_id'=>$invoice_quotation->id,
                        'requisition_id'=>$id,
                        'supplier_id'=>$request->get('supplier_id'),
                        "requisition_product_id"=>$requisition_id,
                        'user_id'=>Auth::id(),
                        'price'=>$request->price[$key],
                        'product_id' => NewRequisitionProduct::find($requisition_id)->product_id,
                        'product_remarks' =>$request->product_remarks[$key],
//                        'qty'=>$request->quotation_qty[$key],
                    ];
                    QuotationProduct::query()->create($data);
                }

            }
        }
        $invoice_quotation->update(['price'=>$price]);
        /* quotation store end */

        session()->flash('success','Quotation complete');
        return redirect()->route('quotations.list',$id);


    }
    /* quotation store end */


    /* purchase order making  start */
    public function makePurchaseOrder($id){
        $suppliers = Supplier::get(['id','name']);
        $invoice_requisition = NewRequisition::query()->findOrFail($id);
        if($invoice_requisition == null){
            return view('errors.404');
        }

        $products = NewRequisitionProduct::query()->whereNotNull('user_id')->where('new_requisition_id',$id)->get();
        return view('inventory.purchase.make-purchase-order',compact('products','invoice_requisition','suppliers'));
    }
    /* purchase order making end */


    /* purchase order store start */
    public function storePurchaseOrder(Request $request, $id){
//        dd($request->all());

        $suppliers_array = array();

        if(count($request->supplier_id) > 0){

            $new_requisition = NewRequisition::find($id);
            $new_requisition->update(['sent_for'=>3]); // 3 for purchase without quotation

            foreach ($request->supplier_id as $key => $supplier_id) {
//                NewRequisitionProduct::find($key)->update(['price'=>$request->price[$key]]);
                if(!in_array($supplier_id, $suppliers_array)){
                    array_push($suppliers_array, $supplier_id);
                    $new_purchase = Purchase::query()->create([
                        'purchase_no' => getPurchaseId($new_requisition->unit_id),
                        'unit_id' => $new_requisition->unit_id,
                        'requisition_id' => $new_requisition->id,// New Requisition table id
                        'purchase_type' => 1, // 1 for direct purchase, 0 for purchase from quotation
                        'user_id' => Auth::id(),
                        'supplier_id' =>$supplier_id,
                        'payment_type' =>$request->payment_type[$key],
                    ]);

//                    $purchase_array[$supplier_id] = $new_purchase->id;
                }
                PurchaseProduct::query()->create([
                    'purchase_id' => $new_purchase->id,
                    'requisition_id'=>$new_requisition->id,// New Requisition table id
                    'product_id' => $request->product_id[$key],
                    'price' => $request->price[$key],
                    'qty' =>$request->qty[$key],
                    'supplier_id' => $new_purchase->supplier_id,

                    'requisition_product_id'=>$request->requisition_product_id[$key],//new requisition_product_id
                    'quotation_id' => 0,
                ]);
            }
        }
        session()->flash('success','Purchase order made successfully !');
        return redirect('Inventory/add-inventory-requisition-purchase');

    }
    /* purchase order store end */



    /* Quotation Lists start */
    public function quotationLists(){
        $requisitions = NewRequisition::query()->where(get_where())->orderBy('id','desc')->get();
        return view('inventory.purchase.requisition-quotation-lists',compact('requisitions'));
    }
    /* Quotation lists End */

    /* Comparative Statements start */
    public function comparativeStatements(){
        $requisitions = NewRequisition::query()->where(get_where())->orderBy('cs_no','desc')->get();
        return view('inventory.purchase.comparative-statements',compact('requisitions'));
    }
    /* Comparative Statements end */

    /* Quotations fetch start */
    public function allQuotations($requisitionId){
        // dd($requisitionId);
        $quotations = QuotationProduct::query()->with('supplier')->where('requisition_id',$requisitionId)->get()->groupBy('supplier_id');
        if ($quotations->count()==0){
            session()->flash('error','No quotation found!');
            return redirect()->route('inventory.requisition.quotation.list');
        }
        $suppliers = Supplier::get(['id','name']);
        $requisition = NewRequisition::query()->with('new_requisition_products')->findOrFail($requisitionId);
        return view('inventory.purchase.supplier-quotation',compact('quotations','requisition','suppliers'));
    }
    /* Quotations fetch end */

    /* Quotations fetch start */
    public function setPaymentType($data){
        $new_requisition_id = explode('&',$data)[0];
        $supplier_id = explode('&',$data)[1];
        $type = explode('&',$data)[2];

        $purchase = Purchase::where(['requisition_id'=>$new_requisition_id,'supplier_id'=>$supplier_id])->first();

        if($purchase != null){
            $update = $purchase->update(['payment_type'=>$type]);
            if($update){
                return response()->json(['success'=>true]);
            }
        }
        return response()->json(['success'=>false]);
    }
    /* Quotations fetch end */

    /* reset PO */
    public function resetPO($quotation_id){
        $quotation = Quotation::find($quotation_id);
        $flag = false;
        if(isset($quotation->quotationProduct[0]->id)){
            $flag = true;
            foreach ($quotation->quotationProduct as $key => $value) {
                PurchaseProduct::where('quotation_product_id',$value->id)->update(['qty'=>0]);
                NewRequisitionProduct::where('id',$value->requisition_product_id)->update(['po_qty'=> 0]);
            } 
        }
        if($flag){
            return back()->with('success','Reset Successfull');
        }else{
            return back()->with('error','Somthing went wrong !');
        }
        
    }
    /* reset PO */

     /* reset Individual PO */
    public function resetIndividualPO($data){

        $new_requisition_product_id = explode('&',$data)[0];
        $quotation_product_id = explode('&',$data)[1];
        $product_id = explode('&',$data)[2];
        $purchase_product_id = explode('&',$data)[3];

        $purchase_product = PurchaseProduct::find($purchase_product_id);
        $goodsin = GoodsinProduct::where('purchase_id', $purchase_product->purchase_id)->where('product_id',$product_id)->sum('qty');

        $purchase_product->update(['qty'=>$goodsin]);
        return back()->with('success','Reset Successful');
        
    }
    /* reset PO */


    /* reset Individual PO */
    public function removePO($data){

        $new_requisition_product_id = explode('&',$data)[0];
        $quotation_product_id = explode('&',$data)[1];
        $product_id = explode('&',$data)[2];
        $purchase_product_id = explode('&',$data)[3];

        $purchase_product = PurchaseProduct::find($purchase_product_id);
        $goodsin = GoodsinProduct::where('purchase_id', $purchase_product->purchase_id)->where('product_id',$product_id)->first();
        if(!isset($goodsin->id)){
            $delete = $purchase_product->delete();
            return back()->with('success','Successfully removed the PO');
        }else{
            $goodsintotal = GoodsinProduct::where('purchase_id', $purchase_product->purchase_id)->where('product_id',$product_id)->sum('qty');

            $purchase_product->update(['qty'=>$goodsintotal]);
            return back()->with('success','Reset Successful');
        }
        
        
    }
    /* reset PO */

    //customising price for each quotation product
    public function saveQuotationProduct($data){
        $id = explode('&', $data)[0];
        $price = explode('&', $data)[1];

        $quotation = QuotationProduct::find($id)->update(['price'=>$price]);
        $purchase_product = PurchaseProduct::where('quotation_product_id',$id)->update(['price'=>$price]);
        if($quotation){
            session()->flash('success','Price Successfully Saved');
        }else{
            session()->flash('error','Something Went Wrong !');
        }
        return redirect()->back();
    }

    //customising qty for requisition
    public function saveRequisitionProductQty($data){
        $explode = explode('*', $data)[0];
        $id = explode('&', $explode)[0];
        $qty = explode('&', $explode)[1];
        $remarks = explode('*', $data)[1];
        // dd($id);

        
        $new_requisition_product = NewRequisitionProduct::find($id);
        $changed_qty = $qty - $new_requisition_product->qty;
        $new_requisition_product->qty = $qty;
        $new_requisition_product->checking_note = $remarks;
        $new_requisition_product->save();

        $requisition_product = RequisitionProduct::where('requisition_id',$new_requisition_product->new_requisition->requisition_id)->where('product_id',$new_requisition_product->product_id)->first();
        $requisition_product->qty = strval($requisition_product->qty + $changed_qty);
        $requisition_product->checking_note = $remarks;
        $requisition_product->save();
        //  dd($requisition_product);

        if($requisition_product){
            session()->flash('success','Qty Successfully Saved');
        }else{
            session()->flash('error','Something Went Wrong !');
        }
        return redirect()->back();
    }

    //deleting quotation which is not purchased
    public function deleteQuotation($id){
        $quotation = QuotationProduct::find($id)->delete();
        if($quotation){
            return response()->json(['success'=>true]);
        }
        return response()->json(['success'=>false]);
    }

    /* Delete Quotation and related data*/
    public function deleteSupplierQuotation($id){
        $quotation = Quotation::find($id);
        if(isset($quotation->purchase->id)){
            $goodsin = Goodsin::where('purchase_id',$quotation->purchase->id)->first();
            if(isset($goodsin->id)){
                return back()->with('error', 'This PO has MRR, so it can not be deleted');
            }
            $purchase = Purchase::where('requisition_id',$quotation->requisition_id)->where('supplier_id',$quotation->supplier_id)->first();
            $purchase->delete();
            PurchaseProduct::where('purchase_id',$purchase->id)->delete();
        }
        $quotation->delete();
        QuotationProduct::where('quotation_id',$id)->delete();
        return back()->with('success', 'Quotation deleted successfully');
    }

    
    //Updated By Mizan
    
    public function comparativeStatementQuotations($requisition_id)
    {
        // dd($requisition_id);
        $suppliers = QuotationProduct::query()->where('requisition_id',$requisition_id)->get()->groupBy('supplier_id');
        $allProducts = QuotationProduct::query()->where('requisition_id',$requisition_id)->get()->groupBy('requisition_product_id');
        $cs_date = Quotation::where('requisition_id',$requisition_id )->first();
        $requisition = NewRequisition::query()->findOrFail($requisition_id);
        return view('inventory.purchase.comparative-statement',compact('allProducts','requisition','suppliers','cs_date'));

    }

    /* Comparative statement for individual requisitions end */


    public function order(Request $request){
        $requisition_id = $request->requisition_id ?? null;
        $quotation_id = $request->quotation_id ?? null;
        $quotations = $request->requisition_id != null ? Quotation::where('requisition_id',$requisition_id)->get(): null ;
        // $purchase = Purchase::where('confirm', 1)->get();
        // $purchase_array = array();
        // foreach ($purchase as $key => $value) {
        //     array_push($purchase_array, $value->requisition_id);
        // }
        // if(isset($purchase_array[0])){
        //     $requisitions = Purchase::where('confirm', 0)->whereNotIn('requisition_id', $purchase_array)->get(['id','requisition_id'])->groupBy(['requisition_id']);
        // }else{
        $requisitions = NewRequisition::where(get_where())->where('purchased_status',2)->get(['id','invoice_no','requisition_id']);
        //}

        return view('inventory.purchase.purchase-order',compact('requisitions','quotations','requisition_id','quotation_id'));
    }

    public function requisitionQuotationList(Request $request){
        //return $request->all();
        $products = NewRequisitionProduct::where('new_requisition_id',$request->requisition_id)->orderBy('id','asc')->get();

        $suppliers = Supplier::all();

        // $html = '<option value="0">Select Party Quotation </option>';

        // foreach ($quotations as $quotation){
        //     $html.='<option value="'.$quotation->id.'">  Party : '.$quotation->supplier->name.' ( '.$quotation->supplier->phone.' )  </option>';
        // }
        return view('inventory.purchase.ajax-quotation-list',compact('products','suppliers'));

    }


    public function store(Request $request){
        $request->all();
        if(isset($request->purchase)){
            $product_array = array();
            $suppliers_array = array();
            $count_purchased = 0;
            $count_less_than_zero = 0;
            foreach ($request->purchase as $key => $value) {
                $product = QuotationProduct::find($request->purchase[$key]);
                $new_requisition_product = NewRequisitionProduct::where('new_requisition_id', $request->requisition_id)->where('product_id',$product->product_id)->first();
                $already_purchased = PurchaseProduct::where('quotation_product_id', $product->id)->where('product_id',$product->product_id)->first();

                 //updating price for new requisition product and quotation product
                $new_requisition_product->update(['price'=>$request->purchase_price[$value]]);
                $product->update(['price'=>$request->purchase_price[$value]]);

                if(isset($already_purchased->id)){
                    //updating price for purchase
                    $already_purchased->update(['price'=>$request->purchase_price[$value]]);
                    $total_po = PurchaseProduct::where('requisition_product_id',$new_requisition_product->id)->where('product_id',$product->product_id)->sum('qty');
                    // || $request->purchase_qty[$value] <= 0
                    if(($new_requisition_product->qty <  $total_po + $request->purchase_qty[$value]) || $request->purchase_qty[$value] <= 0){
                        $count_purchased++;
                        $name_of_product = Product::find($already_purchased->product_id)->item_code;
                        
                    }
                    
                }else{
                    if($request->purchase_qty[$value] <= 0 || $request->purchase_qty[$value] > $new_requisition_product->qty){
                        $count_less_than_zero++;
                    }
                }
                if(!in_array($product->product_id,  $product_array)){
                    array_push($product_array, $product->product_id);
                    if(!in_array($product->supplier_id,  $suppliers_array)){
                        array_push($suppliers_array, $product->supplier_id);
                    }
                }else{
                    return back()->with(['error'=> "You can not select same item twice !"]);
                }
            }
            if($count_purchased > 0){
                return back()->with(['error'=> "All Qty for Item code ".$name_of_product." has been purchased or PO Qty must be greater than 0  !"]);
            }

            if($count_less_than_zero > 0){
                return back()->with(['error'=> "PO can not be less than 0 or greater than Requisition Qty!"]);
            }
            
            if(isset($suppliers_array[0])){
                $new_requisition = NewRequisition::find($request->requisition_id);
                $new_requisition->update(['purchased_status'=>1]);
                $new_requisition->update(['note'=>$request->note]);
                foreach ($suppliers_array as $supplier_value) {
                    //return $value;
                    // $quotation = Quotation::where('supplier_id', $supplier_value)->where('requisition_id',$new_requisition->id)->first();
                    // $purchase_for_quotation = Purchase::where('quotation_id',$quotation->id)->first();
                    $new_purchase = Purchase::where('supplier_id',$supplier_value)->where('requisition_id',$request->requisition_id)->first();

                    //check if this quotations' at least one item is purchased or not

                    if(isset($new_purchase->id)){
                        $purchased_status =  1;
                        // $new_purchase = Purchase::where('supplier_id',$supplier_value)->where('requisition_id',$request->requisition_id)->first();
                    }else{
                        $purchased_status =  0;
                        $new_purchase = Purchase::query()->create([
                            'purchase_no' => getPurchaseId($new_requisition->unit_id),
                            'unit_id' => $new_requisition->unit_id,
                            'requisition_id' => $request->requisition_id,//new requisition table id
                            'purchase_type' => 0, // 1 for direct purchase, 0 for purchase from quotation
                            'user_id' => Auth::id(),
                            'supplier_id' =>$supplier_value,
                            'payment_type' => $request->payment_type[$supplier_value],
                        ]);

                        Quotation::where('supplier_id', $supplier_value)->where('requisition_id',$new_requisition->id)->update(['status'=> 1]);
                    }
                   
                    foreach ($request->purchase as $key => $value) {
                        $quotation_product = QuotationProduct::find($request->purchase[$key]);
                        $new_requisition_product = NewRequisitionProduct::where('new_requisition_id', $request->requisition_id)->where('product_id',$quotation_product->product_id)->first();
                        $purchase_price = $request->purchase_price[$value];
                        $purchase_qty = $request->purchase_qty[$value];
                            
                        $quotation_product->price = $purchase_price;
                        $quotation_product->save();
                        $update_product = Product::find($quotation_product->product_id);
                        $update_product->update(['price'=>$purchase_price]);
                        if($quotation_product->supplier_id == $supplier_value){
                            /*did a mistake here,
                            Here,In the PurchaseProduct Model, quotation_id is really quotation_product_id and
                            quotation_prodcut_id is basically product_id */
                            if($purchased_status == 0){
                                //if not purchased this item
                                $new_purchase_details = PurchaseProduct::create([
                                    'purchase_id' => $new_purchase->id,
                                    'product_id' => $quotation_product->product_id,
                                    'product_unit_id' => $update_product->product_unit_id,
                                    'quotation_id' => $quotation_product->id,
                                    'requisition_id' => $request->requisition_id,//new requisition table id
                                    'requisition_product_id' => $new_requisition_product->id,//new requisition product table id
                                    'quotation_product_id' => $quotation_product->id,
                                    'supplier_id' => $quotation_product->supplier_id,
                                    'qty' => $purchase_qty,
                                    'price' => $purchase_price,
                                ]);
                            }else{
                                $new_purchase_details = PurchaseProduct::where('purchase_id',$new_purchase->id)->where('product_id',$quotation_product->product_id)->first();
                                if(isset($new_purchase_details->id)){
                                    $past_value = $new_purchase_details->qty;
                                    $total_purchase_qty = $past_value + $purchase_qty;

                                    //double was not updating so, total qty has to be made string
                                    $new_purchase_details->update(['qty'=>strval($total_purchase_qty)]);
                                }else{
                                    $new_purchase_details = PurchaseProduct::create([
                                        'purchase_id' => $new_purchase->id,
                                        'product_id' => $quotation_product->product_id,
                                        'product_unit_id' => $update_product->product_unit_id,
                                        'quotation_id' => $quotation_product->id,
                                        'requisition_id' => $request->requisition_id,//new requisition table id
                                        'requisition_product_id' => $new_requisition_product->id,//new requisition product table id
                                        'quotation_product_id' => $quotation_product->id,
                                        'supplier_id' => $quotation_product->supplier_id,
                                        'qty' => $purchase_qty,
                                        'price' => $purchase_price,
                                    ]);
                                }
                                
                                

                            }
                            //double was not updating so, total qty has to be made string
                            $new_requisition_product->update(['po_qty'=>strval($new_requisition_product->po_qty + $purchase_qty)]);
                            $product = Product::find($quotation_product->product_id);
                            if($product != null){
                                $product->last_purchase_order_no = $quotation_product->id;
                                $product->last_purchase_qty = $quotation_product->qty;
                                $product->last_purchase_price = $quotation_product->price;
                                $product->last_purchase_date = $quotation_product->created_at;
                                $product->update();
                                if($product->id){
                                    $TempDataproduct = TempData::where('product_id',$product->id)->first();
                                    if($TempDataproduct !== null){
                                        $TempDataproduct->update(['last_purchase_price' => $quotation_product->price,'last_purchase_date',$quotation_product->created_at]);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return back()->with(['success'=> "Purchase Order Created"]);
            //return redirect('Inventory/purchase-summary')->with(['success'=> "Purchase Order Created"]);
        }else{
            return back()->with(['error'=> "Select at least one product"]);
        }


    }

    public function confirm(Request $request){
        //return $request->all();
        $products = NewRequisitionProduct::where('new_requisition_id', $request->requisition_id)->orderBy('id','asc')->get();
        $new_requisition = NewRequisition::find($request->requisition_id);
        $new_requisition->update(['purchased_status'=>1]);

        if(isset($products[0]->id)){

            foreach ($products as $key => $value) {
                $purchase = Purchase::create([
                    'purchase_id' => getPurchaseId($new_requisition->unit_id),
                    'unit_id' => $new_requisition->unit_id,
                    'requisition_id'=>$request->requisition_id,
                    'quotation_id'=>1,
                    'user_id'=>Auth::id(),
                    'note'=>$request->note,
                ]);
                PurchaseProduct::create([
                    'purchase_id' => $purchase->id,
                    'requisition_id'=>$request->requisition_id,
                    'supplier_id' => $request->supplier_id[$key],
                ]);
                // PurchaseProduct::find($value->id)->update([

                // ]);
            }
        }

        return redirect('/Inventory/purchase-summary')->with(['success'=> "Purchase Order Confirmed"]);
    }
    public function update(Request $request)
    {
        $purchase_id = $request->get('purchase_id');
        $requisition_id = $request->get('requisition_id');
        $quotation_id = $request->get('quotation_id');

        if ($requisition_id != 0 && $quotation_id != 0 ){
            $request['user_id'] = Auth::id();
            $purchase_update = Purchase::query()->find($purchase_id);
            $purchase_update->update($request->all());
            if($purchase_update->id){
                foreach($purchase_update->quotation->quotationProduct as $quotationproduct){
                    $product = Product::find($quotationproduct->product_id);
                    if($product != null){
                        $product->last_purchase_price = $quotationproduct->price;
                        $product->last_purchase_date = $quotationproduct->created_at;
                        $product->update();
                        if($product->id){
                            $TempDataproduct = TempData::where('product_id',$product->id)->first();
                            if($TempDataproduct !== null){
                                $TempDataproduct->update(['last_purchase_price' => $quotationproduct->price,'last_purchase_date',$quotationproduct->created_at]);
                            }
                        }
                    }
                }
            }
            session()->flash('success','Purchase Order Updated!');
            return redirect()->route('inventory.purchase.summary');
        }else{
            session()->flash('failed','Purchase Order could not Update!');
            return redirect()->back();
        }
    }

    public function summaryPurchase(){
        $purchases = Purchase::query()->where(get_where())->orderBy('id','desc')->get();
        return view('inventory.purchase.summary-purchase',compact('purchases'));
    }

    public function printPONo(){
        $purchases = Purchase::query()->where(get_where())->orderBy('id','desc')->get();
        return view('inventory.purchase.print-po-no',compact('purchases'));
    }

    public function deletePurchase($id){
        $purchase = Purchase::find($id);
        $delete_purchase = $purchase->delete();
        $purchase_products = PurchaseProduct::where('purchase_id',$purchase->id)->get();
        $delete_purchase_products = PurchaseProduct::where('purchase_id',$purchase->id)->delete();

        if($delete_purchase && $delete_purchase_products){
            //$update = NewRequisition::where('id',$purchase->requisition_id)->where('unit_id',$purchase->unit_id)->update(['purchased_status' => 0]);
            $update = true;
            $new_requisition_products = NewRequisitionProduct::where('new_requisition_id',$purchase->requisition_id)->get();
            foreach ($new_requisition_products as $key => $value) {
                NewRequisitionProduct::find($value->id)->update(['po_qty'=> PurchaseProduct::where('requisition_product_id',$value->id)->sum('qty')]);
            }
            if($update){
                return response()->json(['success'=>true]);
            }
        }
        return response()->json(['success'=>false]);
    }


    /* Print start */
    public function printPurchaseOrder($id){
        $purchase = Purchase::query()->findOrFail($id);
        return view('inventory.purchase.print-purchase-order',compact('purchase'));
    }

    public function detailPurchaseOrder($id){
        $purchase = Purchase::query()->findOrFail($id);
        return view('inventory.purchase.detail-purchase-order',compact('purchase'));
    }
    /* Print End */

    /* Print start */
    public function mailPurchaseOrder($id){
        $purchase = Purchase::query()->with('supplier')->findOrFail($id);
        $supplier_email =  $purchase->supplier->email;
        $data['purchase'] = $purchase;
        if(filter_var($supplier_email, FILTER_VALIDATE_EMAIL)){
            // $mail = Mail::send('inventory.purchase.mail-purchase-order', $data, function ($message) use ($supplier_email){
            //     $message->from('purchase.wellgarments@gmail.com', 'Purchase Department, Wellgroup')
            //             ->to($supplier_email)
            //             ->subject('Purchase Order');
            // });
            $mail = Mail::to($supplier_email)->send(new PurchaseOrder($purchase));
            if($mail){
                return redirect()->back()->with('success',"Mailed Successfully to ". $supplier_email);
            }else{
                return redirect()->back()->with('error',"Something went wrong!"); 
            }
            
        }else{
             return redirect()->back()->with('error',"Supplier email does not exsits!");
        }
    }
    /* Print End */


}
