Spamworldpro Mini Shell
Spamworldpro


Server : Apache
System : Linux server2.corals.io 4.18.0-348.2.1.el8_5.x86_64 #1 SMP Mon Nov 15 09:17:08 EST 2021 x86_64
User : corals ( 1002)
PHP Version : 7.4.33
Disable Function : exec,passthru,shell_exec,system
Directory :  /home/corals/mcoil.corals.io/app/Http/Controllers/Admin/Orders/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /home/corals/mcoil.corals.io/app/Http/Controllers/Admin/Orders/OrderController.php
<?php

namespace App\Http\Controllers\Admin\Orders;

use App\Shop\Addresses\Repositories\Interfaces\AddressRepositoryInterface;
use App\Shop\Addresses\Transformations\AddressTransformable;
use App\Shop\Couriers\Courier;
use App\Shop\Couriers\CourierRepository;
use App\Shop\Couriers\Repositories\Interfaces\CourierRepositoryInterface;
use App\Shop\Customers\Customer;
use App\Shop\Customers\Repositories\CustomerRepository;
use App\Shop\Customers\Repositories\Interfaces\CustomerRepositoryInterface;
use App\Shop\Orders\Order;
use App\Shop\OrderProducts\OrderProduct;
use App\Shop\ProductAttributes\ProductAttribute;
use App\Shop\FillTanks\FillTank;
use App\Shop\DiscountCoupons\DiscountCoupon;
use App\Shop\Orders\Repositories\Interfaces\OrderRepositoryInterface;
use App\Shop\Orders\Repositories\OrderRepository;
use App\Shop\OrderStatuses\OrderStatus;
use App\Shop\Products\Product;
use App\Shop\Addresses\Address;
use App\Shop\OrderStatuses\Repositories\Interfaces\OrderStatusRepositoryInterface;
use App\Shop\OrderStatuses\Repositories\OrderStatusRepository;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Ramsey\Uuid\Uuid;
use Illuminate\Support\Facades\DB;
use App\Shop\WebsiteSettings\WebsiteSetting;
use Illuminate\Support\Facades\Mail;
use \Stripe\Stripe;
use \Stripe\Customer as Stripe_customer;
use \Stripe\ApiOperations\Create;
use \Stripe\Charge;
use \Stripe\PaymentIntent;
use App\Mail\SendOrderToCustomerMailable;
use App\Shop\Employees\Employee;
use App\Mail\sendEmailNotificationToAdminMailable;
use \Stripe\StripeClient;
use App\Shop\Order\OrderProductPrices;
class OrderController extends Controller {
    use AddressTransformable;

    /**
     * @var OrderRepositoryInterface
     */
    private $orderRepo;

    /**
     * @var CourierRepositoryInterface
     */
    private $courierRepo;

    /**
     * @var CustomerRepositoryInterface
     */
    private $customerRepo;

    /**
     * @var OrderStatusRepositoryInterface
     */
    private $orderStatusRepo;
    private $apiKey;
    private $stripeService;

    public function __construct(
        OrderRepositoryInterface $orderRepository,
        CourierRepositoryInterface $courierRepository,
        CustomerRepositoryInterface $customerRepository,
        OrderStatusRepositoryInterface $orderStatusRepository
    ) {
        $this->orderRepo = $orderRepository;
        $this->courierRepo = $courierRepository;
        $this->customerRepo = $customerRepository;
        $this->orderStatusRepo = $orderStatusRepository;
        $this->middleware(['permission:update-order, guard:employee'], ['only' => ['edit', 'update']]);
        $this->apiKey = config('stripe.secret');
		$this->stripeService = new \Stripe\Stripe();
		$this->stripeService->setVerifySslCerts(false);
        $this->stripeService->setApiKey($this->apiKey);
        $this->elavonUrl = config('constants.evalon_url');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    // public function index() {
    // 	// Fetch all orders except oil one
    //     $list = $this->orderRepo->listOrders('created_at', 'desc');
        
    //     $orders = $this->transFormOrder($list);
    //     // Fetch all oil orders
       
    //     $completedList = $this->orderRepo->listOrdersByFilter(['oil_type_order'=>'1', 'order_status_id'=>'1']);

    //     $list = Order::where('oil_type_order','1')->where('order_status_id','!=','1')->get();

    //   	$oilOrders = $this->transFormOrder($list);
    //     $completedOrders = $this->transFormOrder($completedList);

    //     $orderStatuses = OrderStatus::all();
    //   	//$customerAddress = DB::table('addresses')->where(['id' => $oilOrders->address_id])->first();
    //     // Fetch the drivers
    //     $drivers = Customer::where(['is_driver' => '1'])->get();
    //     return view('admin.orders.list', ['orders' => $orders, 'oilOrders' => $oilOrders, 'drivers' => $drivers, 'orderStatuses' => $orderStatuses, 'completedOrders' => $completedOrders]);
    // }

    /**
     * To create the new product order (for customer)
     *
     * @return \Illuminate\Http\Response
     */
    public function productOrder() {
    	// Fetch the customers list
    	$customers = $this->customerRepo->listCustomers('name', 'ASC');
    	// Fetch the list of products
    	$products = Product::where('status',1)->where('oil_type_status',0)->orderBy('name', 'asc')->get();
    	// Fetch the list of active discount coupons
    	$todayDate = date('Y-m-d');
    	$discountCoupons = DiscountCoupon::whereDate('valid_upto', '>', $todayDate)->get();
    	return view('admin.orders.product-order-create', [
    		'customers' => $customers,
    		'products' => $products,
    		'discountCoupons' => $discountCoupons
    	]);
    }

    /**
     * To save new product order (for customer)
     *
     * @return \Illuminate\Http\Response
     */
    public function saveOrder(Request $request) {
        
    	$customer = $request->get('customer');
    	$discount = $request->get('discount');
    	$paymentOption = $request->get('payment_option');
    	$product = $request->get('product');
    	$quantity = $request->get('quantity');
    	$productCount = count($product);
    	if ($productCount > 0) {
    		$subtotal = 0;
    		$vat = 0;
    		// Itretate the products and do calculation
    		for($i=0; $i<$productCount; $i++) {
    			$productDetails = Product::find($product[$i]);
    			$subtotal += $productDetails->price;
    			$vat += ( ( $productDetails->price * $productDetails->tax ) / 100 );
    		}
    		$total = ( $subtotal + $vat );
    		// Calculate the discount (If applied)
    		$discountAmount = 0;
    		if ($discount != '') {
    			$discountDetails = DiscountCoupon::find($discount);
    			if ($discountDetails->coupon_type == '1') {
    			    // Percentage
    				$discountAmount = ( ( $total * $discountDetails->discount_value ) / 100 );
    			} else {
    			    // Fixed amount
    				$discountAmount = $discountDetails->discount_value;
    			}
    		}
    		$grandTotal = $total - $discountAmount;
    		// Get the address
    		$customerAddress = DB::table('addresses')->where(['customer_id' => $customer, 'status' => '1', 'billing_type_address' => '1'])->first();
    		if ($customerAddress) {
	    		// Start transaction
	    		DB::beginTransaction();
	    		$order = new Order;
	    		$order->courier_id = 1;
	    		$order->reference = Uuid::uuid4()->toString();
	    		$order->customer_id = $customer;
	    		$order->address_id = $customerAddress->id;
	    		$order->order_status_id = 6;	// awaiting payment
	    		$order->payment = 'stripe';
	    		if ($discountAmount > 0) {
	    			$order->discounts = $discountAmount;
		    		$order->discount_coupon_code = $discountDetails->coupon_code;
		    		$order->discount_coupon_type = $discountDetails->coupon_type;
		    		$order->discount_value = $discountDetails->discount_value;
		    		$order->discount_amount = $discountAmount;
	    		}
	    		$order->total_products = $subtotal;
	    		$order->tax = $vat;
	    		$order->total = $grandTotal;
	    		$order->tax_value = $vat;
	    		$order->total_paid = $grandTotal;
	    		$order->billing_address_id = $customerAddress->id;
	    		$order->delivery_address_id = $customerAddress->id;
	    		$order->oil_type_order = '0';
	    		$order->created_by_admin = '1';
	    		// Payment option
	    		$order->payment_option = $paymentOption;
	    		if ($order->save()) {
	    		    $products = ProductAttribute::get();
    	            if(count($products) > 0){
    	                foreach($products as $order_product){
    	                        $orders_prod_insert = new OrderProductPrices;
                                $orders_prod_insert->order_id = $order->id;
                                $orders_prod_insert->product_id = $order_product->product_id;
                                $orders_prod_insert->attribute_id = $order_product->id;
                                $orders_prod_insert->price = $order_product->price;
                                $orders_prod_insert->sale_price = $order_product->sale_price;
                                $orders_prod_insert->save();
    	                }
    	            }
    	            
	    			for($i=0; $i<$productCount; $i++) {
	    				$orderProducts = new OrderProduct;
	    				$orderProducts->order_id 			= $order->id;
	    				$orderProducts->product_id 			= $productDetails->id;
	    				$orderProducts->quantity 			= $quantity[$i];
	    				$orderProducts->product_name 		= $productDetails->name;
	    				$orderProducts->product_sku 		= $productDetails->sku;
	    				$orderProducts->product_description = $productDetails->description;
	    				$orderProducts->product_price 		= $productDetails->price;
	    				$orderProducts->save();
	    			}
	    			DB::commit();
	    			return redirect()->route('admin.orders.index')->with('message', 'Order created successfully.');
	    		} else {
	    			DB::rollBack();
	    			return redirect()->back()->with('error', 'Some error in creating order.');
	    		}
    		} else {
    			return redirect()->back()->with('error', 'No billing address found for the select customer.');
    		}
    	} else {
    		return redirect()->back()->with('error', 'Some error in creating order.');
    	}
    }

    /**
     * To create the new oil order (for customer)
     *
     * @return \Illuminate\Http\Response
     */
    public function oilOrder() {	
    	// Fetch the customers list
    	$customers = $this->customerRepo->listCustomers('lname', 'ASC');
    	// Fetch the list of products
    	$products = Product::where('status',1)->where('oil_type_status',1)->orderBy('name', 'asc')->get();
    	// Fetch the list of active discount coupons
    	$todayDate = date('Y-m-d');
    	$discountCoupons = DiscountCoupon::whereDate('valid_upto', '>', $todayDate)->get();
    	// Fetch the list of county
    	$county_list = DB::table('county')->where('status', '1')->get();
    	$day = date('D');
    	if($day == "Fri" || $day == "Sat" || $day == "Sun"){
    	    $delivery_date = date('Y-m-d', strtotime('next monday'));
    	}else{
    	     $delivery_date = date('Y-m-d', strtotime(' +1 day'));
    	}
        $elavon_user_name = config('elavon.key');
        $elavon_user_password = config('elavon.secret');
        
        $base_inc = base64_encode($elavon_user_name.':'.$elavon_user_password);
        $vendor_name = config('elavon.vendorName');
        
        $ch = curl_init();
        $header = array();
        
        $header[] = 'Content-type: application/json';
        $header[] = 'Authorization: Basic '.$base_inc;
        $payload = json_encode( array( "vendorName"=> $vendor_name ) );

        curl_setopt($ch, CURLOPT_URL,$this->elavonUrl."/api/v1/merchant-session-keys");
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
        //curl_setopt($ch, CURLOPT_POSTFIELDS,"vendorName=Juvotest");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
        $server_output = curl_exec($ch);
        $out = json_decode($server_output);
        $merchantSessionKey = $out->merchantSessionKey;
    	
    	return view('admin.orders.oil-order-create', [
    		'customers' => $customers,
    		'products' => $products,
    		'discountCoupons' => $discountCoupons,
    		'county_list' => $county_list,
    		'delivery_date'=>$delivery_date,
    	
    		'merchantSessionKey'=>$merchantSessionKey
    	]);
    }

    /**
     * To fetch fetch county town list
     *
     * @return \Illuminate\Http\Response
     */
    public function fetchCountyTown(Request $request) {
    	$countyId = $request->get('countyId');
    	$options = '<option value="">TOWN</option>';
    	if ($countyId != '') {
    		// Fetch the town list
    		$countyList = DB::table('town')->where('county_id', $countyId)->get();
    		if ($countyList && $countyList->count() > 0) {
    			foreach( $countyList as $county ) {
    				$options .= '<option value="' . $county->id . '">'. $county->name .'</option>';
    			}
    		}
    	}
    	return response()->json($options);
    }

    /**
     * To fetch customer addresses list
     *
     * @return \Illuminate\Http\Response
     */
    public function fetchCustomerAddresses(Request $request) {
    	$customerId = $request->get('customerId');
    	$options = '<option value="">ADDRESS</option>';
    	if ($customerId != '') {
    		// Fetch the active address list
    		$addresses = Address::where(['customer_id' => $customerId, 'status' => '1'])->get();
    		if ($addresses && $addresses->count() > 0) {
    			foreach( $addresses as $address ) {
    				$options .= '<option value="' . $address->id . '">'. $address->address_1;
    				if (!empty($address->address_2)) {
    				    $options .= ', ' . $address->address_2;
    				}
    				$options .= '</option>';
    			}
    		}
    	}
    	return response()->json($options);
    }

    /**
     * To save new oil order (for customer)
     *
     * @return \Illuminate\Http\Response
     */
     public function saveOilOrder(Request $request) {
        $request->validate([
            'customer' => 'required',
            'address' => 'required',
            'product' => 'required',
            'quantity' => 'required',
        ]);
        $customerId = $request->get('customer');
        $addressId = $request->get('address');
        $countyId = $request->get('county');
        $townId = $request->get('town');
        $productId = $request->get('product');
        $quantityId = $request->get('quantity');
        $discountId = $request->get('discount');
        $deliveryDate = $request->get('delivery_date');
        $quantityAttr = $request->get('quantity_attr');
        $paymentOption = $request->get('payment_option');
        $custom_quantity =0;
        $quote = array();
        if ($quantityId == "fill the tank") {
            $productPrice = $this->oilProductFillTheTankPrice();
            /*if($request->has('product_quantity') && $request->input('product_quantity') != ''){
                $custom_quantity = $request->input('product_quantity');
                
                
            }
            if($request->input('product_price') !=''){
                    $productPrice = $request->input('product_price');    
            }else{
                    $productPrice = $this->getAutoPrice($productId,$custom_quantity);
           }*/
           
           
        } else {
            $productPrice  = $this->oilProductPrice($quantityId);
        }
        
        $productDetails = Product::find($productId);
        $vat = 0;
        if ($productDetails) {
            // vat = ( price * vat_percent / 100 );
            $vat = (($productPrice * $productDetails->tax) / 100);
        }
        $discount = 0;
        $discountCouponCode = '';
        if ($discountId != '') {
            $discountCoupon = DiscountCoupon::find($discountId);
            if ($discountCoupon) {
                $discountCouponCode = $discountCoupon->coupon_code;
                if ($discountCoupon->coupon_type == 1) {
                    $discount = ((($productPrice + $vat) * $discountCoupon->discount_value) / 100);
                } else {
                    $discount = $discountCoupon->discount_value;
                }
            }
        }
        $totalProducts = $productPrice;
        $total = (($productPrice + $vat) - $discount);
        DB::beginTransaction();
        $order = new Order;
        $order->reference = Uuid::uuid4()->toString();
        $order->courier_id = 1;
        $order->customer_id = $customerId;
        $order->address_id = $addressId;
        $order->order_status_id = 6;    // Awaiting payment
        $order->payment = 'Stripe';
        if ($discountId != '') {
            $order->discounts = $discount;
            $order->discount_coupon_code = $discountCoupon->coupon_code;
            $order->discount_coupon_type = $discountCoupon->coupon_type;
            $order->discount_value = $discountCoupon->discount_value;
            $order->discount_amount = $discount;
        }
        $order->total_products = $totalProducts;
        $order->total_shipping = 0;
        $order->tax = $vat;
        $order->total = $total;
        $order->tax_percentage = $productDetails->tax;
        $order->tax_value = $vat;
        $order->total_paid = $total;
        $order->billing_address_id = $addressId;
        $order->delivery_address_id = $addressId;
        $order->order_county_id = $countyId;
        $order->order_town_id = $townId;
        $order->transaction_status = ($paymentOption == 'Credit Card') ? "requires_payment_method" : "other_payment";
        if ($quantityId == "fill the tank") {
            $order->fill_the_tank_status = '1';
            if($custom_quantity > 0){
                $order->fill_the_tank_quantity = $custom_quantity;
            }
        } else {
            $order->fill_the_tank_status = '0';
        }
        $order->delivery_date = date('Y-m-d', strtotime(str_replace("/", "-", $deliveryDate)));
        $order->delivery_note = $request->delivery_note;
        $order->oil_type_order = '1';
        $order->created_at = date('Y-m-d H:i:s');
        $order->created_by_admin = '1';
        // Payment option
        $order->payment_option = $paymentOption;
        if ($order->save()) {
            // Get the product attributes
            $productAttribute = ProductAttribute::where(['product_id' => $productId, 'quantity' => $quantityAttr])->first();
            $orderProducts = new OrderProduct;
            $orderProducts->order_id = $order->id;
            $orderProducts->product_id = $productDetails->id;
            if (empty($productAttribute)) {
                $orderProducts->product_attribute_id = '1';
                $orderProducts->quantity = '0';
            } else {
                $orderProducts->product_attribute_id = $productAttribute->id;
                $orderProducts->quantity = $quantityAttr;
            }
            $orderProducts->product_name = $productDetails->name;
            $orderProducts->product_sku = $productDetails->sku;
            $orderProducts->product_description = $productDetails->description;
            $orderProducts->product_price = $productPrice;
            if ($orderProducts->save()) {
                $products = ProductAttribute::get();
                    if(count($products) > 0){
                        foreach($products as $order_product){
                                $orders_prod_insert = new OrderProductPrices;
                                $orders_prod_insert->order_id = $order->id;
                                $orders_prod_insert->product_id = $order_product->product_id;
                                $orders_prod_insert->attribute_id = $order_product->id;
                                $orders_prod_insert->price = $order_product->price;
                                $orders_prod_insert->sale_price = $order_product->sale_price;
                                $orders_prod_insert->save();
                        }
                    }
                    $fill_in_tank_price = FillTank::first();
                    if($fill_in_tank_price){
                        $orders_prod_insert = new OrderProductPrices;
                        $orders_prod_insert->order_id = $order->id;
                        $orders_prod_insert->product_id = 0;
                        $orders_prod_insert->attribute_id = 0;
                        $orders_prod_insert->price = $productPrice;
                        $orders_prod_insert->quantity = $custom_quantity;
                        $orders_prod_insert->save();
                    }
              //  if($request->token){
              //      $orderId = $order->id;
              //      $orderDetails = Order::find($orderId);
        //             $orderProduct = OrderProduct::where(['order_id' => $orderId])->first();
        //             $productDetails = Product::find($orderProduct->product_id);
        //             $customer_data = Customer::find($orderDetails->customer_id);
        //             $data['emailFrom'] = \Config::get('values.MAIL_FROM');

        //             try {
        //                 $stripe_client = new StripeClient($this->apiKey);
        //                 $payment_data = $stripe_client->paymentMethods->create([
        //                     'type' => 'card',
        //                     'card' => [
        //                       'number' => base64_decode($request->input('number')),
        //                       'exp_month' => base64_decode($request->input('month')),
        //                       'exp_year' => base64_decode($request->input('year')),
        //                       'cvc' => base64_decode($request->input('track_id')),
        //                     ],
        //                      'billing_details'=> [
        //                          'name'=> $request->input('name')
        //                          ]
        //                   ]);

        //                 $customerDetailsAry = array(
        //                     'email' => $customer_data->email,
        //                     'source' => $request->token
        //                 );
        //                 // Adding stripe customer
        //                 $customerResult = $this->addCustomer($customerDetailsAry);
        //                 // Payment Intent Customer -- START
        //                 $payment_intent = new PaymentIntent();
        //                 $payment_intent_data = array(
        //                     'customer'              => $customerResult->id,
        //                     'amount'                => $orderDetails->total_paid * 100, // Tax is added here
        //                     'currency'              => $request->currency_code,
        //                     'description'           => $productDetails->name,
        //                     'payment_method_types'  => ['card'],
        //                     'capture_method'        => 'manual',
        //                     'payment_method'=>$payment_data->id,
        //                     'metadata'              => array(
        //                         'order_id'    => $orderId
        //                     ),
        //                     'shipping' => [
        //                         'name' => $customer_data->name,
        //                         'address' => [
        //                           'line1' => $orderDetails->address->address_1,
        //                           'postal_code' => $orderDetails->address->zip,
        //                           'city' => $orderDetails->address->town,
        //                           'state' => $orderDetails->address->town,
        //                           'country' => 'IE',
        //                         ],
        //                     ],
        //                 );
        //                 $result = $payment_intent->create($payment_intent_data);
        //                 //dd($result);
        //             }
        //             catch(\Stripe\Exception\CardException $e) {
        //               // Since it's a decline, \Stripe\Exception\CardException will be caught
        //                 DB::rollBack();
        //                 \Log::info(print_r($e->getError()->message,true));
        //                 return redirect()->back()->with('error', $e->getError()->message);
        //             } catch (\Stripe\Exception\RateLimitException $e) {
        //                 DB::rollBack();
        //                 \Log::info(print_r($e->getError()->message,true));
        //                 return redirect()->back()->with('error', $e->getError()->message);
        //               // Too many requests made to the API too quickly
        //             } catch (\Stripe\Exception\InvalidRequestException $e) {
        //                 DB::rollBack();
        //                 \Log::info(print_r($e->getError()->message,true));
        //                 return redirect()->back()->with('error', $e->getError()->message);
        //               // Invalid parameters were supplied to Stripe's API
        //             } catch (\Stripe\Exception\AuthenticationException $e) {
        //                 DB::rollBack();
        //                 \Log::info(print_r($e->getError()->message,true));
        //                 return redirect()->back()->with('error', $e->getError()->message);
        //               // (maybe you changed API keys recently)
        //             } catch (\Stripe\Exception\ApiConnectionException $e) {
        //                 DB::rollBack();
        //                 \Log::info(print_r($e->getError()->message,true));
        //                 return redirect()->back()->with('error', $e->getError()->message);
        //               // Network communication with Stripe failed
        //             } catch (\Stripe\Exception\ApiErrorException $e) {
        //                 DB::rollBack();
        //                 \Log::info(print_r($e->getError()->message,true));
        //                 return redirect()->back()->with('error', $e->getError()->message);
        //               // Display a very generic error to the user, and maybe send
        //               // yourself an email
        //             } catch (Exception $e) {
        //                 DB::rollBack();
        //                 \Log::info(print_r($e->getError()->message,true));
        //                 return redirect()->back()->with('error', $e->getError()->message);
        //               // Something else happened, completely unrelated to Stripe
        //             }
        //             $serialized_result = $result->jsonSerialize();
        //             if ($serialized_result['status'] == 'requires_payment_method' || $serialized_result['status'] == 'requires_confirmation') {
        //                 $orderDetails->order_status_id = 2;     # on-delivery
        //             } else {
        //                 $orderDetails->order_status_id = 3; # error
        //             }
        //             $orderDetails->transaction_id       = $serialized_result['id'];
        //             $orderDetails->stripe_customer_id   = $serialized_result['customer'];
        //             $orderDetails->transaction_status   = $serialized_result['status'];
        //             $orderDetails->save();
              //  }
            
              if($request->merchent_key){
                        $orderId = $order->id;
                   $orderDetails = Order::find($orderId);
                    $orderProduct = OrderProduct::where(['order_id' => $orderId])->first();
                    $productDetails = Product::find($orderProduct->product_id);
                    $customer_data = Customer::find($orderDetails->customer_id);
                   $data['emailFrom'] = \Config::get('values.MAIL_FROM');
                   $address = Address::where('customer_id',$orderDetails->customer_id)->first();
                    $elavon_user_name = config('elavon.key');
            $elavon_user_password = config('elavon.secret');
            $base_inc = base64_encode($elavon_user_name.':'.$elavon_user_password);
            $vendor_name = config('elavon.vendorName');
            $order_total = round($total,2);
           $elav_order_total = $order_total * 100;
           //$elav_order_total = number_format($order_total,2);
            
            $ch = curl_init();
            $header = array();
           
            $header[] = 'Content-type: application/json';
            $header[] = 'Authorization: Basic '.$base_inc;
            $payload = json_encode( array( "vendorName"=> $vendor_name ) );
                $card_identifier = $request->input('card-identifier');
                $ms = $request->input('merchent_key');
                
                $payment_payload = json_encode( array(
                    "transactionType"=> $orderDetails->fill_the_tank_status == '1' ? "Deferred" : "Payment",
                    "paymentMethod"=>array('card' => array("merchantSessionKey"=>$ms,"cardIdentifier"=>$card_identifier,
                    "save"=> false
                )),
                    "vendorTxCode"=>"oil-".rand(),
                    "amount"=> (int)$elav_order_total,
                    "currency"=> "EUR",
                    "description"=> "Oil Order",
                    "customerFirstName"=> $customer_data->fname,
                    "customerLastName"=> $customer_data->lname,
                    "customerEmail"=> $customer_data->email,
                    "billingAddress"=>array("address1"=>$address->address_1,"postalCode"=>$address->zip,"city"=> $address->town,"country"=> 'IE'),
                    "entryMethod"=> "Ecommerce",
                    "apply3DSecure"=> "Force",
                     "strongCustomerAuthentication"=>array("notificationURL"=> route('admin.threed.secure'),
                  "browserIP"=> $_SERVER['REMOTE_ADDR'],
                        "browserAcceptHeader"=> "\\*/\\*",
                        "browserJavascriptEnabled"=> false,
                        
                        "browserLanguage"=> substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2),
                       
                        "browserUserAgent"=> "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:67.0) Gecko/20100101 Firefox/67.0",
                        "challengeWindowSize"=> "Small",
                       
                        "transType"=> "GoodsAndServicePurchase",
                )
                    
                ));
                
                curl_setopt($ch, CURLOPT_URL,$this->elavonUrl."/api/v1/transactions");
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $payment_payload);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
                $server_output_pay = curl_exec($ch);
                $serialized_result = json_decode($server_output_pay);
                if(isset($serialized_result->status) && $serialized_result->status == '3DAuth'){
                    
                    $transData = [];
                    $transData['paReq'] = $serialized_result->cReq;
                    $transData['acsUrl'] = $serialized_result->acsUrl;
                    $transData['ref'] = $order->id;
                    $transData['url'] = route('admin.threed.secure');
                    $orderDetails->transaction_id = $serialized_result->transactionId;
                    $orderDetails->payment = 'Credit Card';
                    $orderDetails->save();
                    DB::commit();
                    return view('auth.threedsecure',$transData);
                }else if(isset($serialized_result->status) && $serialized_result->status == 'Ok'){
                    $orderDetails->order_status_id = 1; 
                    $orderDetails->transaction_id       = $serialized_result->transactionId;
                    $orderDetails->transaction_status   = (isset($serialized_result->transactionType) && $serialized_result->transactionType == 'Deferred') ? 'requires_confirmation' : 'succeeded';
                    $orderDetails->save();
                    DB::commit();
                    return redirect()->route('admin.orders.index')->with('message', 'Order created successfully.');
                }else{
                    DB::rollBack();
                    return redirect()->back()->with('error', 'Some error in creating order.');        
                }
                \Log::info(print_r($serialized_result,true));
                //dd($serialized_result);
                // try{
                //      if ($serialized_result->status == 'Ok' || $serialized_result->transactionType == 'Deferred' || $serialized_result->transactionType == 'Payment') {
                //           $orderDetails->order_status_id = 2;     # on-delivery
                //       } else {
                //             $orderDetails->order_status_id = 3; # error
                //         }
                //         $orderDetails->transaction_id       = $serialized_result->transactionId;
                //         $orderDetails->transaction_status   = (isset($serialized_result->transactionType) && $serialized_result->transactionType != '') ? 'requires_confirmation' : 'other_payment';
                //          $orderDetails->payment = 'Credit Card';
                //         $orderDetails->save();
                // }
                // catch(Exception $e) {
                //      \Log::info('Message: ' .$e->getMessage());
                //      DB::rollBack();
                //     return redirect()->back()->with('error', 'Some error in creating order.');
                //  }
                 /*if ($serialized_result->transactionType == 'Deferred') {
                       $orderDetails->order_status_id = 2;     # on-delivery
                  } else {
                        $orderDetails->order_status_id = 3; # error
                    }
                    $orderDetails->transaction_id       = $serialized_result->transactionId;
                    $orderDetails->transaction_status   = (isset($serialized_result->transactionType) && $serialized_result->transactionType != '') ? 'requires_confirmation' : 'other_payment';
                     $orderDetails->payment = 'Credit Card';
                    $orderDetails->save();*/
              }
                DB::commit();
                return redirect()->route('admin.orders.index')->with('message', 'Order created successfully.');
            } else {
                DB::rollBack();
                return redirect()->back()->with('error', 'Some error in creating order.');
            }
        } else {
            DB::rollBack();
            return redirect()->back()->with('error', 'Some error in creating order.');
        }
    }


    /**
     * Display the specified resource.
     *
     * @param  int $orderId
     * @return \Illuminate\Http\Response
     */
    public function show($orderId) {
      
        $order = $this->orderRepo->findOrderById($orderId);
        $orderRepo = new OrderRepository($order);
        $order->courier = $orderRepo->getCouriers()->first();
        // $order->address = $orderRepo->getAddresses()->first();
        $orderAddress = DB::table('addresses')->where('id', $order->delivery_address_id)->first();
        $items = $orderRepo->listOrderedProducts();
        $elavon_user_name = config('elavon.key');
	    $elavon_user_password = config('elavon.secret');
	    
	    $base_inc = base64_encode($elavon_user_name.':'.$elavon_user_password);
        $vendor_name = config('elavon.vendorName');
        
        $ch = curl_init();
        $header = array();
        
        $header[] = 'Content-type: application/json';
        $header[] = 'Authorization: Basic '.$base_inc;
        $payload = json_encode( array( "vendorName"=> $vendor_name ) );
        
        curl_setopt($ch, CURLOPT_URL,$this->elavonUrl."/api/v1/merchant-session-keys");
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
        //curl_setopt($ch, CURLOPT_POSTFIELDS,"vendorName=Juvotest");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
        $server_output = curl_exec($ch);
        $out = json_decode($server_output);
      
        $merchantSessionKey = $out->merchantSessionKey;
        // Driver
        $driver = Customer::find($order->driver_id);
        // Fetch order status list
        $orderStatuses = OrderStatus::all();
        $created_date = strtotime($order->delivery_date);
        $day = date('D', $created_date);
        /*if($day == 'Fri' || $day == 'Sat' || $day == 'Sun'){
            $delivery_date =  date('d/m/Y', strtotime('next monday', strtotime($order->delivery_date)));
        }else{
            $delivery_date = date('d/m/Y', strtotime($order->delivery_date));
        }*/
        if($order->order_status != 1 ||  $order->completed_date == null){
            $delivery_date = date('d/m/Y', strtotime($order->delivery_date));    
        }else{
            $delivery_date = date('d/m/Y @ H:i:a', strtotime($order->completed_date));
        }
        if ($order->oil_type_order == '1') {
            
        	// Fetch the list of products
        	$products = Product::where('status',1)->where('oil_type_status',1)->orderBy('name', 'asc')->get();
        	// Get the today's date
        	$todayDate = date('Y-m-d');
        	// Fetch the list of active discount coupons
        	$discountCoupons = DiscountCoupon::whereDate('valid_upto', '>', $todayDate)->get();
        	// Fetch the list of applied coupon codes
        	$appliedDiscounts = Order::where('customer_id', '=', $order->customer_id)->where('id', '!=', $order->id)->pluck('discount_coupon_code')->all();
        	// Fetch the selected product quatities
        	$productQuantities = DB::table('product_attributes')
                ->leftJoin('attribute_value_product_attribute', 'attribute_value_product_attribute.product_attribute_id', '=', 'product_attributes.id')
                ->leftJoin('attribute_values','attribute_values.id','=','attribute_value_product_attribute.attribute_value_id')
                ->leftJoin('attributes','attributes.id','=','attribute_values.attribute_id')
                ->select('product_attributes.id','attributes.name','attribute_values.value')
                ->where('product_attributes.product_id', $items[0]->id)
                ->orderBy('attribute_values.value', 'asc')
                ->get();
             $stripe_key = config('stripe.key');
        	return view('admin.orders.show', [
        	    'order' => $order,
        	    'items' => $items,
        	    'customer' => $this->customerRepo->findCustomerById($order->customer_id),
        	    'currentStatus' => $this->orderStatusRepo->findOrderStatusById($order->order_status_id),
        	    'payment' => $order->payment,
        	    'user' => auth()->guard('employee')->user(),
        	    'driver' => $driver,
        	    'orderStatuses' => $orderStatuses,
        	    // For edit purpose
        	    'products' => $products,
        	    'discountCoupons' => $discountCoupons,
        	    'appliedDiscounts' => $appliedDiscounts,
        	    'productQuantities' => $productQuantities,
        	    // Delivery addresses
        	    'orderAddress' => $orderAddress,
                'delivery_date'=>$delivery_date,
                'merchantSessionKey'=>$merchantSessionKey
        	]);
      	} else {
      	    
      		// Fetch the list of products
      		$products = Product::where('status',1)->where('oil_type_status',0)->orderBy('name', 'asc')->get();
      		// Get the today's date
      		$todayDate = date('Y-m-d');
			// Fetch the list of active discount coupons
      		$discountCoupons = DiscountCoupon::whereDate('valid_upto', '>', $todayDate)->get();
      		// Fetch the list of applied coupon codes
    		$appliedDiscounts = Order::where('customer_id', '=', $order->customer_id)->where('id', '!=', $order->id)->pluck('discount_coupon_code')->all();
    		$stripe_key = config('stripe.key');
      		return view('admin.orders.show', [
      		    'order' => $order,
      		    'items' => $items,
			    'customer' => $this->customerRepo->findCustomerById($order->customer_id),
      		    'currentStatus' => $this->orderStatusRepo->findOrderStatusById($order->order_status_id),
      		    'payment' => $order->payment,
      		    'user' => auth()->guard('employee')->user(),
      		    'driver' => $driver,
      		    'orderStatuses' => $orderStatuses,
      		    // For edit purpose
      		    'products' => $products,
      		    'discountCoupons' => $discountCoupons,
      		    'appliedDiscounts' => $appliedDiscounts,
      		    // Delivery addresses
    	    	'orderAddress' => $orderAddress,
                'delivery_date'=>$delivery_date,
                'stripe_key'=>$stripe_key,
                'merchantSessionKey'=>$merchantSessionKey
  			]);
      	}
    }

    /**
     * @param $orderId
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit($orderId) {
        $order = $this->orderRepo->findOrderById($orderId);
        $orderRepo = new OrderRepository($order);
        $order->courier = $orderRepo->getCouriers()->first();
        $order->address = $orderRepo->getAddresses()->first();
        $items = $orderRepo->listOrderedProducts();
        if ($order->oil_type_order == '1') {
        	// Fetch the list of products
        	$products = Product::where('status',1)->where('oil_type_status',1)->orderBy('name', 'asc')->get();
        	// Get the today's date
        	$todayDate = date('Y-m-d');
        	// Fetch the list of active discount coupons
        	$discountCoupons = DiscountCoupon::whereDate('valid_upto', '>', $todayDate)->get();
        	// Fetch the list of applied coupon codes
        	$appliedDiscounts = Order::where('customer_id', '=', $order->customer_id)->where('id', '!=', $order->id)->pluck('discount_coupon_code')->all();
        	// Fetch the selected product quatities
        	$initialProductQuantites = DB::table('product_attributes')
        	    ->leftJoin('attribute_value_product_attribute', 'attribute_value_product_attribute.product_attribute_id', '=', 'product_attributes.id')
                ->leftJoin('attribute_values','attribute_values.id','=','attribute_value_product_attribute.attribute_value_id')
        	    ->leftJoin('attributes','attributes.id','=','attribute_values.attribute_id')
        	    ->select('product_attributes.id','attributes.name','attribute_values.value')
        	    ->where('product_attributes.product_id', $items[0]->id)
        	    ->orderBy('attribute_values.value', 'asc')
        	    ->get();
        	return view('admin.orders.oil-order-edit', [
        	    'statuses' => $this->orderStatusRepo->listOrderStatuses(),
        	    'order' => $order,
        	    'items' => $items,
        	    'customer' => $this->customerRepo->findCustomerById($order->customer_id),
        	    'currentStatus' => $this->orderStatusRepo->findOrderStatusById($order->order_status_id),
        	    'payment' => $order->payment,
        	    'user' => auth()->guard('employee')->user(),
        	    'products' => $products,
        	    'discountCoupons' => $discountCoupons,
        	    'initialProductQuantites' => $initialProductQuantites,
        	    'appliedDiscounts' => $appliedDiscounts
        	]);
        } else {
        	return view('admin.orders.edit', [
        	    'statuses' => $this->orderStatusRepo->listOrderStatuses(),
        	    'order' => $order,
        	    'items' => $items,
        	    'customer' => $this->customerRepo->findCustomerById($order->customer_id),
        	    'currentStatus' => $this->orderStatusRepo->findOrderStatusById($order->order_status_id),
        	    'payment' => $order->payment,
        	    'user' => auth()->guard('employee')->user()
        	]);
        }
    }

    /**
     * @param Request $request
     * @param $orderId
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, $orderId) {
        $order = $this->orderRepo->findOrderById($orderId);
        $orderRepo = new OrderRepository($order);
        if ($request->has('total_paid') && $request->input('total_paid') != null) {
            $orderData = $request->except('_method', '_token');
        } else {
            $orderData = $request->except('_method', '_token', 'total_paid');
        }
        $orderRepo->updateOrder($orderData);
        return redirect()->route('admin.orders.edit', $orderId);
    }

    /**
     * Generate order invoice
     *
     * @param int $id
     * @return mixed
     */
    public function generateInvoice(int $id) {
        $setting = WebsiteSetting::first();
        $order = $this->orderRepo->findOrderById($id);
        $address = DB::table('addresses')->where('id', $order->delivery_address_id)->first();
        $data = [
            'order' => $order,
            'products' => $order->products,
            'customer' => $order->customer,
            'courier' => $order->courier,
            'address' 	=> $address,
            'status' => $order->orderStatus,
            'payment' => $order->paymentMethod,
            'setting' => $setting
        ];
        // For debugging purpose
        //return view('invoices.orders', $data);
        $pdf = app()->make('dompdf.wrapper');
        $pdf->loadView('invoices.orders', $data)->stream();
        return $pdf->stream();
    }

    /**
     * Generate order invoice
     *
     * @param int $id
     * @return mixed
     */
    public function invoiceDetails(Request $request) {
        $setting = WebsiteSetting::first();
    	$orderId = $request->get('orderId');
    	$order = $this->orderRepo->findOrderById($orderId);
    	$address = DB::table('addresses')->where('id', $order->delivery_address_id)->first();
    	$created_date = strtotime($order->delivery_date);
        $day = date('D', $created_date);
       
        if($day == 'Sat' || $day == 'Fri' || $day == 'Sun'){
            $delivery_date =  date('d/m/Y', strtotime('next monday', strtotime($order->delivery_date)));
        }else{
            $delivery_date = date('d/m/Y', strtotime($order->delivery_date));
        }
        $data = [
            'order' 	=> $order,
            'products' 	=> $order->products,
            'customer' 	=> $order->customer,
            'courier' 	=> $order->courier,
            'address' 	=> $address,
            'status' 	=> $order->orderStatus,
            'payment' 	=> $order->paymentMethod,
            'setting' => $setting,
            'delivery_date'=>$delivery_date
        ];
        $htmlResponse 	= view('invoices.admin-orders', $data)->render();
        return response()->json($htmlResponse);
    }

    /**
     * @param Collection $list
     * @return array
     */
    private function transFormOrder(Collection $list) {
        $courierRepo = new CourierRepository(new Courier());
        $customerRepo = new CustomerRepository(new Customer());
        $orderStatusRepo = new OrderStatusRepository(new OrderStatus());
        return $list->transform(function (Order $order) use ($courierRepo, $customerRepo, $orderStatusRepo) {
            $order->courier = $courierRepo->findCourierById($order->courier_id);
            $order->customer = $customerRepo->findCustomerById($order->customer_id);
            $order->status = $orderStatusRepo->findOrderStatusById($order->order_status_id);
            return $order;
        })->all();
    }

    /**
     * @param Request $request
     * @param $orderId
     *
     * @return array
     */
    public function statusUpdate(Request $request) {
    	$orderId = $request->get('orderId');
    	$status  = $request->get('status');
        $order =  Order::where(['id' => $orderId])->first();
        $completed_date = date('Y-m-d H:i:s');
        if($request->order_main_status){
            if($status == '1'){
                 $updateArray = ['order_status' => $status,'transaction_status'=>'succeeded','completed_date'=>$completed_date];
            }else{
                
                if($order->payment_option != 'Credit Card'){
                    $updateArray = ['order_status' => $status,'transaction_status'=>'other_payment','completed_date'=>''];    
                }else{
                    $updateArray = ['order_status' => $status,'transaction_status'=>'requires_payment_method','completed_date'=>'']; 
                }
                
            }
           
        }
       
        else{
            $updateArray = ['order_status_id' => $status];
        }

    	$response = array();
    	if ($orderId != '' && $status != '') {
    		if (Order::where(['id' => $orderId])->update($updateArray)) {
    			$response = array(
    				'status' => 1,
    				'msg' => 'Status updated successfully'
    			);
    		} else {
    			$response = array(
	    			'status' => 2,
	    			'msg' => 'Some error'
	    		);
    		}
    	} else {
    		$response = array(
    			'status' => 3,
    			'msg' => 'Some error'
    		);
    	}
    	return response()->json($response);
    }

    /**
     * @param Request $request
     * @param $orderId
     *
     * @return array
     */
    public function paymentOptionUpdate(Request $request) {
    	$orderId = $request->get('orderId');
    	$paymentOption = $request->get('paymentOption');
    	$response = array();
    	$order =  Order::where(['id' => $orderId])->first();
    	if ($orderId != '' && $paymentOption != '') {
            if($paymentOption == 'Credit Card'){
                if($order->order_status == '1'){
                   $update_order_status = Order::where(['id' => $orderId])->update(['payment_option' => $paymentOption,'order_status_id'=>'6']); 
                }else{
                    $update_order_status = Order::where(['id' => $orderId])->update(['payment_option' => $paymentOption,'order_status_id'=>'6','transaction_status'=>'requires_payment_method']);
                }
                
            }else{
                 if($order->order_status == '1'){
                   $update_order_status = Order::where(['id' => $orderId])->update(['payment_option' => $paymentOption]); 
                }else{
                    $update_order_status = Order::where(['id' => $orderId])->update(['payment_option' => $paymentOption,'transaction_status'=>'other_payment']);
                }
                
            }
    		if ($update_order_status) {
    			$response = array(
    				'status' => 1,
    				'msg' => 'New payment option has been assigned'
    			);
    		} else {
    			$response = array(
	    			'status' => 2,
	    			'msg' => 'Some error'
	    		);
    		}
    	} else {
    		$response = array(
    			'status' => 3,
    			'msg' => 'Some error'
    		);
    	}
    	return response()->json($response);
    }

    /**
     * @param Request $request
     * @param $orderId
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy(Request $request, $id) {
    	if ($id != '') {
    		$redirection_url = $request->redirection_url;
    		// Start transaction
    		DB::beginTransaction();
    		if (OrderProduct::where(['order_id' => $id])->delete()) {
    			if (Order::where(['id' => $id])->delete()) {
    				DB::commit();
    				if (!empty($redirection_url)) {
    				    return redirect()->back();
    				} else {
    				    return redirect()->route('admin.orders.index');
    				}
    			} else {
    				DB::rollBack();
    				if (!empty($redirection_url) && $redirection_url == 'customers') {
    				    return redirect()->back();
    				} else {
    				    return redirect()->route('admin.orders.index')->with('error', 'Error occurred with the deletion!');
    				}
    			}
    		} else {
    			DB::rollBack();
    			if (!empty($redirection_url) && $redirection_url == 'customers') {
    			    return redirect()->route('admin.customers.index')->with('error', 'Error occurred with the deletion!');
    			} else {
    			    return redirect()->route('admin.orders.index')->with('error', 'Error occurred with the deletion!');
    			}
    		}
    	}
    }

    // To fetch oil product attributes / Quantities
    public function fetchOilProductAttributes(Request $request) {
        // Here we are showing combination of [Attribute:Attribute value]
        // Fetch product_attributes_id from product_attributes table
        $product_attributes_data = DB::table('product_attributes')
            ->leftJoin('attribute_value_product_attribute', 'attribute_value_product_attribute.product_attribute_id', '=', 'product_attributes.id')
            ->leftJoin('attribute_values','attribute_values.id','=','attribute_value_product_attribute.attribute_value_id')
            ->leftJoin('attributes','attributes.id','=','attribute_values.attribute_id')
            ->select('product_attributes.id','attributes.name','attribute_values.value')
            ->where('product_attributes.product_id',$request->product_id)
            ->orderBy('attribute_values.value', 'asc')
            ->get();
        $output="<option value=''>QUANTITY</option><option value='fill the tank'>Fill The Tank</option>";
        foreach($product_attributes_data as $product_attributes) {
            $output .="<option data-qty=".$product_attributes->value." value='".$product_attributes->id."'>".$product_attributes->name." : ".$product_attributes->value."</option>";
        }
        return response()->json($output);
    }

    // To calculate new quote
    public function calculateNewQuote(Request $request) {
    	$productId 	= $request->get('productId');
    	$productQty	= $request->get('productQty');
    	$discountId	= $request->get('discountId');
    	$quote = array();
    	if ($productQty == "fill_the_tank" || $productQty == "fill the tank") {
    	    $productPrice = $this->oilProductFillTheTankPrice();
    	} else {
    	    $productPrice  = $this->oilProductPrice($productQty);
    	}
    	$productDetails = Product::find($productId);
    	$vat = 0;
    	if( $productDetails ) {
    		// vat = ( price * vat_percent / 100 );
    		$vat = ( ( $productPrice * $productDetails->tax ) / 100 );
    	}
    	$discount = 0;
    	$discountCouponCode = '';
    	if ($discountId != '') {
    		$discountCoupon = DiscountCoupon::find($discountId);
    		if ($discountCoupon) {
    			$discountCouponCode = $discountCoupon->coupon_code;
    			if ($discountCoupon->coupon_type == 1) {
    				$discount = ((($productPrice + $vat) * $discountCoupon->discount_value) / 100);
    			} else {
    				$discount = $discountCoupon->discount_value;
    			}
    		}
    	}
    	$quote = array(
    		'subtotal' => number_format($productPrice, 2),
    		'vat' => number_format($vat, 2),
    		'discountCouponCode' => $discountCouponCode,
    		'discount' => number_format($discount, 2),
    		'total' => number_format((($productPrice + $vat) - $discount), 2)
    	);
    	return response()->json($quote);
    }

    // To get the fill_the_tank_price value
    public function oilProductFillTheTankPrice() {
        $fill_tank_data = FillTank::find(1);
        if (!empty($fill_tank_data->price)) {
            return $fill_tank_data->price;
        }
    }

    // To get the 
    public function oilProductPrice($product_attribute_id) {
    	$attribute_data = ProductAttribute::find($product_attribute_id);
        return $attribute_data->price;
    }

    // To update the order
    public function updateOrder(Request $request) {
    	$orderType = $request->get('orderType');
    	if ($orderType == 'oil') {
    		$orderId = $request->get('orderId', '');
    		$productId = $request->get('productId');
    		$productQty = $request->get('productQty', 0);
    		$productAttrId = $request->get('productAttrId');
    // 		if ($productQty == "fill_the_tank" || $productQty == "fill the tank" || $productAttrId == "fill_the_tank") {
    // 		    $productPrice = $this->oilProductFillTheTankPrice($orderId);
    // 		} else {
    // 		    $productPrice  = $this->oilProductPrice($productAttrId);
    // 		}
            $productPrice  = $request->input('price');
            $productPrice = str_replace( ',', '', $productPrice );
    		$product = Product::find($productId);
    		$prod_attr = ProductAttribute::where('product_id',$productId)->where('quantity',$productQty)->first();
    		if($prod_attr){
    		    $productAttrId = $prod_attr->id;
    		}else{
    		     $productAttrId = 0;
    		}
    		$vat = 0;
    		if ($product) {
    			$vat = (($productPrice * $product->tax) / 100);
    		}
    		$order = Order::find($orderId);
    		// If the applied discount is of percentage type then calculate the discount again
    		$discountAmount = 0;
    		if ($order && $order->discount_coupon_type == '1') {
    			$discountAmount = ((($productPrice + $vat) * $order->discount_value) / 100);
    		} else {
    			$discountAmount = $order->discount_value;
    		}
    		$subtotal = $productPrice;
    		$total = ($subtotal + $vat) - $discountAmount;
    		$response = array();
    		if (!empty($orderId)) {
    			// Start transaction
    			DB::beginTransaction();
    			$order = Order::where(['id' => $orderId])->first();
    			$order->total_products = $subtotal;
    			$order->tax = $vat;
    			$order->total = $total;
    			$order->tax_value = $vat;
    			$order->total_paid = $total;
    			$order->updated_by_admin = '1';
    			$order->fill_the_tank_status = ($productQty > 0) ? 0 : 1;
    			// Include the discount column as well, if it is updated
    			if ($discountAmount != $order->discount_amount) {
    				$order->discounts = $discountAmount;
    				$order->discount_amount = $discountAmount;
    			}
    			if ($order->save()) {
    				$orderProduct = OrderProduct::where(['order_id' => $orderId])->first();
    				$orderProduct->product_id = $productId;
    				$orderProduct->product_attribute_id = $productAttrId;
    				$orderProduct->quantity = $productQty;
    				$orderProduct->product_name = $product->name;
    				$orderProduct->product_sku = $product->sku;
    				$orderProduct->product_description = $product->description;
    				$orderProduct->product_price = $subtotal;
    				if ($orderProduct->save()) {
    					DB::commit();
    					$response = array(
    						'status' => 1,
    						'msg' => 'Quote updated successfully',
    						'data' => array(
    							'subtotal' => number_format($subtotal, 2),
    							'vat' => number_format($vat, 2),
    							'discount' => number_format((is_null($discountAmount) ? 0: $discountAmount), 2),
    							'grandtotal' => number_format(($subtotal + $vat) - $discountAmount, 2),
    							'product_name' => $product->name,
    							'product_qty'  => $productQty,
    						)
    					);
    				} else {
    					DB::rollBack();
    					$response = array(
    						'status' => 2,
    						'msg' => 'Some error in quote update'
    					);
    				}
    			} else {
    				DB::rollBack();
    				$response = array(
    					'status' => 3,
    					'msg' => 'Some error in quote update'
    				);
    			}
    		} else {
    			$response = array(
    				'status' => 4,
    				'msg' => 'Invalid order id!'
    			);
    		}
    	} else {
    		$orderId = $request->get('orderId');
    		$productId = $request->get('productId');
    		$productQty = $request->get('productQty');
    		$existingProductId = $request->get('existingProductId');
    		$response = array();
    		// Get the order product details
        	$orderProduct = OrderProduct::where(['order_id' => $orderId, 'product_id' => $productId])->first();
        	$response = array();
        	// Check if the product already exist in the order_product table
        	//if (is_null($orderProduct)) {
        	    // If the existing product and the previous product both are same then only qty needs to be update
        		if ($productId == $existingProductId) {
        			// Get the order details
        			$order = Order::find($orderId);
        			// Get the order product details
        			$orderProduct = OrderProduct::where(['order_id' => $orderId, 'product_id' => $productId])->first();
        			// Get product details
        			$productDetails = Product::find($orderProduct->product_id);
        			$orderProductOldPrice = $orderProduct->product_price * $orderProduct->quantity;
        			$orderProductNewPrice = $orderProduct->product_price * $productQty;
        			$totalProducts = $order->total_products;
        			$totalVat = $order->tax;
        			// Updates is in increase side
        			if ($orderProductNewPrice > $orderProductOldPrice) {
        				$oldProductVat = (($orderProduct->product_price * $orderProduct->quantity * $productDetails->tax) / 100);
        				$calculatedProductVat = (($orderProductNewPrice * $productDetails->tax) / 100);
        				$vatDifference = abs($calculatedProductVat - $oldProductVat);
        				$priceDiff = abs($orderProductNewPrice - $orderProductOldPrice);
        				$orderDiscountAmount = $order->discount_amount;
        				if ($order->discount_coupon_type == '1') {
        					$newDiscountAmount = ((($totalProducts + $priceDiff + $totalVat + $vatDifference) * $order->discount_value) / 100);
        				} else {
        					$newDiscountAmount = $order->discount_amount;
        				}
        				$totalProducts = ($totalProducts + $priceDiff);
        				$updatedVat = ($totalVat + $vatDifference);
        				$grandTotal = ($totalProducts + $updatedVat - $newDiscountAmount);
        				// Start transaction
        				DB::beginTransaction();
        				$order->total_products = $totalProducts;
        				$order->total = $grandTotal;
        				$order->total_paid = $grandTotal;
        				$order->tax = $updatedVat;
        				$order->tax_value = $updatedVat;
        				if ($orderDiscountAmount != $newDiscountAmount) {
        					$order->discounts = $newDiscountAmount;
        					$order->discount_amount = $newDiscountAmount;
        				}
        				$order->updated_by_admin = '1';
        				if ($order->save()) {
        					$orderProduct->quantity = $productQty;
        					if ($orderProduct->save()) {
        						DB::commit();
        						$response = array(
        							'status' => 1,
        							'msg' => 'Order updated successfully',
        							'data' => array(
        								'subtotal' 	=> number_format($totalProducts, 2),
        								'vat' 		=> number_format($updatedVat, 2),
        								'discount' 	=> number_format($newDiscountAmount, 2),
        								'grandtotal'=> number_format($grandTotal, 2),
        								'product_price' => number_format($orderProductNewPrice, 2),
        							)
        						);
        					} else {
        						DB::rollBack();
        						$response = array(
        							'status' => 2,
        							'msg' => 'Some error in order update'
        						);
        					}
        				} else {
        					DB::rollBack();
        					$response = array(
        						'status' => 3,
        						'msg' => 'Some error in order update'
        					);
        				}
        			} else {
        				$oldProductVat = (($orderProduct->product_price * $orderProduct->quantity * $productDetails->tax) / 100);
        				$calculatedProductVat = (($orderProductNewPrice * $productDetails->tax) / 100);
        				$vatDifference = abs($calculatedProductVat - $oldProductVat);
        				$priceDiff = abs($orderProductNewPrice - $orderProductOldPrice);
        				$orderDiscountAmount = $order->discount_amount;
        				if ($order->discount_coupon_type == '1') {
        					$newDiscountAmount = ((($totalProducts + $priceDiff + $totalVat + $vatDifference) * $order->discount_value) / 100);
        				} else {
        					$newDiscountAmount = $order->discount_amount;
        				}
        				$totalProducts = ($totalProducts - $priceDiff);
        				$updatedVat = ($totalVat - $vatDifference);
        				$grandTotal = ($totalProducts + $updatedVat - $newDiscountAmount);
        				// Start transaction
        				DB::beginTransaction();
        				$order->total_products = $totalProducts;
        				$order->total = $grandTotal;
        				$order->total_paid = $grandTotal;
        				$order->tax = $updatedVat;
        				$order->tax_value = $updatedVat;
        				if ($orderDiscountAmount != $newDiscountAmount) {
        					$order->discounts = $newDiscountAmount;
        					$order->discount_amount = $newDiscountAmount;
        				}
        				$order->updated_by_admin = '1';
        				if ($order->save()) {
        					$orderProduct->quantity = $productQty;
        					if ($orderProduct->save()) {
        						DB::commit();
        						$response = array(
        							'status' => 1,
        							'msg' => 'Order updated successfully',
        							'data' => array(
        								'subtotal' 	=> number_format($totalProducts, 2),
        								'vat' 		=> number_format($updatedVat, 2),
        								'discount' 	=> number_format($newDiscountAmount, 2),
        								'grandtotal'=> number_format($grandTotal, 2),
        								'product_price' => number_format($orderProductNewPrice, 2),
        							)
        						);
        					} else {
        						DB::rollBack();
        						$response = array(
        							'status' => 2,
        							'msg' => 'Some error in order update'
        						);
        					}
        				} else {
        					DB::rollBack();
        					$response = array(
        						'status' => 3,
        						'msg' => 'Some error in order update'
        					);
        				}
        			}
        		} else {
        			// Get the order details
        			$order = Order::find($orderId);
        			// Get the order products
        			$orderProduct = OrderProduct::where(['order_id' => $orderId, 'product_id' => $existingProductId])->first();
        			if (is_null($orderProduct)) {
                		//DB::rollBack();
            		    $response = array(
                			'status' => 5,
                			'msg' => 'Product already exists in order!'
                		);
            		}
        			// Get the order product details
        			$orderProductDetails = Product::find($existingProductId);
        			// Hold the existing product data
        			$existingProductPrice = $orderProduct->product_price;
        			$existingProductQty = $orderProduct->quantity;
        			$existingProductTotalAmount = $existingProductPrice * $existingProductQty;
        			$existingProductVat = (($existingProductTotalAmount * $orderProductDetails->tax) / 100);
        			// Calculate the new product data
        			$productDetails = Product::find($productId);
        			$productPrice = $productDetails->price;
        			$productTotalPrice = ($productPrice * $productQty);
        			$productTotalVat = (($productTotalPrice * $productDetails->tax) / 100);
        			// discount = ((price + vat) * discount_rate) / 100;
        			$newSubTotal = (($order->total_products - $existingProductTotalAmount) + $productTotalPrice);
        			$newVat = (($order->tax - $existingProductVat) + $productTotalVat);
        			$newTotal = $newSubTotal + $newVat;
        			if ($order->discount_coupon_type == '1') {
        				$newDiscountAmount = (($newTotal * $order->discount_value) / 100);
        			} else {
        				$newDiscountAmount = $order->discount_amount;
        			}
        			$grandTotal = $newTotal - $newDiscountAmount;
        			// Start transaction
        			DB::beginTransaction();
        			$orderProduct->product_id = $productDetails->id;
        			$orderProduct->quantity = $productQty;
        			$orderProduct->product_name = $productDetails->name;
        			$orderProduct->product_sku = $productDetails->sku;
        			$orderProduct->product_description	= $productDetails->description;
        			$orderProduct->product_price = $productDetails->price;
        			if ($orderProduct->save()) {
        				$order->discounts = $newDiscountAmount;
        				$order->discount_amount = $newDiscountAmount;
        				$order->total_products = $newSubTotal;
        				$order->tax = $newVat;
        				$order->tax_value = $newVat;
        				$order->total = $grandTotal;
        				$order->total_paid = $grandTotal;
        				$order->updated_by_admin = '1';
        				if ($order->save()) {
        					DB::commit();
        					$response = array(
        						'status' => 1,
        						'msg' => 'Order updated successfully',
        						'data' => array(
        							'subtotal' 	=> number_format($newSubTotal, 2),
        							'vat' 		=> number_format($newVat, 2),
        							'discount' 	=> number_format($newDiscountAmount, 2),
        							'grandtotal'=> number_format($grandTotal, 2),
        							'product_id' => $productDetails->id,
        							'product_name' => $productDetails->name,
        							'product_sku' => $productDetails->sku,
        							'product_qty' => $productQty,
        							'product_price' => $productDetails->price,
        						)
        					);
        				} else {
        					DB::rollBack();
        					$response = array(
        						'status' => 2,
        						'msg' => 'Some error in order update'
        					);
        				}
        			} else {
        				DB::rollBack();
        				$response = array(
        					'status' => 3,
        					'msg' => 'Some error in order update'
        				);
        			}
        		}
    		/*} else {
    		    DB::rollBack();
    		    $response = array(
        			'status' => 5,
        			'msg' => 'Product already exists in order!'
        		);
    		}*/
    	}
    	return response()->json($response);
    }

    // To update order discount
    public function updateOrderDiscount(Request $request) {
	    $orderId = $request->get('orderId');
	    $orderType = $request->get('orderType');
	    $discountId = $request->get('discountId');
	    // Oil products
	    if ($orderType == 'oil') {
	       
	    	if (!empty($discountId) || $discountId != '0') {
	    		// Fetch the discount details
	    		$discountCoupon = DiscountCoupon::find($discountId);
	    		if ($discountCoupon) {
	    			// Fetch the order details
	    			$order = Order::find($orderId);
	    			if ($order) {
	    				// Calculate the new discount value
	    				$subtotal = $order->total_products;
	    				$vat = $order->tax;
	    				$newDiscountAmount = 0;
	    				if ($discountCoupon->coupon_type == '1') {
	    				    // Percentage type
	    					$newDiscountAmount = ((($subtotal + $vat) * $discountCoupon->discount_value) / 100);
	    				} else {
	    				    // Fixed amount type
	    					$newDiscountAmount = $discountCoupon->discount_value;
	    				}
	    				$newDiscountAmount = number_format($newDiscountAmount, 2);
	    				$newDiscountAmount = filter_var($newDiscountAmount, FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);
	    				$discounts = $newDiscountAmount;
	    				$discount_coupon_code = $discountCoupon->coupon_code;
	    				$discount_coupon_type = $discountCoupon->coupon_type;
	    				$discount_value = $discountCoupon->discount_value;
	    				$discount_amount = $newDiscountAmount;
	    				$total = number_format((($subtotal + $vat) - $newDiscountAmount), 2);
	    				$total_paid = number_format((($subtotal + $vat) - $newDiscountAmount), 2);
	    				$total = filter_var($total, FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);
	    				$total_paid = filter_var($total_paid, FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);
	    				$order->discounts = $discounts;
	    				$order->discount_coupon_code = $discount_coupon_code;
	    				$order->discount_coupon_type = $discount_coupon_type;
	    				$order->discount_value = $discount_value;
	    				$order->discount_amount = $discount_amount;
	    				$order->total = $total;
	    				$order->total_paid = $total_paid;
	    				$order->total_products = $subtotal;
	    				if( $order->save() ) {
	    					$response = array(
	    						'status' => 1,
	    						'msg' => 'Discount updated successfully',
	    						'data' => array(
	    							'discount' 	=> number_format($discount_amount, 2),
	    							'grandtotal'=> number_format($total_paid, 2)
	    						)
	    					);
	    				} else {
	    					$response = array(
	    						'status' => 2,
	    						'msg' => 'Some error in discount update'
	    					);
	    				}
	    			} else {
	    				$response = array(
	    					'status' => 3,
	    					'msg' => 'Invalid order'
	    				);
	    			}
	    		} else {
	    			$response = array(
	    				'status' => 3,
	    				'msg' => 'Invalid discount coupon code applied'
	    			);
	    		}
	    	} else {
	    	    // discount coupon is removed
	    		// Fetch the order details
	    		$order = Order::find($orderId);
	    		if ($order) {
	    			// Get the discount amount
	    			$discountAmount = $order->discounts;
	    			$total = $order->total + $discountAmount;
	    			$total_paid = $order->total + $discountAmount;
	    			$order->discounts = 0;
	    			$order->discount_coupon_code = null;
	    			$order->discount_coupon_type = null;
	    			$order->discount_value = null;
	    			$order->discount_amount = null;
	    			$order->total = $total;
	    			$order->total_paid = $total_paid;
	    			$order->updated_by_admin = '1';
	    			if ($order->save()) {
	    				$response = array(
	    					'status' => 1,
	    					'msg' => 'Discount updated successfully',
	    					'data' => array(
	    						'discount' 	=> number_format(0, 2),
	    						'grandtotal'=> number_format($total_paid, 2)
	    					)
	    				);
	    			} else {
	    				$response = array(
	    					'status' => 2,
	    					'msg' => 'Some error in discount update'
	    				);
	    			}
	    		} else {
	    			$response = array(
	    				'status' => 3,
	    				'msg' => 'Invalid order'
	    			);
	    		}
	    	}
	    } else {
	        // Shop products
	    	if (!empty($discountId) || $discountId != '0') {
	    	    // a new discount coupon is applied
	    		// Fetch the discount details
	    		$discountCoupon = DiscountCoupon::find($discountId);
	    		if ($discountCoupon) {
	    			// Fetch the order details
	    			$order = Order::find($orderId);
	    			if ($order) {
	    				// Calculate the new discount value
	    				$subtotal = $order->total_products;
	    				$vat = $order->tax;
	    				$newDiscountAmount = 0;
	    				if ($discountCoupon->coupon_type == '1') {
	    				    // Percentage type
	    					$newDiscountAmount = ((($subtotal + $vat) * $discountCoupon->discount_value) / 100);
	    				} else {
	    				    // Fixed amount type
	    					$newDiscountAmount = $discountCoupon->discount_value;
	    				}
	    				$newDiscountAmount = number_format($newDiscountAmount, 2);
	    				$newDiscountAmount = filter_var($newDiscountAmount, FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);
	    				$discounts = $newDiscountAmount;
	    				$discount_coupon_code = $discountCoupon->coupon_code;
	    				$discount_coupon_type = $discountCoupon->coupon_type;
	    				$discount_value = $discountCoupon->discount_value;
	    				$discount_amount = $newDiscountAmount;
	    				$total = number_format((( $subtotal + $vat ) - $newDiscountAmount), 2);
	    				$total_paid = number_format((( $subtotal + $vat ) - $newDiscountAmount), 2);
	    				$total = filter_var($total, FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);
	    				$total_paid = filter_var($total_paid, FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);
	    				$order->discounts = $discounts;
	    				$order->discount_coupon_code = $discount_coupon_code;
	    				$order->discount_coupon_type = $discount_coupon_type;
	    				$order->discount_value = $discount_value;
	    				$order->discount_amount = $discount_amount;
	    				$order->total = $total;
	    				$order->total_paid = $total_paid;
	    				if( $order->save() ) 	{
	    					$response = array(
	    						'status' => 1,
	    						'msg' => 'Discount updated successfully',
	    						'data' => array(
	    							'discount' 	=> number_format($discount_amount, 2),
	    							'grandtotal'=> number_format($total_paid, 2)
	    						)
	    					);
	    				} else {
	    					$response = array(
	    						'status' => 2,
	    						'msg' => 'Some error in discount update'
	    					);
	    				}
	    			} else {
	    				$response = array(
	    					'status' => 3,
	    					'msg' => 'Invalid order'
	    				);
	    			}
	    		} else {
	    			$response = array(
	    				'status' => 3,
	    				'msg' => 'Invalid discount coupon code applied'
	    			);
	    		}
	    	} else {
	    	    // discount coupon is removed
	    		// Fetch the order details
	    		$order = Order::find($orderId);
	    		if ($order) {
	    			// Get the discount amount
	    			$discountAmount = $order->discounts;
	    			$total = $order->total + $discountAmount;
	    			$total_paid = $order->total + $discountAmount;
	    			$order->discounts = 0;
	    			$order->discount_coupon_code = null;
	    			$order->discount_coupon_type = null;
	    			$order->discount_value = null;
	    			$order->discount_amount = null;
	    			$order->total = $total;
	    			$order->total_paid = $total_paid;
	    			$order->updated_by_admin = '1';
	    			if ($order->save()) {
	    				$response = array(
	    					'status' => 1,
	    					'msg' => 'Discount updated successfully',
	    					'data' => array(
	    						'discount' 	=> number_format(0, 2),
	    						'grandtotal'=> number_format($total_paid, 2)
	    					)
	    				);
	    			} else {
	    				$response = array(
	    					'status' => 2,
	    					'msg' => 'Some error in discount update'
	    				);
	    			}
	    		} else {
	    			$response = array(
	    				'status' => 3,
	    				'msg' => 'Invalid order'
	    			);
	    		}
	    	}
	    }
	    return response()->json($response);
    }

    // To delete shop order product
    public function deleteOrder(Request $request) {
	    $orderId = $request->get('orderId');
	    $productId = $request->get('productId');
	    $response = array();
	    // Get the order details
	    $order = Order::find($orderId);
	    if ($order) {
			// Get the order products
			$orderProduct = OrderProduct::where(['order_id' => $orderId, 'product_id' => $productId])->first();
			if ($orderProduct) {
				// Get the order product details
				$orderProductDetails = Product::find($productId);
				// Hold the existing product data
				$existingProductPrice = $orderProduct->product_price;
				$existingProductQty = $orderProduct->quantity;
				$existingProductTotalAmount = $existingProductPrice * $existingProductQty;
				$existingProductVat = (($existingProductTotalAmount * $orderProductDetails->tax) / 100);
				// Calculate the new order data by subtracting the deleted product amount
				// discount = ((price + vat) * discount_rate) / 100;
				$newSubTotal = ($order->total_products - $existingProductTotalAmount);
				$newVat = ($order->tax - $existingProductVat );
				$newTotal = ($newSubTotal + $newVat);
				$oldDiscountAmount = $order->discount_amount;
				if ($order->discount_coupon_type == '1') {
					$newDiscountAmount = (($newTotal * $order->discount_value) / 100);
				} else {
					$newDiscountAmount = $order->discount_amount;
				}
				$grandTotal = $newTotal - $newDiscountAmount;
				// Start transaction
				DB::beginTransaction();
				// Delete the product from order_product
				if ($orderProduct->delete()) {
					$order->tax = $newVat;
					$order->tax_value = $newVat;
					$order->total_products = $newSubTotal;
					$order->total_paid = $grandTotal;
					$order->updated_by_admin = '1';
					if ($oldDiscountAmount != $newDiscountAmount) {
						$order->discounts = $newDiscountAmount;
						$order->discount_amount = $newDiscountAmount;
					}
					if ($order->save()) {
						DB::commit();
						$response = array(
							'status' => 1,
							'msg' => 'Order updated successfully',
							'data' => array(
								'subtotal' 	=> number_format($newSubTotal, 2),
								'vat' 		=> number_format($newVat, 2),
								'discount' 	=> number_format($newDiscountAmount, 2),
								'grandtotal'=> number_format($grandTotal, 2)
							)
						);
					} else {
						DB::rollBack();
						$response = array(
							'status' => 2,
							'msg' => 'Some error in delete product'
						);
					}
				} else {
					DB::rollBack();
					$response = array(
						'status' => 3,
						'msg' => 'Some error in delete product'
					);
				}
			} else {
				$response = array(
					'status' => 4,
					'msg' => 'Invalid order product'
				);
			}
	    } else {
	    	$response = array(
	    		'status' => 5,
	    		'msg' => 'Invalid order'
	    	);
	    }
	    return response()->json($response);
	}

	// To add a new product to shop order
    public function addProduct(Request $request) {
    	$orderId = $request->get('orderId');
    	$productId = $request->get('productId');
    	$productQty = $request->get('productQty');
    	// Get the order details
    	$order = Order::find($orderId);
    	// Get the order product details
    	$orderProduct = OrderProduct::where(['order_id' => $orderId, 'product_id' => $productId])->first();
    	// Get product details
    	$productDetails = Product::find($productId);
    	// Check if the product already exist in the order_product table
    	$response = array();
    	if (is_null($orderProduct)) {
    		// Calculate the product amount
    		$productPrice = ($productDetails->price * $productQty);
    		$productVat = (($productPrice * $productDetails->tax) / 100);
    		// Calculate the order table changes
    		$newSubTotal = ($order->total_products + $productPrice);
    		$newVat = ($order->tax + $productVat);
    		$newTotal = ($newSubTotal + $newVat);
    		$oldDiscountAmount = $order->discount_amount;
    		if ($order->discount_coupon_type == '1') {
    			$newDiscountAmount = (($newTotal * $order->discount_value) / 100);
    		} else {
    			$newDiscountAmount = $order->discount_amount;
    		}
    		$grandTotal = $newTotal - $newDiscountAmount;
    		// Start transaction
    		DB::beginTransaction();
    		// Add the new product entry to order_product table
    		$newOrderProduct = new OrderProduct;
    		$newOrderProduct->order_id = $orderId;
    		$newOrderProduct->product_id = $productId;
    		$newOrderProduct->quantity = $productQty;
    		$newOrderProduct->product_name = $productDetails->name;
    		$newOrderProduct->product_sku = $productDetails->sku;
    		$newOrderProduct->product_description = $productDetails->description;
    		$newOrderProduct->product_price = $productDetails->price;
    		if ($newOrderProduct->save()) {
    			// Update the order table
    			$order->tax = $newVat;
    			$order->tax_value = $newVat;
    			$order->total_products = $newSubTotal;
    			$order->total_paid = $grandTotal;
    			$order->updated_by_admin = '1';
    			if ($oldDiscountAmount != $newDiscountAmount) {
    				$order->discounts = $newDiscountAmount;
    				$order->discount_amount = $newDiscountAmount;
    			}
    			if ($order->save()) {
    				DB::commit();
    				$response = array(
    					'status' => 1,
    					'msg' => 'Order updated successfully',
    					'data' => array(
    						'subtotal' 	=> number_format($newSubTotal, 2),
    						'vat' 		=> number_format($newVat, 2),
    						'discount' 	=> number_format($newDiscountAmount, 2),
    						'grandtotal'=> number_format($grandTotal, 2),
    						'product_id'    => $productId,
    						'product_sku' 	=> $productDetails->sku,
    						'product_name' 	=> $productDetails->name,
    						'product_qty' 	=> $productQty,
    						'product_price' => number_format($productPrice, 2)
    					)
    				);
    			} else {
    				DB::rollBack();
    				$response = array(
    					'status' => 2,
    					'msg' => 'Some error in delete product'
    				);
    			}
    		} else {
				$response = array(
					'status' => 2,
					'msg' => 'Some error in delete product'
				);
    		}
    	} else {
    		$response = array(
    			'status' => 5,
    			'msg' => 'Product already exists in order!'
    		);
    	}
    	return response()->json($response);
    }

    // To update delivery date
    public function updateDeliveryDate(Request $request) {
    	$orderId = $request->get('orderId');
    	$updatedDeliveryDate = $request->get('updatedDeliveryDate');
    	$response = array();
    	if ($orderId != '') {
    		$deliveryDate = date('Y-m-d', strtotime(str_replace("/", "-", $updatedDeliveryDate)));
    		$order = Order::find($orderId);
    		$order->delivery_date = $deliveryDate;
    		if ($order->save()) {
    			$response = array(
    				'status' => 1,
    				'msg' => 'Order updated successfully',
    				'delivery_date' => $deliveryDate,
    				'formated_delivery_date' => date('d/m/Y', strtotime($deliveryDate))
    			);
    		} else {
    			$response = array(
					'status' => 2,
					'msg' => 'Some error in delevery date product'
				);
    		}
    	} else {
			$response = array(
				'status' => 3,
				'msg' => 'Invalid order'
			);
    	}
    	return response()->json($response);
    }

    public function sendDeliveryEmail(Request $request, $id){
        try {
            $order = $this->orderRepo->findOrderById($id);
            $customer = $order->customer;
            $driver = Customer::find($order->driver_id);
            $data['customer_name'] = $customer->name;
            $data['delevery_date'] = $order->delivery_date;
            $data['driver'] = $driver->name ?? 'n/a';
            $data['created_at'] = $order->created_at;
            // Send the email
            Mail::send('emails.admin.emailDeliveryDetailstoCustomer', $data, function ($message) use ($customer, $order) {
                $message->from(config('constants.ADMIN_EMAIL'));
                $message->to($customer->email,$customer->name)->subject('#'.$order->id.' Order Delivery Details');
            });

            Order::where("id",$id)->update(['is_email_sent_customer'=>'1']);

            $response = array(
                'status' => 1,
                'msg' => 'Email sent successfully.'
            );
            return response()->json($response);
        }
        catch(Exception $e) {
            \Log::info('Message: ' .$e->getMessage());

            $response = array(
                'status' => 0,
                'msg' => $e->getMessage()
            );
            return response()->json($response);
        }
    }

    public function filterOrders(Request $request) {
        // Fetch all orders except oil one

        $list = $this->orderRepo->listOrders('created_at', 'desc');
        
        $orders = $this->transFormOrder($list);
        // Fetch all oil orders

        $list = Order::where('oil_type_order','1');
        $completedList = Order::where('oil_type_order','1');

        $filter_data = [];

        if($request->from_date && $request->to_date){
            $toDate = date("Y-m-d",strtotime($request->to_date));
            $fromDate = date("Y-m-d",strtotime($request->from_date));
            $list->whereDate('created_at','>=', $fromDate)->whereDate('created_at','<=', $toDate);
            $completedList->whereDate('created_at','>=', $fromDate)->whereDate('created_at','<=', $toDate);

            $filter_data['from_date'] = $request->from_date;
            $filter_data['to_date'] = $request->to_date;
        }
        if($request->order_status != ''){
            $list->where("order_status", $request->order_status);
            $completedList->where("order_status", $request->order_status);

            $filter_data['order_status'] = $request->order_status;
        }
        if($request->payment_status != ''){
            $list->where("order_status_id", $request->payment_status);
            $completedList->where("order_status_id", $request->payment_status);

            $filter_data['payment_status'] = $request->payment_status;
        }
        if($request->driver != ''){
            if($request->driver == '0'){
                 $list->whereNull("driver_id");
                $completedList->whereNull("driver_id");
            }else{
                $list->where("driver_id", $request->driver);
                $completedList->where("driver_id", $request->driver);
            }
            

            $filter_data['driver'] = $request->driver;
        }
        $completedList = $completedList->where('order_status_id','1')->get();
        $list = $list->where('order_status_id','!=','1')->get();

        $oilOrders = $this->transFormOrder($list);
        $completedOrders = $this->transFormOrder($completedList);

        $orderStatuses = OrderStatus::all();

        $drivers = Customer::where(['is_driver' => '1'])->get();
        return view('admin.orders.list', ['orders' => $orders, 'oilOrders' => $oilOrders, 'drivers' => $drivers, 'orderStatuses' => $orderStatuses, 'completedOrders' => $completedOrders, 'filter_data' => $filter_data]);
    }
    
    //  public function payment(Request $request){
    //     $orderId = base64_decode($request->input('order_id'));
        
    //         $orderDetails = Order::find($orderId);
    //         $orderProduct = OrderProduct::where(['order_id' => $orderId])->first();
    //         $productDetails = Product::find($orderProduct->product_id);
    //         $customer_data = Customer::find($orderDetails->customer_id);
    //         $data['emailFrom'] = \Config::get('values.MAIL_FROM');

    //             try {
    //                 $stripe_client = new StripeClient($this->apiKey);
    //                 $payment_data = $stripe_client->paymentMethods->create([
    //                     'type' => 'card',
    //                     'card' => [
    //                       'number' => base64_decode($request->input('number')),
    //                       'exp_month' => base64_decode($request->input('month')),
    //                       'exp_year' => base64_decode($request->input('year')),
    //                       'cvc' => base64_decode($request->input('track_id')),
    //                     ],
    //                      'billing_details'=> [
    //                          'name'=> $request->input('name')
    //                          ]
    //                 ]);

    //             $customerDetailsAry = array(
    //                 'email' => $customer_data->email,
    //                 'source' => $request->token
    //             );
    //             // Adding stripe customer
    //             $customerResult = $this->addCustomer($customerDetailsAry);
    //             // Payment Intent Customer -- START
    //             $payment_intent = new PaymentIntent();
    //             $payment_intent_data = array(
    //                 'customer'              => $customerResult->id,
    //                 'amount'                => $orderDetails->total_paid * 100, // Tax is added here
    //                 'currency'              => $request->currency_code,
    //                 'description'           => $productDetails->name,
    //                 'payment_method_types'  => ['card'],
    //                 'capture_method'        => 'manual',
    //                 'payment_method'=>$payment_data->id,
    //                 'metadata'              => array(
    //                     'order_id'    => $orderId
    //                 ),
    //             );
    //             $result = $payment_intent->create($payment_intent_data);
    //         }
    //         catch(\Stripe\Exception\CardException $e) {
    //           // Since it's a decline, \Stripe\Exception\CardException will be caught
    //             \Log::info(print_r($e->getError()->message,true));
    //             return redirect()->back()->with('error', $e->getError()->message);
    //         } catch (\Stripe\Exception\RateLimitException $e) {
    //             \Log::info(print_r($e->getError()->message,true));
    //             return redirect()->back()->with('error', $e->getError()->message);
    //           // Too many requests made to the API too quickly
    //         } catch (\Stripe\Exception\InvalidRequestException $e) {
    //             \Log::info(print_r($e->getError()->message,true));
    //             return redirect()->back()->with('error', $e->getError()->message);
    //           // Invalid parameters were supplied to Stripe's API
    //         } catch (\Stripe\Exception\AuthenticationException $e) {
    //             \Log::info(print_r($e->getError()->message,true));
    //             return redirect()->back()->with('error', $e->getError()->message);
    //           // (maybe you changed API keys recently)
    //         } catch (\Stripe\Exception\ApiConnectionException $e) {
    //             \Log::info(print_r($e->getError()->message,true));
    //             return redirect()->back()->with('error', $e->getError()->message);
    //           // Network communication with Stripe failed
    //         } catch (\Stripe\Exception\ApiErrorException $e) {
    //             \Log::info(print_r($e->getError()->message,true));
    //             return redirect()->back()->with('error', $e->getError()->message);
    //           // Display a very generic error to the user, and maybe send
    //           // yourself an email
    //         } catch (Exception $e) {
    //             \Log::info(print_r($e->getError()->message,true));
    //             return redirect()->back()->with('error', $e->getError()->message);
    //           // Something else happened, completely unrelated to Stripe
    //         }
    //         $serialized_result = $result->jsonSerialize();
    //         if ($serialized_result['status'] == 'requires_payment_method' || $serialized_result['status'] == 'requires_confirmation') {
    //             $orderDetails->order_status_id = 2;     # on-delivery
    //         } else {
    //             $orderDetails->order_status_id = 3; # error
    //         }
    //         $orderDetails->transaction_id       = $serialized_result['id'];
    //         $orderDetails->stripe_customer_id   = $serialized_result['customer'];
    //         $orderDetails->transaction_status   = $serialized_result['status'];
    //         $orderDetails->save();
           
    //         // Storing session for success or failed page
    //         $employee = Employee::find(1);
    //         if ($serialized_result['status'] == 'requires_payment_method' || $serialized_result['status'] == 'requires_confirmation') {
    //             \Session::flash('message', "Payment successfull!");
    //             return redirect()->route('admin.orders.show', $orderDetails->id);
    //         } else {
    //             return redirect()->oute('admin.orders.show', $orderDetails->id);
    //         }
    // }
    public function payment(Request $request){
        $orderId = base64_decode($request->input('order_id'));
        
            $orderDetails = Order::find($orderId);
            $orderProduct = OrderProduct::where(['order_id' => $orderId])->first();
            $productDetails = Product::find($orderProduct->product_id);
            $customer_data = Customer::find($orderDetails->customer_id);
            $data['emailFrom'] = \Config::get('values.MAIL_FROM');
            $address = Address::where('customer_id',$orderDetails->customer_id)->first();
                try {
                  	$elavon_user_name = config('elavon.key');
		    $elavon_user_password = config('elavon.secret');
		    $base_inc = base64_encode($elavon_user_name.':'.$elavon_user_password);
            $vendor_name = config('elavon.vendorName');
            $order_total = $orderDetails->total_paid * 100;
            $order_total = round($order_total,2);
           //$elav_order_total = number_format($order_total,2);
            
            $ch = curl_init();
            $header = array();
           
            $header[] = 'Content-type: application/json';
            $header[] = 'Authorization: Basic '.$base_inc;
            $payload = json_encode( array( "vendorName"=> $vendor_name ) );
		    	$card_identifier = $request->input('card-identifier');
				$ms = $request->input('merchent_key');
				
				$payment_payload = json_encode( array(
					"transactionType"=> $orderDetails->fill_the_tank_status == '1'? "Deferred" : "Payment",
					"paymentMethod"=>array('card' => array("merchantSessionKey"=>$ms,"cardIdentifier"=>$card_identifier,
					"save"=> false
				)),
					"vendorTxCode"=>"oil-".rand(),
					"amount"=> (int)$order_total,
					"currency"=> "EUR",
					"description"=> "Oil Order",
					"customerFirstName"=> $customer_data->fname,
			 		"customerLastName"=> $customer_data->lname,
			 		"customerEmail"=> $customer_data->email,
			 		"billingAddress"=>array("address1"=>$address->address_1,"postalCode"=>$address->zip,"city"=> $address->town,"country"=> 'IE'),
			 		"entryMethod"=> "Ecommerce",
			 		 "apply3DSecure"=> "Force",
			 		"strongCustomerAuthentication"=>array("notificationURL"=> route('admin.orders.threed.secure'),
                  "browserIP"=> $_SERVER['REMOTE_ADDR'],
                        "browserAcceptHeader"=> "\\*/\\*",
                        "browserJavascriptEnabled"=> false,
                        
                        "browserLanguage"=> substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2),
                       
                        "browserUserAgent"=> "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:67.0) Gecko/20100101 Firefox/67.0",
                        "challengeWindowSize"=> "Small",
                       
                        "transType"=> "GoodsAndServicePurchase",
                )
				));
				curl_setopt($ch, CURLOPT_URL,$this->elavonUrl."/api/v1/transactions");
				curl_setopt($ch, CURLOPT_POST, true);
				curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
				curl_setopt($ch, CURLOPT_POSTFIELDS, $payment_payload);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
				$server_output_pay = curl_exec($ch);
				$serialized_result = json_decode($server_output_pay);
				if(isset($serialized_result->status) && $serialized_result->status == '3DAuth'){
                    
                    $transData = [];
                    $transData['paReq'] = $serialized_result->cReq;
                    $transData['acsUrl'] = $serialized_result->acsUrl;
                    $transData['ref'] = $orderId;
                    $transData['url'] = route('admin.orders.threed.secure');
                    $orderDetails->transaction_id = $serialized_result->transactionId;
                    $orderDetails->payment = 'Credit Card';
                    $orderDetails->save();
                    DB::commit();
                    return view('auth.threedsecure',$transData);
                }else if(isset($serialized_result->status) && $serialized_result->status == 'Ok'){
                    $orderDetails->order_status_id = 1; 
                    $orderDetails->transaction_id       = $serialized_result->transactionId;
                    $orderDetails->transaction_status   = (isset($serialized_result->transactionType) && $serialized_result->transactionType == 'Deferred') ? 'requires_confirmation' : 'succeeded';
                    $orderDetails->save();
                    \Session::flash('message', "Payment successfull!");
                    return redirect()->route('admin.orders.show', $orderDetails->id);
                }else{
                    return redirect()->route('admin.orders.show', $orderDetails->id);
                }
            }
            catch (Exception $e) {
               
                return redirect()->back()->with('error', $e->getError()->message);
              // Something else happened, completely unrelated to Stripe
            }
            
            // if ($serialized_result->status == 'Ok' || $serialized_result->transactionType == 'Deferred' || $serialized_result->transactionType == 'Payment') {
            //     $orderDetails->order_status_id = 2;     # on-delivery
            // } else {
            //     $orderDetails->order_status_id = 3; # error
            // }
            // $orderDetails->transaction_id       = $serialized_result->transactionId;
            // $orderDetails->stripe_customer_id   = '';
            // $orderDetails->transaction_status   = 'requires_confirmation';
            // $orderDetails->save();
           
            // Storing session for success or failed page
            // $employee = Employee::find(1);
            // if ($serialized_result->status == 'Ok') {
            //     \Session::flash('message', "Payment successfull!");
            //     return redirect()->route('admin.orders.show', $orderDetails->id);
            // } else {
            //     return redirect()->oute('admin.orders.show', $orderDetails->id);
            // }
    }
     public function addCustomer($customerDetailsAry) {
        $customer = new Stripe_customer();
        $customerDetails = $customer->create($customerDetailsAry);
        return $customerDetails;
    }

    public function endOfDayReport() {
        $toDate = date("Y-m-d");
        $fromDate = date("Y-m-d");

        $filter_data['from_date'] = $fromDate;
        $filter_data['to_date'] = $toDate;
        // Fetch all orders except oil one
        
        $list = Order::where('oil_type_order','1')->whereDate('created_at','>=', $fromDate)->whereDate('created_at','<=', $toDate)->get();

        $oilOrders = $this->transFormOrder($list);
       
        $orderStatuses = OrderStatus::all();

        // Fetch the drivers
        $drivers = Customer::where(['is_driver' => '1'])->get();
        return view('admin.orders.end-of-day-report', ['oilOrders' => $oilOrders, 'drivers' => $drivers, 'orderStatuses' => $orderStatuses, "filter_data" => $filter_data]);
    }

    public function filterOrdersReport(Request $request) {
        $list = Order::where('oil_type_order','1');

        $filter_data = [];

        if($request->from_date && $request->to_date){
            $toDate = date("Y-m-d",strtotime(str_replace("/", "-", $request->to_date)));
            $fromDate = date("Y-m-d",strtotime(str_replace("/", "-", $request->from_date)));
            $list->whereDate('created_at','>=', $fromDate)->whereDate('created_at','<=', $toDate);
            $filter_data['from_date'] = $fromDate;
            $filter_data['to_date'] = $toDate;
        }
        if($request->order_status != ''){
            $list->where("order_status", $request->order_status);

            $filter_data['order_status'] = $request->order_status;
        }
        if($request->driver != ''){
            $list->where("driver_id", $request->driver);

            $filter_data['driver'] = $request->driver;
        }
         if($request->payment_status != ''){
            $list->where("order_status_id", $request->payment_status);

            $filter_data['payment_status'] = $request->payment_status;
        }

       // $list = $list->where('order_status_id','!=','1')->get();
        $list = $list->orderBy('id','desc')->get();
        $oilOrders = $this->transFormOrder($list);

        $orderStatuses = OrderStatus::all();

        $drivers = Customer::where(['is_driver' => '1'])->get();
        return view('admin.orders.end-of-day-report', ['oilOrders' => $oilOrders, 'drivers' => $drivers, 'orderStatuses' => $orderStatuses, 'filter_data' => $filter_data]);
    }

    public function printFilterOrdersReport(Request $request) {
        $list = Order::where('oil_type_order','1');

        $filter_data = [];
      
        if($request->from_date && $request->to_date){
            $toDate = date("Y-m-d",strtotime(str_replace("/", "-", $request->to_date)));
            $fromDate = date("Y-m-d",strtotime(str_replace("/", "-", $request->from_date)));
            $list->whereDate('created_at','>=', $fromDate)->whereDate('created_at','<=', $toDate);
            $filter_data['from_date'] = $fromDate;
            $filter_data['to_date'] = $toDate;
        }
        if($request->order_status != ''){
            $list->where("order_status", $request->order_status);

            $filter_data['order_status'] = $request->order_status;
        }
        if($request->driver != ''){
            $list->where("driver_id", $request->driver);

            $filter_data['driver'] = $request->driver;
        }
         if($request->payment_status != ''){
            $list->where("order_status_id", $request->payment_status);

            $filter_data['payment_status'] = $request->payment_status;
        }

        //$list = $list->where('order_status_id','!=','1')->get();
        $list = $list->orderBy('id','desc')->get();
        $oilOrders = $this->transFormOrder($list);

        $orderStatuses = OrderStatus::all();

        $drivers = Customer::where(['is_driver' => '1'])->get();
       
        $pdf = app()->make('dompdf.wrapper');
        $pdf->loadView('admin.orders.printFilterOrdersReport', ['oilOrders' => $oilOrders, 'drivers' => $drivers, 'orderStatuses' => $orderStatuses, 'filter_data' => $filter_data])->stream();
        return $pdf->stream();
    }
    
    public function updateQuantity(Request $request){
        $order_id = $request->input('order_id');
        
    	$product_id 	   = $request->product_id;
    	$demanded_quantity = $request->qty;
    	// Fetching the available quantity array for the product
    	$quantity_data = DB::table('order_product_prices')
    		->leftJoin('attribute_value_product_attribute', 'attribute_value_product_attribute.product_attribute_id','=','order_product_prices.attribute_id')
			->leftJoin('attribute_values', 'attribute_values.id','=','attribute_value_product_attribute.attribute_value_id')
    		->where('order_product_prices.product_id',$product_id)
    		->where('order_product_prices.order_id',$order_id)
    		->select('attribute_values.value')
    		->orderBy('attribute_values.value', 'ASC')
    		->get();
    	// Array Of all quantities
    	$quantities = [];
    	foreach($quantity_data as $quantity) {
    		$quantities[] = $quantity->value;
    	}
    	// Case 1st : When demanded_quantity is in the array then fetch the price directly
    	if (in_array($demanded_quantity, $quantities)) {
    		// Fetching the price according to quantity
    		$price = $this->fetch_price_according_quantity($product_id, $demanded_quantity,$order_id);
    		$price = round($price,2);
    		$price = number_format($price,2,'.','');
    		echo $price;
    	// Case 2nd : When demanded_quantity is greater than all the quantities
    	} elseif ($demanded_quantity > max($quantities)) {
    		$array_length = count($quantities);
    		$high_threshold_liter = max($quantities);
    		
    		if ($array_length > 1) { 
    		    $low_threshold_liter  = $quantities[$array_length-2];
    		} else { 
    		    $low_threshold_liter  = max($quantities);
    		}
    		
    		$low_thresh_val  = DB::table('order_product_prices')
    	->leftJoin('product_attributes','product_attributes.id','=','order_product_prices.attribute_id')
    	->where('order_id',$order_id)->where('order_product_prices.product_id',$product_id)->where('product_attributes.quantity','<',$demanded_quantity)->select('order_product_prices.price','product_attributes.quantity')->orderBy('product_attributes.quantity','desc')->first();
 
    		$high_threshold_price = $this->fetch_price_according_quantity($product_id, $high_threshold_liter,$order_id);
    		$low_threshold_price = $this->fetch_price_according_quantity($product_id, $low_threshold_liter,$order_id);
    		// Calculating the price per liter 
    		$price_per_liter = ($high_threshold_price - $low_threshold_price) / ($high_threshold_liter - $low_threshold_liter);
    		$price_per_liter = round($price_per_liter,2);
    		// Calculating the price that will be paid
    		//Fill Price
    		
			$fill_price = ($price_per_liter * ($demanded_quantity - $low_thresh_val->quantity)) + $low_thresh_val->price;
		
    			$price = round($fill_price,2);
    		$price = number_format($price,2,'.','');
    		
    			echo $price;
    	// Case 3rd : When demanded_quantity is less than all the quantities
    	} elseif ( $demanded_quantity < min($quantities) ) {
    		$array_length = count($quantities);
    		$low_threshold_liter  = min($quantities);
    		if ($array_length > 1) {
    		    $high_threshold_liter  = $quantities[1];
    		} else {
    		    $high_threshold_liter  = min($quantities);
    		}
    		$high_threshold_price = $this->fetch_price_according_quantity($product_id, $high_threshold_liter,$order_id);
    		$low_threshold_price = $this->fetch_price_according_quantity($product_id, $low_threshold_liter,$order_id);
    		// Calculating the price per liter 
    		$price_per_liter = ($high_threshold_price - $low_threshold_price) / ($high_threshold_liter - $low_threshold_liter);
    		$price_per_liter = round($price_per_liter,2);
    		// Calculating the price that will be paid
    		//Fill Price
			$fill_price = ($price_per_liter * ($demanded_quantity - $low_threshold_liter)) + $low_threshold_price;
    	
    		$price = round($fill_price,2);
    		$price = number_format($price,2,'.','');
    			echo $price;
    	// Case 4th :  When demanded_quantity is in middle of existimg quantity
    	} else {
    		$low_threshold_liter  = $this->fetch_minimum_quantity($demanded_quantity, $quantities);
    		$high_threshold_liter = $this->fetch_maximum_quantity($demanded_quantity, $quantities);
    		$high_threshold_price = $this->fetch_price_according_quantity($product_id, $high_threshold_liter,$order_id);
    		$low_threshold_price = $this->fetch_price_according_quantity($product_id, $low_threshold_liter,$order_id);
    		// Calculating the price per liter 
    		$price_per_liter = ($high_threshold_price - $low_threshold_price) / ($high_threshold_liter - $low_threshold_liter);
    		$price_per_liter = round($price_per_liter,2);
    		// Calculating the price that will be paid
    		//Fill Price
    	    
			$fill_price = ($price_per_liter * ($demanded_quantity - $low_threshold_liter)) + $low_threshold_price;
			
    		$price = round($fill_price,2);
    		$price = number_format($price,2,'.','');
    		echo $price;
    	}
    }
    
    public function fetch_price_according_quantity($product_id, $quantity,$order_id) {
    	$quantity= round($quantity, 0);
    	$price_data = DB::table('order_product_prices')
    	    ->leftJoin('attribute_value_product_attribute', 'attribute_value_product_attribute.product_attribute_id','=','order_product_prices.attribute_id')
    		->leftJoin('attribute_values', 'attribute_values.id','=','attribute_value_product_attribute.attribute_value_id')
    		->where('order_product_prices.product_id',$product_id)
    		->where('order_product_prices.order_id',$order_id)
    		->where('attribute_values.value',$quantity)
    		->select('order_product_prices.price')
    		->first();
    	if(!$price_data){
    	    $price_data = DB::table('product_attributes')
    	    ->leftJoin('attribute_value_product_attribute', 'attribute_value_product_attribute.product_attribute_id','=','product_attributes.id')
    		->leftJoin('attribute_values', 'attribute_values.id','=','attribute_value_product_attribute.attribute_value_id')
    		->where('product_attributes.product_id',$product_id)
    		->where('attribute_values.value',$quantity)
    		->select('product_attributes.price')
    		->first();
    	}
    	return $price_data->price;
    }
    
    public function fetch_minimum_quantity($value, $search_array) {
    	$min = 0;
    	foreach ($search_array as $search) {
    		if ($search > $value) {
    		    break;
    		}
    		$min = $search;
    	}
    	return $min;
    } 

    public function fetch_maximum_quantity($value, $search_array) {
    	$max = 0;
    	foreach ($search_array as $search) {
    		if ($search > $value) {
    		    $max = $search;
    		    break;
    		}
    	}
    	return $max;
    }
    
    public function updatePrice(Request $request){
        $order_id = $request->input('order_id');
        
    	$product_id 	   = $request->product_id;
    
    	$price = str_replace( ',', '', $request->price );
    	
    	// Fetching the available quantity array for the product
//     	$quantity_data = DB::table('order_product_prices')
//     		->leftJoin('attribute_value_product_attribute', 'attribute_value_product_attribute.product_attribute_id','=','order_product_prices.attribute_id')
// 			->leftJoin('attribute_values', 'attribute_values.id','=','attribute_value_product_attribute.attribute_value_id')
//     		->where('order_product_prices.product_id',$product_id)
//     		->where('order_product_prices.order_id',$order_id)
//     		->select('order_product_prices.value')
//     		->orderBy('attribute_values.value', 'ASC')
//     		->get();
    	// Array Of all quantities
    	$quantities = [];
    	
    	$price_data = DB::table('order_product_prices')
    	->leftJoin('product_attributes','product_attributes.id','=','order_product_prices.attribute_id')
    	->where('order_product_prices.order_id',$order_id)->where('order_product_prices.product_id',$product_id)->where('order_product_prices.price',$price)->first();
   
    	$minimum_quan = DB::table('order_product_prices')
    	->leftJoin('product_attributes','product_attributes.id','=','order_product_prices.attribute_id')
    	->where('order_id',$order_id)->where('order_product_prices.product_id',$product_id)->orderBy('product_attributes.quantity','asc')->select('order_product_prices.price',
    	'product_attributes.quantity')->first();
    
    	$max_quan = DB::table('order_product_prices')
    	->leftJoin('product_attributes','product_attributes.id','=','order_product_prices.attribute_id')
    	->where('order_id',$order_id)->where('order_product_prices.product_id',$product_id)->orderBy('product_attributes.quantity','desc')->select('order_product_prices.price',
    	'product_attributes.quantity')->first();
    	
       
        
    	
    	if($price_data){
    	    echo $price_data->quantity;
    	}
    	
    	else if($price > $max_quan->price){
    	   $low_thr_val = DB::table('order_product_prices')
    	->leftJoin('product_attributes','product_attributes.id','=','order_product_prices.attribute_id')
    	->where('order_id',$order_id)->where('order_product_prices.product_id',$product_id)->where('order_product_prices.price','<',$max_quan->price)->orderBy('product_attributes.quantity','desc')->select('order_product_prices.price',
    	'product_attributes.quantity')->first();
    	
    	    $price_per_liter = ($max_quan->price - $low_thr_val->price)/($max_quan->quantity - $low_thr_val->quantity);
    	    \Log::info($price_per_liter);
    //	    $price_per_liter = float($price_per_liter,2);
    	    $price_per_liter = round($price_per_liter,2);
    	    
    	
            $quantity_gap = ($price - $max_quan->price)/$price_per_liter;
            $quantity_gap =  round($quantity_gap);
            $quantity = $quantity_gap + $max_quan->quantity;
            echo json_encode($quantity);
    	}
    	else if($price < $minimum_quan->price){
    	    $hight_thr_val =  DB::table('order_product_prices')
    	->leftJoin('product_attributes','product_attributes.id','=','order_product_prices.attribute_id')
    	->where('order_id',$order_id)->where('order_product_prices.product_id',$product_id)->where('order_product_prices.price','>',$minimum_quan->price)->orderBy('product_attributes.quantity','asc')->select('order_product_prices.price',
    	'product_attributes.quantity')->first();
    	
    	    $price_per_liter = ($hight_thr_val->price - $low_thr_val->price)/($hight_thr_val->quantity - $low_thr_val->quantity);
    	    $price_per_liter = round($price_per_liter,2);
    	    
    	    $quantity_gap = ($price - $minimum_quan->price)/$price_per_liter;
            $quantity_gap =  round($quantity_gap);
            $quantity = $quantity_gap + $minimum_quan->quantity;
            echo json_encode($quantity);
    	}
    	else{
    	 
    	
    	$low_thr_val = DB::table('order_product_prices')
    	->leftJoin('product_attributes','product_attributes.id','=','order_product_prices.attribute_id')
    	->where('order_id',$order_id)->where('order_product_prices.product_id',$product_id)->where('order_product_prices.price','<',$price)->orderBy('product_attributes.quantity','desc')->select('order_product_prices.price',
    	'product_attributes.quantity')->first();
    	
    	$hight_thr_val =  DB::table('order_product_prices')
    	->leftJoin('product_attributes','product_attributes.id','=','order_product_prices.attribute_id')
    	->where('order_id',$order_id)->where('order_product_prices.product_id',$product_id)->where('order_product_prices.price','>',$price)->orderBy('product_attributes.quantity','asc')->select('order_product_prices.price',
    	'product_attributes.quantity')->first();
    	
    	$price_per_liter = ($hight_thr_val->price - $low_thr_val->price)/($hight_thr_val->quantity - $low_thr_val->quantity);
    	$price_per_liter = round($price_per_liter,2);
        $quantity_gap = ($price - $low_thr_val->price)/$price_per_liter;
        
            $quantity_gap =  round($quantity_gap);
            
            
            $quantity = $quantity_gap + $low_thr_val->quantity;
           
            echo json_encode($quantity);
    	    
    	}
    	
    }
    public function updateCutomerNotes(Request $request){
        $order_id = $request->input('orderId');
    	$customer_notes = $request->input('customer_notes');
    	$order  = Order::where('id',$order_id)->update(['delivery_note'=>$customer_notes]);
    	return 1;
    }
    
    public function getAutoPrice($product_id,$demanded_quantity){
        //$order_id = $order_id;
        
    	$product_id 	   = $product_id;
    	$order_id = 0;
    //	$demanded_quantity = $request->qty;
    	// Fetching the available quantity array for the product
    	$quantity_data = DB::table('product_attributes')
    		->leftJoin('attribute_value_product_attribute', 'attribute_value_product_attribute.product_attribute_id','=','product_attributes.id')
			->leftJoin('attribute_values', 'attribute_values.id','=','attribute_value_product_attribute.attribute_value_id')
    		->where('product_attributes.product_id',$product_id)
    		->select('attribute_values.value')
    		->orderBy('attribute_values.value', 'ASC')
    		->get();
    	// Array Of all quantities
    	$quantities = [];
    	foreach($quantity_data as $quantity) {
    		$quantities[] = $quantity->value;
    	}
    	// Case 1st : When demanded_quantity is in the array then fetch the price directly
    	if (in_array($demanded_quantity, $quantities)) {
    		// Fetching the price according to quantity
    		$price = $this->fetch_price_according_quantity($product_id, $demanded_quantity,$order_id);
    		$price = round($price,2);
    		$price = number_format($price,2,'.','');
    		return $price;
    	// Case 2nd : When demanded_quantity is greater than all the quantities
    	} elseif ($demanded_quantity > max($quantities)) {
    		$array_length = count($quantities);
    		$high_threshold_liter = max($quantities);
    		
    		if ($array_length > 1) { 
    		    $low_threshold_liter  = $quantities[$array_length-2];
    		} else { 
    		    $low_threshold_liter  = max($quantities);
    		}
    		
    		$low_thresh_val  = DB::table('order_product_prices')
    	->leftJoin('product_attributes','product_attributes.id','=','order_product_prices.attribute_id')
    	->where('order_id',$order_id)->where('order_product_prices.product_id',$product_id)->where('product_attributes.quantity','<',$demanded_quantity)->select('order_product_prices.price','product_attributes.quantity')->orderBy('product_attributes.quantity','desc')->first();
            if(!$low_thresh_val){
    	  $low_thresh_val  =   DB::table('product_attributes')
    		->leftJoin('attribute_value_product_attribute', 'attribute_value_product_attribute.product_attribute_id','=','product_attributes.id')
			->leftJoin('attribute_values', 'attribute_values.id','=','attribute_value_product_attribute.attribute_value_id')
    		->where('product_attributes.product_id',$product_id)
    		->where('product_attributes.quantity','<',$demanded_quantity)->orderBy('product_attributes.quantity','desc')
    		
    		->first();
    	}
    		$high_threshold_price = $this->fetch_price_according_quantity($product_id, $high_threshold_liter,$order_id);
    		$low_threshold_price = $this->fetch_price_according_quantity($product_id, $low_threshold_liter,$order_id);
    		// Calculating the price per liter 
    		$price_per_liter = ($high_threshold_price - $low_threshold_price) / ($high_threshold_liter - $low_threshold_liter);
    		$price_per_liter = round($price_per_liter,2);
    		// Calculating the price that will be paid
    		//Fill Price
    		
			$fill_price = ($price_per_liter * ($demanded_quantity - $low_thresh_val->quantity)) + $low_thresh_val->price;
		
    			$price = round($fill_price,2);
    		$price = number_format($price,2,'.','');
    		
    			return $price;
    	// Case 3rd : When demanded_quantity is less than all the quantities
    	} elseif ( $demanded_quantity < min($quantities) ) {
    		$array_length = count($quantities);
    		$low_threshold_liter  = min($quantities);
    		if ($array_length > 1) {
    		    $high_threshold_liter  = $quantities[1];
    		} else {
    		    $high_threshold_liter  = min($quantities);
    		}
    		$high_threshold_price = $this->fetch_price_according_quantity($product_id, $high_threshold_liter,$order_id);
    		$low_threshold_price = $this->fetch_price_according_quantity($product_id, $low_threshold_liter,$order_id);
    		// Calculating the price per liter 
    		$price_per_liter = ($high_threshold_price - $low_threshold_price) / ($high_threshold_liter - $low_threshold_liter);
    		$price_per_liter = round($price_per_liter,2);
    		// Calculating the price that will be paid
    		//Fill Price
			$fill_price = ($price_per_liter * ($demanded_quantity - $low_threshold_liter)) + $low_threshold_price;
    	
    		$price = round($fill_price,2);
    		$price = number_format($price,2,'.','');
    		return $price;
    	// Case 4th :  When demanded_quantity is in middle of existimg quantity
    	} else {
    		$low_threshold_liter  = $this->fetch_minimum_quantity($demanded_quantity, $quantities);
    		$high_threshold_liter = $this->fetch_maximum_quantity($demanded_quantity, $quantities);
    		$high_threshold_price = $this->fetch_price_according_quantity($product_id, $high_threshold_liter,$order_id);
    		$low_threshold_price = $this->fetch_price_according_quantity($product_id, $low_threshold_liter,$order_id);
    		// Calculating the price per liter 
    		$price_per_liter = ($high_threshold_price - $low_threshold_price) / ($high_threshold_liter - $low_threshold_liter);
    		$price_per_liter = round($price_per_liter,2);
    		// Calculating the price that will be paid
    		//Fill Price
    	    
			$fill_price = ($price_per_liter * ($demanded_quantity - $low_threshold_liter)) + $low_threshold_price;
			
    		$price = round($fill_price,2);
    		$price = number_format($price,2,'.','');
    		return $price;
    	}
    }
    
    public function pendingOrders(Request $request){
       $columns = array( 
                            0 =>'id', 
                            1 =>'customerName',
                            2=> 'customerAdd',
                            3=> 'quantity',
                            4=> 'created-at',
                            5=> 'total',
                            6=>'status',
                            7=>'order_status',
                            8=>'delivery_date',
                            9=>'driver_name'
                        );
        $totalData = Order::where('oil_type_order','1')->where('order_status','!=','1')->where('orders.order_status_id','!=','1')->count();
        $totalFiltered = $totalData;
        $start = $request->input('start');
        $limit = $request->input('length');
        $drivers = Customer::where(['is_driver' => '1'])->get();
         $order = $columns[$request->input('order.0.column')];
        $dir = $request->input('order.0.dir');
        if($order == 'id'){
            $order = 'orders.id';
        }else if($order == 'customerName'){
             $order = 'customers.name';
        }else if($order == 'customerAdd'){
            $order = 'addresses.address_1';
        }else if($order == 'quantity'){
            $order = 'order_product.product_name';
        }else if($order == 'created-at'){
            $order = 'orders.created_at';
        }else if($order == 'total'){
            $order = 'orders.total';
        }else if($order == 'status'){
            $order = 'order_statuses.name';
        }else if($order == 'order_status'){
            $order = 'order_status.name';
        }else if($order == 'delivery_date'){
            $order = 'orders.delivery_date';
        }else if($order == 'driver_name'){
            $order = 'drivers.name';
        }
        $query1 = [];
        if($request->from_date && $request->to_date){
            $toDate = date("Y-m-d",strtotime($request->to_date));
            $fromDate = date("Y-m-d",strtotime($request->from_date));
            $query1[] = ['orders.created_at','>=',$fromDate];
            $query1[] = ['orders.created_at','<=',$toDate];
        }
        if($request->order_status != ''){
            $query1[] = ['orders.order_status','=',$request->order_status];
        }
        if($request->payment_status != ''){
            $query1[] = ['orders.order_status_id','=',$request->payment_status];
        }
        if(empty($request->input('search.value')))
        {
            
            $list = Order::leftJoin('customers',function($join){
                $join->on('customers.id','=','orders.customer_id')
                ->where('customers.is_driver','=','0');
            })
            ->leftJoin('customers as drivers',function($join){
                $join->on('drivers.id','=','orders.driver_id')
                ->where('drivers.is_driver','=','1')
                ->where('orders.driver_id','!=','');
            })
            ->leftJoin('order_product','order_product.order_id','=','orders.id')
           ->leftJoin('order_statuses','order_statuses.id','=','orders.order_status_id')
             ->leftJoin('order_status','order_status.id','=','orders.order_status')
             ->leftJoin('addresses','addresses.id','=','orders.address_id')
                ->where('orders.oil_type_order','1')
                ->where(function($query){
                    $query->where('orders.order_status','!=','1')
                    ->orWhere('orders.order_status_id','!=','1');
                })
                
                ->where($query1)
                ->select('orders.*')
                ->offset($start)
                         ->limit($limit);
        if($request->driver != ''){
            if($request->driver == '0'){
                $list = $list->whereNull("driver_id");
               
            }else{
                $list = $list->where("driver_id", $request->driver);
               
            }
            
        }
            if($order != 'orders.id'){
                $list = $list->orderBy($order,$dir)->orderBy('orders.id','desc')
                         ->get();
            }else{
                $list = $list->orderBy($order,$dir)
                         ->get();
            }
                    
            $totalData = Order::leftJoin('customers',function($join){
                $join->on('customers.id','=','orders.customer_id')
                ->where('customers.is_driver','=','0');
            })
            ->leftJoin('customers as drivers',function($join){
                $join->on('drivers.id','=','orders.driver_id')
                ->where('drivers.is_driver','=','1')
                ->where('orders.driver_id','!=','');
            })
            ->leftJoin('order_product','order_product.order_id','=','orders.id')
           ->leftJoin('order_statuses','order_statuses.id','=','orders.order_status_id')
             ->leftJoin('order_status','order_status.id','=','orders.order_status')
             ->leftJoin('addresses','addresses.id','=','orders.address_id')
                ->where('orders.oil_type_order','1')->where(function($query){
                    $query->where('orders.order_status','!=','1')
                    ->orWhere('orders.order_status_id','!=','1');
                })
                ->where($query1)
                ->select('orders.*'); 
            if($request->driver != ''){
                if($request->driver == '0'){
                    $totalData = $totalData->whereNull("driver_id");
                   
                }else{
                    $totalData = $totalData->where("driver_id", $request->driver);
                   
                }
            }
            $totalData = $totalData->count();
            $totalFiltered =  $totalData;   
            $oilOrders = $this->transFormOrder($list);
        }else{
            $search = $request->input('search.value'); 

            $list =  Order::leftJoin('customers',function($join){
                $join->on('customers.id','=','orders.customer_id')
                ->where('customers.is_driver','=','0');
            })
             ->leftJoin('customers as drivers',function($join){
                $join->on('drivers.id','=','orders.driver_id')
                ->where('drivers.is_driver','=','1');
            })
             ->leftJoin('order_product','order_product.order_id','=','orders.id')
             ->leftJoin('order_statuses','order_statuses.id','=','orders.order_status_id')
             ->leftJoin('order_status','order_status.id','=','orders.order_status')
             ->leftJoin('addresses','addresses.id','=','orders.address_id')
            ->where('orders.oil_type_order','1')->where(function($query){
                    $query->where('orders.order_status','!=','1')
                    ->orWhere('orders.order_status_id','!=','1');
                })
            ->where(function($query) use($search){
                $query->where('orders.id','LIKE',"%{$search}%")
                ->orWhere('customers.name','LIKE',"%{$search}%")
                 ->orWhere('drivers.name','LIKE',"%{$search}%")
                 ->orWhere('order_product.product_name','LIKE',"%{$search}%")
                 ->orWhere('order_product.quantity','LIKE',"%{$search}%")
                 ->orWhere(DB::raw("(STR_TO_DATE(orders.created_at,'%d/%m/%Y %H:%i:%s'))"), "LIKE", "%{$search}%")
                 ->orWhere('order_statuses.name','LIKE',"%{$search}%")
                 ->orWhere('order_status.name','LIKE',"%{$search}%")
                 ->orWhere('addresses.address_1','LIKE',"%{$search}%")
                  ->orWhere('addresses.address_2','LIKE',"%{$search}%")
                  ->orWhere('addresses.town','LIKE',"%{$search}%")
                   ->orWhere('addresses.county','LIKE',"%{$search}%")
                 ->orwhere('orders.total','LIKE',"%{$search}%");
            })->select('orders.*')
            ->where($query1)
            ->offset($start)
            ->limit($limit);
            if($request->driver != ''){
                if($request->driver == '0'){
                    $list = $list->whereNull("driver_id");
                   
                }else{
                    $list = $list->where("driver_id", $request->driver);
                   
                }
            
            }
            if($order != 'orders.id'){
                $list = $list->orderBy($order,$dir)->orderBy('orders.id','desc')
                         ->get();
            }else{
                $list = $list->orderBy($order,$dir)
                         ->get();
            }
            $totalData = Order::leftJoin('customers',function($join){
                $join->on('customers.id','=','orders.customer_id')
                ->where('customers.is_driver','=','0');
            })
            ->leftJoin('customers as drivers',function($join){
                $join->on('drivers.id','=','orders.driver_id')
                ->where('drivers.is_driver','=','1')
                ->where('orders.driver_id','!=','');
            })
            ->leftJoin('order_product','order_product.order_id','=','orders.id')
           ->leftJoin('order_statuses','order_statuses.id','=','orders.order_status_id')
             ->leftJoin('order_status','order_status.id','=','orders.order_status')
             ->leftJoin('addresses','addresses.id','=','orders.address_id')
                ->where('orders.oil_type_order','1')->where(function($query){
                    $query->where('orders.order_status','!=','1')
                    ->orWhere('orders.order_status_id','!=','1');
                })
                ->where($query1)
                ->select('orders.*'); 
            if($request->driver != ''){
                if($request->driver == '0'){
                    $totalData = $totalData->whereNull("driver_id");
                   
                }else{
                    $totalData = $totalData->where("driver_id", $request->driver);
                   
                }
            }
            $totalData = $totalData->count();
            $totalFiltered = count($list);
            $oilOrders = $this->transFormOrder($list);
        }
        
        $data = array();
        if(!empty($oilOrders))
        {
            foreach ($oilOrders as $order)
            {
                $show =  route('admin.orders.show', $order->id);
                $action = route('admin.order.destroy', [$order->id]);
                $address1 = isset($order->address->address_1) ? $order->address->address_1 : '';
                $address2 = isset($order->address->address_2) ? ', '.$order->address->address_2 : '';
                $town = isset($order->address->town) ? ', '.$order->address->town : '';
                $county = isset($order->address->county) ? ', '.$order->address->county : '';
                

                $img = '';
                $quantity = '';
                $product_name = '';
                if( isset( $order->products ) ){
                    foreach( $order->products as $product ){
                        if($product->oil_type_status == '1'){
                        	$path = \URL::asset('/public/storage/'.$product->cover);
                        	 $img = '<img src="'.$path.'" alt=""  style="height: 15px;width: 15px; margin-right:5px" />';
                        }else{
                        	$path = url('/images/default.jpg');
                        	 $img = '<img src="'.$path.'" alt=""  style="height: 15px;width: 15px; margin-right:5px" />';
                        }
                        if(empty($product['pivot']['quantity'])){
                        	$quantity = '(Fill the Tank)';
                        }else{
                        	$quantity = '('.$product['pivot']['quantity'].')';
                        }
                        $product_name = $product->name;
                    }
                }


                $cover_id = "<a title='Show order' href='{$show}'>".$img.$product_name."</a>".' '.$quantity;
                $date =  date('d/m/Y h:i a', strtotime($order->created_at));
                $total = config('cart.currency_symbol').$order->total;
                $status_name = '';
                if($order->status->name == 'paid'){
                	$status_name = 'badge-success';
                }elseif($order->status->name == 'pending'){
                	$status_name = 'badge-warning';
                }elseif($order->status->name == 'awaiting payment'){
                	$status_name = 'badge-awaiting';
                }elseif($order->status->name == 'error'){
                	$status_name = 'badge-danger';
                }
                if($order->order_status != 1 ||  $order->completed_date == null){
                    $delivery_date = date('d/m/Y', strtotime($order->delivery_date));    
                }else{
                    $delivery_date = date('d/m/Y H:i:a', strtotime($order->completed_date));
                }
                $status = '<span class="badge font-badge '.$status_name.'">'.$order->status->name.'</span>';
                $driver_name = '';
                $order_status = '';
                if($order->order_status == '1'){
                    $order_status = '<span class="badge font-badge badge-success">Completed</span>';
                }else{
                    $order_status = '<span class="badge font-badge badge-warning">Pending</span>';
                }
                if($order->driver_id != ''){
                	foreach($drivers as $driver){
                		if($driver->id == $order->driver_id){
                			$driver_name =  $driver->name;
                		}
                	}
                }
                $csrf_token = csrf_token();
                // {{ ( $order->status->name == 'pending' || $order->status->name == 'awaiting payment' ) ? '': 'disabled' }}
                $actions =  "<form action='{$show}' method='post' id='remove-from-form' class='form-horizontal'><input type='hidden' name='id' value='{ $order->id }'><input type='hidden' name='_token' value='{$csrf_token}' /> <input type='hidden' name='_method' value='delete'><div class='btn-group'><a href='{$show}' class='btn btn-default'><i class='fa fa-eye'></i> View</a><button id='{ $order->id }' type='submit' title='Delete' class='btn btn-danger delete_submit'><i class='fa fa-times'></i> Delete</button></div></form>";                                     
                                                       
                                             
                $nestedData['id'] = $order->id;
                $nestedData['customerName'] = $order->customer->name;
                $nestedData['customerAdd'] = $address1.$address2.$town.$county;
                $nestedData['quantity'] = $cover_id;
                $nestedData['created-at'] = $date;
                $nestedData['total'] = $total;
                $nestedData['status'] = $status;
                $nestedData['order_status'] = $order_status;
                $nestedData['delivery_date'] = $delivery_date;
                $nestedData['driver_name'] = $driver_name;
                $nestedData['actions'] = $actions;
                $data[] = $nestedData;

            }
        }
     $json_data = array(
                    "draw"            => intval($request->input('draw')),  
                    "recordsTotal"    => intval($totalData),  
                    "recordsFiltered" => intval($totalFiltered), 
                    "data"            => $data   
                    );
            
        echo json_encode($json_data);     
    }
    
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request) {
    	// Fetch all orders except oil one
        $list = $this->orderRepo->listOrders('created_at', 'desc');
        
        $orders = $this->transFormOrder($list);
        // Fetch all oil orders
       
        // $completedList = $this->orderRepo->listOrdersByFilter(['oil_type_order'=>'1', 'order_status_id'=>'1']);

        // $list = Order::where('oil_type_order','1')->where('order_status_id','!=','1')->get();

       	// $oilOrders = $this->transFormOrder($list);
        // $completedOrders = $this->transFormOrder($completedList);

        $orderStatuses = OrderStatus::all();
       	//$customerAddress = DB::table('addresses')->where(['id' => $oilOrders->address_id])->first();
        // Fetch the drivers
        $drivers = Customer::where(['is_driver' => '1'])->get();
        $filter_data = [];
        if($request->from_date && $request->to_date){
            $filter_data['from_date'] = $request->from_date;
            $filter_data['to_date'] = $request->to_date;
        }
        if($request->order_status != ''){
            $filter_data['order_status'] = $request->order_status;
        }
        if($request->payment_status != ''){
            $filter_data['payment_status'] = $request->payment_status;
        }
        if($request->driver != ''){
            $filter_data['driver'] = $request->driver;
        }
        return view('admin.orders.list', ['orders' => $orders,'drivers' => $drivers, 'orderStatuses' => $orderStatuses,"filter_data" => $filter_data]);
    }
    
    public function completedOrders(Request $request){
        
       $columns = array( 
                            0 =>'id', 
                            1 =>'customerName',
                            2=> 'customerAdd',
                            3=> 'quantity',
                            4=> 'created-at',
                            5=> 'total',
                            6=>'status',
                            7=>'order_status',
                            8=>'delivery_date',
                            9=>'driver_name'
                        );
        $totalData = Order::where('oil_type_order','1')->where('order_status','=','1')->count();
        $totalFiltered = $totalData;
        $start = $request->input('start');
        $limit = $request->input('length');
        $drivers = Customer::where(['is_driver' => '1'])->get();
         $order = $columns[$request->input('order.0.column')];
        $dir = $request->input('order.0.dir');
        $query1 = [];
        if($request->from_date && $request->to_date){
            $toDate = date("Y-m-d",strtotime($request->to_date));
            $fromDate = date("Y-m-d",strtotime($request->from_date));
            $query1[] = ['orders.created_at','>=',$fromDate];
            $query1[] = ['orders.created_at','<=',$toDate];
        }
        if($request->order_status != ''){
            $query1[] = ['orders.order_status','=',$request->order_status];
        }
        if($request->payment_status != ''){
            $query1[] = ['orders.order_status_id','=',$request->payment_status];
        }
        
        if($order == 'id'){
            $order = 'orders.id';
        }else if($order == 'customerName'){
             $order = 'customers.name';
        }else if($order == 'customerAdd'){
            $order = 'addresses.address_1';
        }else if($order == 'quantity'){
            $order = 'order_product.product_name';
        }else if($order == 'created-at'){
            $order = 'orders.created_at';
        }else if($order == 'total'){
            $order = 'orders.total';
        }else if($order == 'status'){
            $order = 'order_statuses.name';
        }else if($order == 'order_status'){
            $order = 'order_status.name';
        }else if($order == 'delivery_date'){
            $order = 'orders.delivery_date';
        }else if($order == 'driver_name'){
            $order = 'drivers.name';
        }
        if(empty($request->input('search.value')))
        {
            
            $list = Order::leftJoin('customers',function($join){
                $join->on('customers.id','=','orders.customer_id')
                ->where('customers.is_driver','=','0');
            })
            ->leftJoin('customers as drivers',function($join){
                $join->on('drivers.id','=','orders.driver_id')
                ->where('drivers.is_driver','=','1')
                ->where('orders.driver_id','!=','');
            })
            ->leftJoin('order_product','order_product.order_id','=','orders.id')
           ->leftJoin('order_statuses','order_statuses.id','=','orders.order_status_id')
             ->leftJoin('order_status','order_status.id','=','orders.order_status')
             ->leftJoin('addresses','addresses.id','=','orders.address_id')
                ->where('orders.oil_type_order','1')->where('orders.order_status','=','1')
                ->where('orders.order_status_id','=','1')
                ->where($query1)
                ->select('orders.*')
                ->offset($start)
                         ->limit($limit);
            if($request->driver != ''){
                if($request->driver == '0'){
                    $list = $list->whereNull("driver_id");
                   
                }else{
                    $list = $list->where("driver_id", $request->driver);
                   
                }
            
            }
            if($order != 'orders.id'){
                $list = $list->orderBy($order,$dir)->orderBy('orders.id','desc')
                         ->get();
            }else{
                $list = $list->orderBy($order,$dir)
                         ->get();
            }
            
            $totalData = Order::leftJoin('customers',function($join){
                $join->on('customers.id','=','orders.customer_id')
                ->where('customers.is_driver','=','0');
            })
            ->leftJoin('customers as drivers',function($join){
                $join->on('drivers.id','=','orders.driver_id')
                ->where('drivers.is_driver','=','1')
                ->where('orders.driver_id','!=','');
            })
            ->leftJoin('order_product','order_product.order_id','=','orders.id')
           ->leftJoin('order_statuses','order_statuses.id','=','orders.order_status_id')
             ->leftJoin('order_status','order_status.id','=','orders.order_status')
             ->leftJoin('addresses','addresses.id','=','orders.address_id')
                ->where('orders.oil_type_order','1')->where('orders.order_status','=','1')
                 ->where('orders.order_status_id','=','1')
                ->where($query1)
                ->select('orders.*');
            if($request->driver != ''){
                if($request->driver == '0'){
                    $totalData = $totalData->whereNull("driver_id");
                   
                }else{
                    $totalData = $totalData->where("driver_id", $request->driver);
                   
                }
            
            }
            
            $totalData = $totalData->count();
             $totalFiltered =  $totalData;            
                       
            $oilOrders = $this->transFormOrder($list);
        }else{
            $search = $request->input('search.value'); 

            $list =  Order::leftJoin('customers',function($join){
                $join->on('customers.id','=','orders.customer_id')
                ->where('customers.is_driver','=','0');
            })
             ->leftJoin('customers as drivers',function($join){
                $join->on('drivers.id','=','orders.driver_id')
                ->where('drivers.is_driver','=','1');
            })
             ->leftJoin('order_product','order_product.order_id','=','orders.id')
             ->leftJoin('order_statuses','order_statuses.id','=','orders.order_status_id')
             ->leftJoin('order_status','order_status.id','=','orders.order_status')
             ->leftJoin('addresses','addresses.id','=','orders.address_id')
            ->where('orders.oil_type_order','1')->where('orders.order_status','=','1')
             ->where('orders.order_status_id','=','1')
            ->where(function($query) use($search){
                $query->where('orders.id','LIKE',"%{$search}%")
                ->orWhere('customers.name','LIKE',"%{$search}%")
                 ->orWhere('drivers.name','LIKE',"%{$search}%")
                 ->orWhere('order_product.product_name','LIKE',"%{$search}%")
                 ->orWhere('order_product.quantity','LIKE',"%{$search}%")
                 ->orWhere(DB::raw("(STR_TO_DATE(orders.created_at,'%d/%m/%Y %H:%i:%s'))"), "LIKE", "%{$search}%")
                 ->orWhere('order_statuses.name','LIKE',"%{$search}%")
                 ->orWhere('order_status.name','LIKE',"%{$search}%")
                 ->orWhere('addresses.address_1','LIKE',"%{$search}%")
                  ->orWhere('addresses.address_2','LIKE',"%{$search}%")
                  ->orWhere('addresses.town','LIKE',"%{$search}%")
                   ->orWhere('addresses.county','LIKE',"%{$search}%")
                 ->orwhere('orders.total','LIKE',"%{$search}%");
            })->select('orders.*')
            ->offset($start)
            ->limit($limit)
            ->orderBy($order,$dir)
            ->where($query1);
            if($request->driver != ''){
                if($request->driver == '0'){
                    $list = $list->whereNull("driver_id");
                   
                }else{
                    $list = $list->where("driver_id", $request->driver);
                   
                }
            
            }
            $list = $list->get();

            $totalFiltered = Order::leftJoin('customers',function($join){
                $join->on('customers.id','=','orders.customer_id')
                ->where('customers.is_driver','=','0');
            })
             ->leftJoin('customers as drivers',function($join){
                $join->on('drivers.id','=','orders.driver_id')
                ->where('drivers.is_driver','=','1');
            })
             ->leftJoin('order_product','order_product.order_id','=','orders.id')
             ->leftJoin('order_statuses','order_statuses.id','=','orders.order_status_id')
             ->leftJoin('order_status','order_status.id','=','orders.order_status')
             ->leftJoin('addresses','addresses.id','=','orders.address_id')
            ->where('orders.oil_type_order','1')->where('orders.order_status','=','1')
             ->where('orders.order_status_id','=','1')
            ->where(function($query) use($search){
                $query->where('orders.id','LIKE',"%{$search}%")
                ->orWhere('customers.name','LIKE',"%{$search}%")
                 ->orWhere('drivers.name','LIKE',"%{$search}%")
                 ->orWhere('order_product.product_name','LIKE',"%{$search}%")
                 ->orWhere('order_product.quantity','LIKE',"%{$search}%")
                 ->orWhere(DB::raw("(STR_TO_DATE(orders.created_at,'%d/%m/%Y %H:%i:%s'))"), "LIKE", "%{$search}%")
                 ->orWhere('order_statuses.name','LIKE',"%{$search}%")
                 ->orWhere('order_status.name','LIKE',"%{$search}%")
                 ->orWhere('addresses.address_1','LIKE',"%{$search}%")
                  ->orWhere('addresses.address_2','LIKE',"%{$search}%")
                  ->orWhere('addresses.town','LIKE',"%{$search}%")
                   ->orWhere('addresses.county','LIKE',"%{$search}%")
                 ->orwhere('orders.total','LIKE',"%{$search}%");
            })->where($query1);
            if($request->driver != ''){
                if($request->driver == '0'){
                    $totalFiltered = $totalFiltered->whereNull("driver_id");
                   
                }else{
                    $totalFiltered = $totalFiltered->where("driver_id", $request->driver);
                   
                }
            
            }
            
            $totalData = Order::leftJoin('customers',function($join){
                $join->on('customers.id','=','orders.customer_id')
                ->where('customers.is_driver','=','0');
            })
            ->leftJoin('customers as drivers',function($join){
                $join->on('drivers.id','=','orders.driver_id')
                ->where('drivers.is_driver','=','1')
                ->where('orders.driver_id','!=','');
            })
            ->leftJoin('order_product','order_product.order_id','=','orders.id')
           ->leftJoin('order_statuses','order_statuses.id','=','orders.order_status_id')
             ->leftJoin('order_status','order_status.id','=','orders.order_status')
             ->leftJoin('addresses','addresses.id','=','orders.address_id')
                ->where('orders.oil_type_order','1')->where('orders.order_status_id','=','1')
                 ->where('orders.order_status_id','=','1')
                ->where($query1)
                ->select('orders.*')
                ->offset($start)
                         ->limit($limit);
            if($request->driver != ''){
                if($request->driver == '0'){
                    $totalData = $totalData->whereNull("driver_id");
                   
                }else{
                    $totalData = $totalData->where("driver_id", $request->driver);
                   
                }
            
            }
            
            $totalData = $totalData->count();
            
            $totalFiltered = $totalFiltered->count();
            $oilOrders = $this->transFormOrder($list);
        }
        
        $data = array();
        if(!empty($oilOrders))
        {
            foreach ($oilOrders as $order)
            {
                $show =  route('admin.orders.show', $order->id);
                $action = route('admin.order.destroy', [$order->id]);
                $address1 = isset($order->address->address_1) ? $order->address->address_1 : '';
                $address2 = isset($order->address->address_2) ? $order->address->address_2 : '';
                $town = isset($order->address->town) ? $order->address->town : '';
                $county = isset($order->address->county) ? $order->address->county : '';
                

                $img = '';
                $quantity = '';
                $product_name = '';
                if( isset( $order->products ) ){
                    foreach( $order->products as $product ){
                        if($product->oil_type_status == '1'){
                        	$path = \URL::asset('/public/storage/'.$product->cover);
                        	 $img = '<img src="'.$path.'" alt=""  style="height: 15px;width: 15px; margin-right:5px" />';
                        }else{
                        	$path = url('/images/default.jpg');
                        	 $img = '<img src="'.$path.'" alt=""  style="height: 15px;width: 15px; margin-right:5px" />';
                        }
                        if(empty($product['pivot']['quantity'])){
                        	$quantity = '(Fill the Tank)';
                        }else{
                        	$quantity = '('.$product['pivot']['quantity'].')';
                        }
                        $product_name = $product->name;
                    }
                }


                $cover_id = "<a title='Show order' href='{$show}'>".$img.$product_name."</a>".' '.$quantity;
                $date =  date('d/m/Y h:i a', strtotime($order->created_at));
                $total = config('cart.currency_symbol').$order->total;
                $status_name = '';
                if($order->status->name == 'paid'){
                	$status_name = 'badge-success';
                }elseif($order->status->name == 'pending'){
                	$status_name = 'badge-warning';
                }elseif($order->status->name == 'awaiting payment'){
                	$status_name = 'badge-awaiting';
                }elseif($order->status->name == 'error'){
                	$status_name = 'badge-danger';
                }
                if($order->order_status != 1 ||  empty($order->completed_date)){
                    $delivery_date = date('d/m/Y', strtotime($order->delivery_date));    
                }else{
                    $delivery_date = date('d/m/Y H:i:a', strtotime($order->completed_date));
                }
                $status = '<span class="badge font-badge '.$status_name.'">'.$order->status->name.'</span>';
                $driver_name = '';
                $order_status = '';
                if($order->order_status == '1'){
                    $order_status = '<span class="badge font-badge badge-success">Completed</span>';
                }else{
                    $order_status = '<span class="badge font-badge badge-warning">Pending</span>';
                }
                if($order->driver_id != ''){
                	foreach($drivers as $driver){
                		if($driver->id == $order->driver_id){
                			$driver_name =  $driver->name;
                		}
                	}
                }
                $csrf_token = csrf_token();
                // {{ ( $order->status->name == 'pending' || $order->status->name == 'awaiting payment' ) ? '': 'disabled' }}
                $actions =  "<form action='{$show}' method='post' id='remove-from-form' class='form-horizontal'><input type='hidden' name='id' value='{ $order->id }'><input type='hidden' name='_token' value='{$csrf_token}' /> <input type='hidden' name='_method' value='delete'><div class='btn-group'><a href='{$show}' class='btn btn-default'><i class='fa fa-eye'></i> View</a><button id='{ $order->id }' type='submit' title='Delete' class='btn btn-danger delete_submit' disabled><i class='fa fa-times'></i> Delete</button></div></form>";                                     
                                                       
                                             
                $nestedData['id'] = $order->id;
                $nestedData['customerName'] = $order->customer->name;
                $nestedData['customerAdd'] = $address1.$address2.$town.$county;
                $nestedData['quantity'] = $cover_id;
                $nestedData['created-at'] = $date;
                $nestedData['total'] = $total;
                $nestedData['status'] = $status;
                $nestedData['order_status'] = $order_status;
                $nestedData['delivery_date'] = $delivery_date;
                $nestedData['driver_name'] = $driver_name;
                $nestedData['actions'] = $actions;
                $data[] = $nestedData;

            }
        }
     $json_data = array(
                    "draw"            => intval($request->input('draw')),  
                    "recordsTotal"    => intval($totalData),  
                    "recordsFiltered" => intval($totalFiltered), 
                    "data"            => $data   
                    );
            
        echo json_encode($json_data);     
    }
    
    public function handlePaymentSubmission(Request $request){
       
        $pares = $request->input('cres');
        $order_id = $request->input('threeDSSessionData');
        $elavon_user_name = config('elavon.key');
        $elavon_user_password = config('elavon.secret');
        $order_data = Order::find($order_id);
        $base_inc = base64_encode($elavon_user_name.':'.$elavon_user_password);
        $vendor_name = config('elavon.vendorName');
         $payment_payload = json_encode( array(
                "cRes"=> $pares
                
              
            ));
       
        $ch = curl_init();
        $header[] = 'Content-type: application/json';
        $header[] = 'Authorization: Basic '.$base_inc;
        curl_setopt($ch, CURLOPT_URL,$this->elavonUrl."/api/v1/transactions/".$order_data->transaction_id."/3d-secure-challenge");
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payment_payload);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
        $server_output_pay = curl_exec($ch);
        $serialized_result = json_decode($server_output_pay);
        \Log::info(print_r($serialized_result,true));
        if(isset($serialized_result->status) && $serialized_result->status == 'Ok'){
            $order_data->transaction_status = $order_data->fill_the_tank_status == '1' ? 'requires_confirmation' : 'succeeded';
            $order_data->order_status_id = 1;
            $order_data->save();
            DB::commit();
            return redirect()->route('admin.orders.index')->with('message', 'Order created successfully.');

        }else{
              return redirect()->route('admin.orders.index')->with('error', 'Some error in creating order.');
        }
    }
    
     public function handlePayment(Request $request){
       
        $pares = $request->input('cres');
        $order_id = $request->input('threeDSSessionData');
        $elavon_user_name = config('elavon.key');
        $elavon_user_password = config('elavon.secret');
        $order_data = Order::find($order_id);
        $base_inc = base64_encode($elavon_user_name.':'.$elavon_user_password);
        $vendor_name = config('elavon.vendorName');
         $payment_payload = json_encode( array(
                "cRes"=> $pares
                
              
            ));
       
        $ch = curl_init();
        $header[] = 'Content-type: application/json';
        $header[] = 'Authorization: Basic '.$base_inc;
        curl_setopt($ch, CURLOPT_URL,$this->elavonUrl."/api/v1/transactions/".$order_data->transaction_id."/3d-secure-challenge");
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payment_payload);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
        $server_output_pay = curl_exec($ch);
        $serialized_result = json_decode($server_output_pay);
        \Log::info(print_r($serialized_result,true));
        if(isset($serialized_result->status) && $serialized_result->status == 'Ok'){
            $order_data->transaction_status = $order_data->fill_the_tank_status == '1' ? 'requires_confirmation' : 'succeeded';
            $order_data->order_status_id = 1;
            $order_data->save();
            \Session::flash('message', "Payment successfull!");
                    return redirect()->route('admin.orders.show', $order_data->id);

        }else{
            \Session::flash('error', "Payment not successfull!");
                    return redirect()->route('admin.orders.show', $order_data->id);
        }
    }
}

Spamworldpro Mini