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/Front/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /home/corals/mcoil.corals.io/app/Http/Controllers/Front/QuoteController.php
<?php

namespace App\Http\Controllers\Front;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Shop\Customers\Customer;
use App\Shop\Counties\County;
use App\Shop\Towns\Town;
use App\Shop\Products\Product;
use App\Shop\Addresses\Address;
use App\Shop\ProductAttributes\ProductAttribute;
use App\Http\Controllers\Front\HomeController;
// use App\Shop\HoldOrders\HoldOrder;
// use App\Shop\HoldOrderProducts\HoldOrderProduct;
use App\Shop\Orders\Order;
use App\Shop\OrderProducts\OrderProduct;
use App\Shop\FillTanks\FillTank;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;

//include(app_path() . '\Libraries\stripe\vendor\autoload.php');
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 QuoteController extends Controller {

    private $home_controller;
    private $apiKey;
    private $stripeService;
    private $elavonUrl;

    public function __construct(HomeController $home_obj){
        $this->home_controller = $home_obj;
        // $this->apiKey = 'sk_test_BrULMa23II4aMdRYy5BvKlkn00QxgAiqJe';
        $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'); 
    }

    // Function to show quote checkout page
    public function quote_checkout(Request $request) {
        $url = 'https://www.google.com/recaptcha/api/siteverify';
        $remoteip = $_SERVER['REMOTE_ADDR'];
        $data = [
        'secret' => config('services.recaptcha.secret'),
        'response' => $request->get('recaptcha'),
        'remoteip' => $remoteip
      ];
      $options = [
        'http' => [
          'header' => "Content-type: application/x-www-form-urlencoded\r\n",
          'method' => 'POST',
          'content' => http_build_query($data)
        ]
    ];
    $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        $resultJson = json_decode($result);

        $orderId = $request->get('order_id');
        if (is_null($orderId)) {
            if ($resultJson->success != true) {
             //return back()->withErrors(['captcha' => 'ReCaptcha Error']);
            }
        }

        // Check if user is not logged-in, then redirect them to login page
        if (!Auth::check()) {
            return redirect()->route('cart.login');
        }
        // Retrieving the user_id 
        $user_id = Auth::id();
        // If order doesn't exist go ahead and create a new order
        if (is_null($orderId)) {
            // Get the discount fields
            $applied_discount_code      = $request->get('applied_discount_code');
            $applied_discount_amount    = $request->get('applied_discount_amount');
            $applied_discount_code_type = $request->get('applied_discount_code_type');
            $applied_discount_value     = $request->get('applied_discount_value');
            // Fetch User data
            $customer_data = Customer::find($user_id);
            // Checking the session  if not exist then redirect to home page
            if ($request->session()->has('county_name_quote')) {
                $county_id = session()->get('county_name_quote');
                $town_id = session()->get('town_name_quote');
                $product_id = session()->get('product_name_quote');
                $product_attribiute_id = session()->get('quantity_name_quote');
            } else {
                return redirect()->route('home');
            }
            // Fetching the productdata that is in session
            $product_session_data = Product::find($product_id);
            // Fetching price
            if ($product_attribiute_id =="fill the tank") {
                //$initial_quote_price = "2500.00";
                $initial_quote_price = $this->fill_the_tank_price();
            } else {
                $initial_quote_price  = $this->home_controller->get_initial_price($product_attribiute_id);
            }
            // Fetching quantity
            if ($product_attribiute_id == "fill the tank") {
                $quantity = "fill the tank";
            } else {
                $quantity = $this->get_quantity($product_attribiute_id);
            }
            // Fetch Addresses
            $delivery_address_list = Address::where('customer_id',$user_id)->where('billing_type_address',0)->orderBy('id', 'asc')->get();
            // Fetch billing type address if available
            $billing_address = Address::where('customer_id',$user_id)->where('billing_type_address',1)->orderBy('id', 'asc')->first();
            // VAT and Order Total Calculation
            $product_data = Product::find($product_id);
            // If some discount is available, deduct that amount from total
            if ($applied_discount_code != '' && $applied_discount_amount != '') {
                // $vat_value     = ( ( $product_data->tax / 100 ) * ( $initial_quote_price - $applied_discount_amount ) );
                // New formulae
                $vat_value = (($initial_quote_price * $product_data->tax) / 100);
                $order_total = $initial_quote_price + $vat_value;
                $order_total = $order_total - $applied_discount_amount;
                // Set the values in session
                $request->session()->put('applied_discount_code', $applied_discount_code);
                $request->session()->put('applied_discount_amount', $applied_discount_amount);
                $request->session()->put('applied_discount_code_type', $applied_discount_code_type);
                $request->session()->put('applied_discount_value', $applied_discount_value);
            } else {
                // $vat_value     = ($product_data->tax/100)*$initial_quote_price;
                $vat_value    = (($initial_quote_price * $product_data->tax) / 100);
                $order_total  =  $initial_quote_price + $vat_value;
            }
            return view('front.quote.checkout',['customer_data'=>$customer_data, 'product_session_data'=>$product_session_data, 'quantity'=>$quantity, 'initial_quote_price'=>$initial_quote_price, 'delivery_address_list'=>$delivery_address_list, 'billing_address'=>$billing_address,'vat_percentage'=>$product_data->tax,'vat_value'=>$vat_value,'order_total'=>$order_total, 'applied_discount_code' => $applied_discount_code, 'applied_discount_amount' => $applied_discount_amount]);
        } else {
            // If order exist, show the details and allow user to make payment
            $orderDetails = Order::find($orderId);
            $orderProduct = OrderProduct::where(['order_id' => $orderId])->first();
            // Fetch User data
            $customer_data = Customer::find($user_id);
            // Fetching the productdata that is in session
            $productDetails = Product::find($orderProduct->product_id);
            // Fetching price
            $initial_quote_price = $orderDetails->total_products;
            // Fetching quantity
            $quantity = $orderProduct->quantity;
            // Fetch Addresses
            $delivery_address_list = Address::where('customer_id', $user_id)->where('billing_type_address',0)->orderBy('id', 'asc')->get();
            // Fetch billing type address if available
            $billing_address = Address::where('customer_id', $user_id)->where('billing_type_address',1)->orderBy('id', 'asc')->first();
            return view('front.quote.checkout', [
                'customer_data' => $customer_data, 
                'product_session_data' => $productDetails, 
                'quantity' => $quantity, 
                'initial_quote_price' => $initial_quote_price, 
                'delivery_address_list' => $delivery_address_list, 
                'billing_address' => $billing_address,
                'vat_percentage' => $orderDetails->tax_percentage,
                'vat_value' => $orderDetails->tax_value,
                'order_total' => $orderDetails->total, 
                'applied_discount_code' => $orderDetails->discount_coupon_code, 
                'applied_discount_amount' => $orderDetails->discount_amount,
                'order_id' => $orderId
            ]);
        }
    } 

    public function get_quantity($product_attribiute_id) {
        $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.id',$product_attribiute_id)
            ->first();
        return $product_attributes_data->value;
    }

    public function get_address(Request $request) {
        $address_data = Address::find($request->address_id);
        echo json_encode($address_data);
    }

    // Function to order oil and process stripe intent
    public function order(Request $request) {
        
        $url = 'https://www.google.com/recaptcha/api/siteverify';
        $remoteip = $_SERVER['REMOTE_ADDR'];
        $data = [
        'secret' => config('services.recaptcha.secret'),
        'response' => $request->get('recaptcha'),
        'remoteip' => $remoteip
      ];
      $options = [
        'http' => [
          'header' => "Content-type: application/x-www-form-urlencoded\r\n",
          'method' => 'POST',
          'content' => http_build_query($data)
        ]
    ];
    $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        $resultJson = json_decode($result);
        if ($resultJson->success != true) {
         //return back()->withErrors(['captcha' => 'ReCaptcha Error']);
        }
        
        $billig_address_id = '';
        $delivery_address_id = '';
        // Retrieving the user_id 
        $user_id = Auth::id();
        // Get the order id ( if exist )
        $orderId = $request->order_id;
        
        // If order id is null, process the order as a new order
        if (is_null($orderId)) {
            // Fetch User data
            $customer_data = Customer::find($user_id);
            // Checking the session if not exist then redirect to home page
            if ($request->session()->has('county_name_quote')) {
                $county_id = session()->get('county_name_quote');
                $town_id = session()->get('town_name_quote');
                $product_id = session()->get('product_name_quote');
                $product_attribiute_id = session()->get('quantity_name_quote');
            } else {
                return redirect()->route('home');
            }
            // Fetching price
            if ($product_attribiute_id =="fill the tank") {
                $initial_quote_price = $this->fill_the_tank_price();
            } else {
                $initial_quote_price  = $this->home_controller->get_initial_price($product_attribiute_id);
            }
            // Fetching quantity
            if ($product_attribiute_id == "fill the tank") {
                $quantity = "fill the tank";
            } else {
                $quantity = $this->get_quantity($product_attribiute_id);
            }
            // Storing the billing address in the database if not added previously else update 
            // Check if billing address available
            $billing_address = Address::where('customer_id',$user_id)->where('billing_type_address',1)->first();
            if ($billing_address) {
                // Update Billing Address
                $address_obj = Address::find($billing_address->id);
                $address_obj->customer_id = $user_id;
                $address_obj->country_id = 1;
                $address_obj->address_1 = $request->address_line1_billing;
                $address_obj->address_2 = $request->address_line2_billing;
                $address_obj->county = $request->county_billing;
                $address_obj->town = $request->town_billing;
                $address_obj->zip = $request->postal_code_billing;
                $address_obj->phone = $request->contact_billing;
                $address_obj->billing_type_address = 1;
                $address_obj->status = 1;
                $address_obj->save();
                $billig_address_id = $billing_address->id;
            } else {
                // Add billing address
                $address_obj = new Address();
                $address_obj->customer_id = $user_id;
                $address_obj->country_id = 1;
                $address_obj->address_1 = $request->address_line1_billing;
                $address_obj->address_2 = $request->address_line2_billing;
                $address_obj->county = $request->county_billing;
                $address_obj->town = $request->town_billing;
                $address_obj->zip = $request->postal_code_billing;
                $address_obj->phone = $request->contact_billing;
                $address_obj->billing_type_address = 1;
                $address_obj->status = 1;
                $address_obj->save();
                $billig_address_id = $address_obj->id;
            }

            /*
            // If order is not fill the tank option we are initially capturing maximum tank price but will reset after setting the quantity at time of delivery
            $maximum_tank_price = $this->fill_the_tank_price();

            // VAT and Order Total Calculation
            $product_data = Product::find($product_id);

            // For discount
            $applied_discount_code      = session()->get('applied_discount_code');
            $applied_discount_amount    = session()->get('applied_discount_amount');
            $applied_discount_code_type = session()->get('applied_discount_code_type');
            $applied_discount_value     = session()->get('applied_discount_value');
            
            // If some discount is available, deduct that amount from total
            if( $applied_discount_code != '' && $applied_discount_amount != '' )
            {
                // $vat_value     = ( ( $product_data->tax / 100 ) * ( $initial_quote_price - $applied_discount_amount ) );

                $vat_value    = (($initial_quote_price * $product_data->tax) / 100);
                $order_total  =  $initial_quote_price  + $vat_value;
                
                $order_total = $order_total - $applied_discount_amount;
            }
            else
            {
                // $vat_value     = ($product_data->tax/100)*$initial_quote_price;

                $vat_value    = (($initial_quote_price * $product_data->tax) / 100);
                $order_total  =  $initial_quote_price  + $vat_value;
            }

            // Storing delivery address
            if(isset($request->delivery_address_checkbox) && $request->delivery_address_checkbox == 1){
                $delivery_address_id = $billig_address_id;
            }else{
                $delivery_address_id = $request->address_list;
            }

            // Start transaction
            DB::beginTransaction();

            // Save the order details (As per MO-91)
            $obj = new Order();
            $obj->reference         = $this->random_string(32);
            $obj->courier_id        = 1;
            $obj->customer_id       = $customer_data->id;
            $obj->address_id        = $billig_address_id;
            $obj->order_status_id   = 6;
            $obj->payment           = 'Stripe';
            $obj->total             = $order_total;
            $obj->total_paid        = $order_total;
            $obj->total_products    = $initial_quote_price;

            // For discount
            $obj->discount_coupon_code  = $applied_discount_code;
            $obj->discount_coupon_type  = $applied_discount_code_type;
            $obj->discount_value        = $applied_discount_value;
            $obj->discounts             = isset($applied_discount_amount) ? $applied_discount_amount: 0;
            $obj->discount_amount       = isset($applied_discount_amount) ? $applied_discount_amount: 0;

            $obj->billing_address_id    = $billig_address_id;
            $obj->delivery_address_id   = $delivery_address_id;
            $obj->order_county_id       = $county_id;
            $obj->order_town_id         = $town_id;
            // Initially we pre authorizing all arders for maximum tank parice and storing it in this column
            $obj->initial_price         = $maximum_tank_price;
            if($product_attribiute_id =="fill the tank")
            {
                $obj->fill_the_tank_status = 1;
            }
            
            $obj->delivery_date        = date("Y-m-d", strtotime($request->get('delivery_date')));
            $obj->delivery_note        = $request->get('order_notes');
            $obj->oil_type_order       = 1;
            $obj->created_at           = date("Y-m-d H:i:s");

            // For tax
            $obj->tax_percentage = $product_data->tax;
            $obj->tax = $vat_value;
            $obj->tax_value = $vat_value;

            $savedOrderId = null;
            if( $obj->save() )
            {
                $order_id = $obj->id;

                // Save data to order_product table
                $obj_det = new OrderProduct();
                $obj_det->order_id              =  $order_id;
                $obj_det->product_id            =  $product_id;
                if($product_attribiute_id != "fill the tank"){ $obj_det->product_attribute_id  =  $product_attribiute_id; }
                if($quantity != "fill the tank"){ $obj_det->quantity  =  $quantity; }
                $obj_det->product_name          =  $product_data->name;
                $obj_det->product_sku           =  $product_data->sku;
                $obj_det->product_description   =  $product_data->description;
                $obj_det->product_price         =  $initial_quote_price;
                
                if( $obj_det->save() )
                {
                    DB::commit();
                    $savedOrderId = $order_id;
                }
                else
                {
                    DB::rollBack();
                }
            }
            else
            {
                DB::rollBack();
            }

            // if( !$request->session()->has('session_order_id') )
            if( !is_null( $savedOrderId ) )
            {
                session([
                    'session_order_id'  => $savedOrderId,
                ]);
            }
            */
            // Storing delivery address
            if (isset($request->delivery_address_checkbox) && $request->delivery_address_checkbox == 1) {
                $delivery_address_id = $billig_address_id;
            } else {
                $delivery_address_id = $request->address_list;
            }
            // Storing the address data and delivery date and notes in session
            session([
                'session_billing_address_id'    => $billig_address_id,
                'session_delivery_address_id'   => $delivery_address_id,
                'session_delivery_date'         => str_replace("/", "-", $request->delivery_date),
                'session_delivery_notes'        => $request->order_notes
            ]);
            return redirect()->route('checkout.payment');
        } else {
            // Storing the billing address in the database if not added previously else update 
            // Check if billing address available
            $billing_address = Address::where('customer_id',$user_id)->where('billing_type_address',1)->first();
            if ($billing_address) {
                // Update Billing Address
                $address_obj = Address::find($billing_address->id);
                $address_obj->customer_id = $user_id;
                $address_obj->country_id = 1;
                $address_obj->address_1 = $request->address_line1_billing;
                $address_obj->address_2 = $request->address_line2_billing;
                $address_obj->county = $request->county_billing;
                $address_obj->town = $request->town_billing;
                $address_obj->zip = $request->postal_code_billing;
                $address_obj->phone = $request->contact_billing;
                $address_obj->billing_type_address = 1;
                $address_obj->status = 1;
                $address_obj->save();
                $billig_address_id = $billing_address->id;
            } else {
                // Add billing address
                $address_obj = new Address();
                $address_obj->customer_id = $user_id;
                $address_obj->country_id = 1;
                $address_obj->address_1 = $request->address_line1_billing;
                $address_obj->address_2 = $request->address_line2_billing;
                $address_obj->county = $request->county_billing;
                $address_obj->town = $request->town_billing;
                $address_obj->zip = $request->postal_code_billing;
                $address_obj->phone = $request->contact_billing;
                $address_obj->billing_type_address = 1;
                $address_obj->status = 1;
                $address_obj->save();
                $billig_address_id = $address_obj->id;
            }
            // Storing delivery address
            if (isset($request->delivery_address_checkbox) && $request->delivery_address_checkbox == 1) {
                $delivery_address_id = $billig_address_id;
            } else {
                $delivery_address_id = $request->address_list;
            }
            // Storing the address data and delivery date and notes in session
            session([
                'session_order_id'              => $orderId,
                'session_billing_address_id'    => $billig_address_id,
                'session_delivery_address_id'   => $delivery_address_id,
                'session_delivery_date'         => str_replace("/", "-", $request->delivery_date),
                'session_delivery_notes'        => $request->order_notes
            ]);
            return redirect()->route('checkout.payment');
        }
    }

//     public function payment(Request $request) {
//      // If session doesn't have order id then its a new order
//      if (!$request->session()->has('session_order_id')) {
//          // Checking the session if not exist then redirect to home page
//          if ($request->session()->has('county_name_quote') && $request->session()->has('session_billing_address_id')) {
//              $county_id = session()->get('county_name_quote');
//              $town_id = session()->get('town_name_quote');
//              $product_id = session()->get('product_name_quote');
//              $product_attribiute_id = session()->get('quantity_name_quote');
//              // For discount
//              $applied_discount_code = session()->get('applied_discount_code');
//              $applied_discount_amount = session()->get('applied_discount_amount');
//          } else {
//              return redirect()->route('home');
//          }
//          // Retrieving the user_id 
            
//          $user_id = Auth::id();
//          // Fetch User data
//          $customer_data = Customer::find($user_id);
//          // Fetching the productdata that is in session
//          $product_session_data = Product::find($product_id);
//          // Fetching quantity
//          if ($product_attribiute_id == "fill the tank") {
//              $quantity = "fill the tank";
//          } else {
//              $quantity = $this->get_quantity($product_attribiute_id);
//          }
//          // Fetching price
//          if ($product_attribiute_id =="fill the tank") {
//              $initial_quote_price = $this->fill_the_tank_price();
//          } else {
//              $initial_quote_price  = $this->home_controller->get_initial_price($product_attribiute_id);
//          }
//          // Stripe key 
//          $stripe_key = config('stripe.key');
//          // VAT and Order Total Calculation
//          $product_data = Product::find($product_id);
//          // If some discount is available, deduct that amount from total
//          if ($applied_discount_code != '' && $applied_discount_amount != '') {
//              // $vat_value     = ( ( $product_data->tax / 100 ) * ( $initial_quote_price - $applied_discount_amount ) );
//              $vat_value = (($initial_quote_price * $product_data->tax) / 100);
//              $order_total =  $initial_quote_price + $vat_value;
//              $order_total = $order_total - $applied_discount_amount;
//          } else {
//              // $vat_value     = ($product_data->tax/100)*$initial_quote_price;
//              $vat_value = (($initial_quote_price * $product_data->tax) / 100);
//              $order_total = $initial_quote_price + $vat_value;
//          }
//          return view('front.quote.payment',['customer_data'=>$customer_data, 'product_session_data'=>$product_session_data, 'quantity'=>$quantity, 'initial_quote_price'=>$initial_quote_price, 'stripe_key'=>$stripe_key, 'vat_percentage'=>$product_data->tax, 'vat_value'=>$vat_value,'order_total'=>$order_total, 'applied_discount_code' => $applied_discount_code, 'applied_discount_amount' => $applied_discount_amount]);
//      } else {
            
//          $orderId = $request->session()->has('session_order_id') ? $request->session()->get('session_order_id') : 0;
            
//          $orderDetails = Order::find($orderId);
//          $orderProduct = OrderProduct::where(['order_id' => $orderId])->first();
//          // Retrieving the user_id 
//          $user_id = Auth::id();
//          // Fetch User data
//          $customer_data = Customer::find($user_id);
//          // Fetching the productdata that is in session
//          $productDetails = Product::find($orderProduct->product_id);
//          // Fetching price
//          $initial_quote_price = $orderDetails->total_products;
//          // Fetching quantity
//          $quantity = $orderProduct->quantity;
//          // Stripe key 
//          $stripe_key = config('stripe.key');
//          return view('front.quote.payment', [
//              'customer_data' => $customer_data, 
//              'product_session_data' => $productDetails, 
//              'quantity' => $quantity, 
//              'initial_quote_price' => $initial_quote_price, 
//              'stripe_key' => $stripe_key, 
//              'vat_percentage' => $orderDetails->tax_percentage,
//              'vat_value' => $orderDetails->tax_value,
//              'order_total' => $orderDetails->total,
//              'applied_discount_code' => $orderDetails->discount_coupon_code, 
//              'applied_discount_amount' => $orderDetails->discount_amount,
//              'order_id' => $orderId
//          ]);
//      }
//     }
public function payment(Request $request) {
        // If session doesn't have order id then its a new order
        if (!$request->session()->has('session_order_id')) {
         
            // Checking the session if not exist then redirect to home page
            if ($request->session()->has('county_name_quote') && $request->session()->has('session_billing_address_id')) {
                $county_id = session()->get('county_name_quote');
                $town_id = session()->get('town_name_quote');
                $product_id = session()->get('product_name_quote');
                $product_attribiute_id = session()->get('quantity_name_quote');
                // For discount
                $applied_discount_code = session()->get('applied_discount_code');
                $applied_discount_amount = session()->get('applied_discount_amount');
            } else {
                return redirect()->route('home');
            }
            // Retrieving the user_id 
            
            $user_id = Auth::id();
            // Fetch User data
            $customer_data = Customer::find($user_id);
            // Fetching the productdata that is in session
            $product_session_data = Product::find($product_id);
            // Fetching quantity
            if ($product_attribiute_id == "fill the tank") {
                $quantity = "fill the tank";
            } else {
                $quantity = $this->get_quantity($product_attribiute_id);
            }
            // Fetching price
            if ($product_attribiute_id =="fill the tank") {
                $initial_quote_price = $this->fill_the_tank_price();
            } else {
                $initial_quote_price  = $this->home_controller->get_initial_price($product_attribiute_id);
            }
            // Stripe key 
            //$stripe_key = config('stripe.key');
            // VAT and Order Total Calculation
            $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);
            \Log::info(print_r($out,true));
            $merchantSessionKey = $out->merchantSessionKey;
            
            $product_data = Product::find($product_id);
            // If some discount is available, deduct that amount from total
            if ($applied_discount_code != '' && $applied_discount_amount != '') {
                // $vat_value     = ( ( $product_data->tax / 100 ) * ( $initial_quote_price - $applied_discount_amount ) );
                $vat_value = (($initial_quote_price * $product_data->tax) / 100);
                $order_total =  $initial_quote_price + $vat_value;
                $order_total = $order_total - $applied_discount_amount;
            } else {
                // $vat_value     = ($product_data->tax/100)*$initial_quote_price;
                $vat_value = (($initial_quote_price * $product_data->tax) / 100);
                $order_total = $initial_quote_price + $vat_value;
            }
           
            return view('front.quote.payment',['merchantSessionKey'=>$merchantSessionKey,'customer_data'=>$customer_data, 'product_session_data'=>$product_session_data, 'quantity'=>$quantity, 'initial_quote_price'=>$initial_quote_price, 'stripe_key'=>'', 'vat_percentage'=>$product_data->tax, 'vat_value'=>$vat_value,'order_total'=>$order_total, 'applied_discount_code' => $applied_discount_code, 'applied_discount_amount' => $applied_discount_amount]);
        } else {
           
            $orderId = $request->session()->has('session_order_id') ? $request->session()->get('session_order_id') : 0;
            
            $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);
            \Log::info(print_r($out,true));
            $merchantSessionKey = $out->merchantSessionKey;
            
            $orderDetails = Order::find($orderId);
            $orderProduct = OrderProduct::where(['order_id' => $orderId])->first();
            // Retrieving the user_id 
            $user_id = Auth::id();
            // Fetch User data
            $customer_data = Customer::find($user_id);
            // Fetching the productdata that is in session
            $productDetails = Product::find($orderProduct->product_id);
            // Fetching price
            $initial_quote_price = $orderDetails->total_products;
            // Fetching quantity
            $quantity = $orderProduct->quantity;
            // Stripe key 
            $stripe_key = config('stripe.key');
            return view('front.quote.payment', [
                'customer_data' => $customer_data, 
                'product_session_data' => $productDetails, 
                'quantity' => $quantity, 
                'initial_quote_price' => $initial_quote_price, 
                'stripe_key' => $stripe_key, 
                'vat_percentage' => $orderDetails->tax_percentage,
                'vat_value' => $orderDetails->tax_value,
                'order_total' => $orderDetails->total,
                'applied_discount_code' => $orderDetails->discount_coupon_code, 
                'applied_discount_amount' => $orderDetails->discount_amount,
                'order_id' => $orderId,
                'merchantSessionKey'=>$merchantSessionKey
            ]);
        }
    }
    

//     public function submit_payment(Request $request) {
//      if (!$request->session()->has('session_order_id')) {
            
//          // Checking the session if not exist then redirect to home page
//          if ($request->session()->has('county_name_quote') && $request->session()->has('session_billing_address_id')) {
//              $county_id = session()->get('county_name_quote');
//              $town_id = session()->get('town_name_quote');
//              $product_id = session()->get('product_name_quote');
//              $product_attribiute_id = session()->get('quantity_name_quote');
//              $billing_address_id = session()->get('session_billing_address_id');
//              $delivery_address_id = session()->get('session_delivery_address_id');
//              $delivery_date = session()->get('session_delivery_date');
//              $delivery_notes = session()->get('session_delivery_notes');
//              // For discount
//              $applied_discount_code = session()->get('applied_discount_code');
//              $applied_discount_amount = session()->get('applied_discount_amount');
//              $applied_discount_code_type = session()->get('applied_discount_code_type');
//              $applied_discount_value = session()->get('applied_discount_value');
//              $today_date = date('Y-m-d');
//              $del_date = strtr($delivery_date, '/', '-');
//              $date1=date_create($today_date);
//              $delivery_date = date("Y-m-d", strtotime($del_date)); 
//                 $date2=date_create($delivery_date);
                
//                 $diff=date_diff($date1,$date2);
//                 /*$interval = $diff->format("%R%a days");
//              if($interval > 0){
//                  $timestamp = strtotime($delivery_date);
//                  $day = date('D', $timestamp);
                    
//                  if($day == 'Fri' || $day == 'Sat' || $day == 'Sun'){
//                      $delivery_date = date('Y-m-d', strtotime('next monday', strtotime($delivery_date)));
                        
//                  }else{
//                          $delivery_date = $delivery_date;
//                  }
//              }else{
//                  $timestamp = strtotime($delivery_date);
//                  $day = date('D', $timestamp);
//                  if($day == 'Fri' || $day == 'Sat' || $day == 'Sun'){
//                      $delivery_date = date('Y-m-d', strtotime('next monday', strtotime($delivery_date)));
//                  }
//              }*/
//              session()->put('session_delivery_date',$delivery_date);
//          } else {
//              return redirect()->route('home');
//          }
//          $customer_data = Customer::find(Auth::id());
            
//          // Fetching necessary data for payment
//          // Fetching price
//          if ($product_attribiute_id =="fill the tank") {
//              $initial_quote_price = $this->fill_the_tank_price();
//          } else {
//              $initial_quote_price  = $this->home_controller->get_initial_price($product_attribiute_id);
//          }
//          // Fetching quantity
//          if ($product_attribiute_id == "fill the tank") {
//              $quantity = "fill the tank";
//          } else {
//              $quantity = $this->get_quantity($product_attribiute_id);
//          }
//          // Fetching the productdata that is in session
//          $product_session_data = Product::find($product_id);
//          $product_id = $product_session_data->id;
//          $product_name = "Product Name: ".$product_session_data->name;
//          // If order is not fill the tank option we are initially capturing maximum tank price but will reset after setting the quantity at time of delivery
//          $maximum_tank_price = $this->fill_the_tank_price();
//          // VAT and Order Total Calculation
//          $product_data = Product::find($product_id);
//          // If some discount is available, deduct that amount from total
//          if ($applied_discount_code != '' && $applied_discount_amount != '') {
//              // $vat_value = ( ( $product_data->tax / 100 ) * ( $initial_quote_price - $applied_discount_amount ) );
//              $vat_value = (($initial_quote_price * $product_data->tax) / 100);
//              $order_total =  $initial_quote_price  + $vat_value;
//              $order_total = $order_total - $applied_discount_amount;
//          } else {
//              // $vat_value     = ($product_data->tax/100)*$initial_quote_price;
//              $vat_value    = (($initial_quote_price * $product_data->tax) / 100);
//              $order_total  =  $initial_quote_price  + $vat_value;
//          }
//          // Adding tax in maximum tank price for stripe pre authorization
//          $maximum_tank_tax = ($product_data->tax/100) * $maximum_tank_price;

//          if($request->has('payment_option') && $request->input('payment_option') == 'Credit Card'){
//              $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'=> base64_decode($request->input('name'))
//                     ]
                    
//              ]);

//              try {
//                  $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' => round($order_total,2) * 100,
//                      //'amount' => ($maximum_tank_price + $maximum_tank_tax) * 100,
//                      'currency' => $request->currency_code,
//                      'description' => $product_name,
//                      'payment_method_types' => ['card'],
//                      'capture_method' => 'manual',
//                      'payment_method'=>$payment_data->id,
//                      'metadata' => array(
//                          'order_id' => $product_id
//                      ),
//                  );
//                  $result = $payment_intent->create($payment_intent_data);
//                  // Payment Intent Customer -- END
//              }
//               catch(\Stripe\Exception\CardException $e) {
//                // Since it's a decline, \Stripe\Exception\CardException will be caught
//               \Log::info(print_r($e->getError()->message,true));
//                session([ 'session_receive_failed_page' => 1 ]);
//                  return redirect()->route('quoues.checkout.failed')->with('error', $e->getError()->message);
//              } catch (\Stripe\Exception\RateLimitException $e) {
//                  \Log::info(print_r($e->getError()->message,true));
//                session([ 'session_receive_failed_page' => 1 ]);
//                  return redirect()->route('quoues.checkout.failed')->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));
//                session([ 'session_receive_failed_page' => 1 ]);
//                  return redirect()->route('quoues.checkout.failed')->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));
//                session([ 'session_receive_failed_page' => 1 ]);
//                  return redirect()->route('quoues.checkout.failed')->with('error', $e->getError()->message);
//                // Authentication with Stripe's API failed
//                // (maybe you changed API keys recently)
//              } catch (\Stripe\Exception\ApiConnectionException $e) {
//                  \Log::info(print_r($e->getError()->message,true));
//                session([ 'session_receive_failed_page' => 1 ]);
//                  return redirect()->route('quoues.checkout.failed')->with('error', $e->getError()->message);
//                // Network communication with Stripe failed
//              } catch (\Stripe\Exception\ApiErrorException $e) {
//                  \Log::info(print_r($e->getError()->message,true));
//                session([ 'session_receive_failed_page' => 1 ]);
//                  return redirect()->route('quoues.checkout.failed')->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));
//                session([ 'session_receive_failed_page' => 1 ]);
//                  return redirect()->route('quoues.checkout.failed')->with('error', $e->getError()->message);
//                // Something else happened, completely unrelated to Stripe
//              }
//              $serialized_result = $result->jsonSerialize();
//              $obj = new Order();
//              $obj->reference = $this->random_string(32);
//              $obj->courier_id = 1;
//              $obj->customer_id = $customer_data->id;
//              $obj->address_id = $billing_address_id;
//              if ($serialized_result['status'] == 'requires_payment_method' || $serialized_result['status'] == 'requires_confirmation') {
//              $obj->order_status_id = 2; # on-delivery
//              } else {
//              $obj->order_status_id = 3;
//              } # error
//              $obj->payment              = $request->has('payment_option') ? $request->input('payment_option') :'Credit Card';
//              // $obj->total             = $initial_quote_price;
//              $obj->total                = $order_total;
//              $obj->total_paid           = $order_total;
//              // for admin order
//              $obj->total_products       = $initial_quote_price;
//              // For discount
//              $obj->discount_coupon_code = $applied_discount_code;
//              $obj->discount_coupon_type = $applied_discount_code_type;
//              $obj->discount_value       = $applied_discount_value;
//              $obj->discounts            = isset($applied_discount_amount) ? $applied_discount_amount: 0;
//              $obj->discount_amount      = isset($applied_discount_amount) ? $applied_discount_amount: 0;
//              $obj->billing_address_id   = $billing_address_id;
//              $obj->delivery_address_id  = $delivery_address_id;
//              $obj->order_county_id      = $county_id;
//              $obj->order_town_id        = $town_id;
//              // $obj->initial_price        = $initial_quote_price;
//              // Initially we pre authorizing all arders for maximum tank parice and storing it in this column
//              $obj->initial_price    = $maximum_tank_price;
//              if($product_attribiute_id =="fill the tank"){ $obj->fill_the_tank_status = 1; }
//              $obj->transaction_id       = $serialized_result['id'];
//              $obj->stripe_customer_id   = $serialized_result['customer'];
//              $obj->transaction_status   = (isset($serialized_result['status']) && $serialized_result['status'] != '') ? $serialized_result['status'] : 'other_payment';
//              $obj->delivery_date        = $delivery_date;
//              $obj->delivery_note        = $delivery_notes;
//              $obj->oil_type_order       = 1;
//              $obj->created_at           = date("Y-m-d H:i:s");
//              // For tax
//              $obj->tax_percentage = $product_data->tax;
//              $obj->tax = $vat_value;
//              $obj->tax_value = $vat_value;
//              $obj->payment_option = $request->has('payment_option') ? $request->input('payment_option') :'Credit Card';
//              $obj->save();
//              $order_id = $obj->id;
                    
//          }else{
//              $obj = new Order();
//              $obj->reference = $this->random_string(32);
//              $obj->courier_id = 1;
//              $obj->customer_id = $customer_data->id;
//              $obj->address_id = $billing_address_id;
//              $obj->order_status_id = 2;
//              $obj->payment              = $request->has('payment_option') ? $request->input('payment_option') :'Credit Card';
//              // $obj->total             = $initial_quote_price;
//              $obj->total                = $order_total;
//              $obj->total_paid           = $order_total;
//              // for admin order
//              $obj->total_products       = $initial_quote_price;
//              // For discount
//              $obj->discount_coupon_code = $applied_discount_code;
//              $obj->discount_coupon_type = $applied_discount_code_type;
//              $obj->discount_value       = $applied_discount_value;
//              $obj->discounts            = isset($applied_discount_amount) ? $applied_discount_amount: 0;
//              $obj->discount_amount      = isset($applied_discount_amount) ? $applied_discount_amount: 0;
//              $obj->billing_address_id   = $billing_address_id;
//              $obj->delivery_address_id  = $delivery_address_id;
//              $obj->order_county_id      = $county_id;
//              $obj->order_town_id        = $town_id;
//              // $obj->initial_price        = $initial_quote_price;
//              // Initially we pre authorizing all arders for maximum tank parice and storing it in this column
//              $obj->initial_price    = $maximum_tank_price;
//              if($product_attribiute_id =="fill the tank"){ $obj->fill_the_tank_status = 1; }
//              $obj->transaction_id       = '';
//              $obj->stripe_customer_id   = '';
//              $obj->transaction_status   = (isset($serialized_result['status']) && $serialized_result['status'] != '') ? $serialized_result['status'] : 'other_payment';
//              $obj->delivery_date        = $delivery_date;
//              $obj->delivery_note        = $delivery_notes;
//              $obj->oil_type_order       = 1;
//              $obj->created_at           = date("Y-m-d H:i:s");
//              // For tax
//              $obj->tax_percentage = $product_data->tax;
//              $obj->tax = $vat_value;
//              $obj->tax_value = $vat_value;
//              $obj->payment_option = $request->has('payment_option') ? $request->input('payment_option') :'Credit Card';
//              $obj->save();
//              $order_id = $obj->id;
//              $serialized_result['status'] = 'requires_confirmation';     
//          }
//          // Save data to order_product table
//          $obj_det = new OrderProduct();
//          $obj_det->order_id              =  $order_id;
//          $obj_det->product_id            =  $product_id;
//          if($product_attribiute_id != "fill the tank"){ $obj_det->product_attribute_id  =  $product_attribiute_id; }
//          if($quantity != "fill the tank"){ $obj_det->quantity  =  $quantity; }else{
//          $fill_tank_data = FillTank::find(1);
//          $obj_det->quantity = $fill_tank_data->quantity;
//          }
//          $obj_det->product_name          =  $product_session_data->name;
//          $obj_det->product_sku           =  $product_session_data->sku;
//          $obj_det->product_description   =  $product_session_data->description;
//          $obj_det->product_price         =  $initial_quote_price;
//          $obj_det->save();

               

           

            

//          // Save to order table if status == 'is_succeeded'
            
//          // Deleting the session key
//          Session::forget('county_name_quote');
//          Session::forget('town_name_quote');
//          Session::forget('county_name_quote');
//          Session::forget('quantity_name_quote');
//          Session::forget('session_billing_address_id');
//          Session::forget('session_delivery_address_id');
//          //Session::forget('session_delivery_date');
//          Session::forget('session_delivery_notes');
//          Session::forget('applied_discount_code');
//          Session::forget('applied_discount_amount');
//          Session::forget('applied_discount_code_type');
//          Session::forget('applied_discount_value');
//          Session::forget('session_order_id');
//          $employee = Employee::find(1);
//          $data['emailFrom'] = \Config::get('values.MAIL_FROM');
//          // Storing session for success or failed page
//          if ($serialized_result['status'] == 'requires_payment_method' || $serialized_result['status'] == 'requires_confirmation') {
//              $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();
//                  }
//              }
//              session([ 'session_success_page' => 1 ]);
//              try {
//                     //  \Mail::to($customer_data)->send(new SendOrderToCustomerMailable($obj));
//                      \Mail::to(config('constants.ADMIN_EMAIL'))->send(new sendEmailNotificationToAdminMailable($obj));
//                  }
//                  catch(Exception $e) {
//                      \Log::info('Message: ' .$e->getMessage());
//                  }
//              return redirect()->route('quoues.checkout.success');
//          } else {
//              session([ 'session_failed_page' => 1 ]);
//              return redirect()->route('quoues.checkout.failed');
//          }
//      } else {
//          $orderId = session()->get('session_order_id');
//          $orderDetails = Order::find($orderId);
//          $orderProduct = OrderProduct::where(['order_id' => $orderId])->first();
//          $productDetails = Product::find($orderProduct->product_id);
//          $customer_data = Customer::find(Auth::id());
//          if($orderDetails->payment_option == 'Credit Card'){
//              try {
//                  $customerDetailsAry = array(
//                  'email' => $customer_data->email,
//                  'source' => $request->token
//                  );
//                  $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'=>base64_decode($request->input('name'))
//                  ]

//                  ]);
//                  // 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',
//                  'metadata'              => array(
//                  'order_id'    => $orderId
//                  ),
//                  'payment_method'=>$payment_data->id,
//                  );
//                  $result = $payment_intent->create($payment_intent_data);
//                  // Payment Intent Customer -- END
//              }
//              catch(\Stripe\Exception\CardException $e) {
//                    // Since it's a decline, \Stripe\Exception\CardException will be caught
//                   \Log::info(print_r($e->getError()->message,true));
//                    session([ 'session_receive_failed_page' => 1 ]);
//                      return redirect()->route('quoues.checkout.failed')->with('error', $e->getError()->message);
//              } catch (\Stripe\Exception\RateLimitException $e) {
//                      \Log::info(print_r($e->getError()->message,true));
//                    session([ 'session_receive_failed_page' => 1 ]);
//                      return redirect()->route('quoues.checkout.failed')->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));
//                    session([ 'session_receive_failed_page' => 1 ]);
//                      return redirect()->route('quoues.checkout.failed')->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));
//                    session([ 'session_receive_failed_page' => 1 ]);
//                      return redirect()->route('quoues.checkout.failed')->with('error', $e->getError()->message);
//                    // Authentication with Stripe's API failed
//                    // (maybe you changed API keys recently)
//              } catch (\Stripe\Exception\ApiConnectionException $e) {
//                      \Log::info(print_r($e->getError()->message,true));
//                    session([ 'session_receive_failed_page' => 1 ]);
//                      return redirect()->route('quoues.checkout.failed')->with('error', $e->getError()->message);
//                    // Network communication with Stripe failed
//              } catch (\Stripe\Exception\ApiErrorException $e) {
//                      \Log::info(print_r($e->getError()->message,true));
//                    session([ 'session_receive_failed_page' => 1 ]);
//                      return redirect()->route('quoues.checkout.failed')->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));
//                    session([ 'session_receive_failed_page' => 1 ]);
//                      return redirect()->route('quoues.checkout.failed')->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->delivery_date   = date("Y-m-d");
//              $orderDetails->save();

//          }else{
//              $orderDetails->order_status_id = 2;
//              $orderDetails->transaction_id       = '';
//              $orderDetails->stripe_customer_id   = '';
//              $orderDetails->transaction_status   = '';
//              $orderDetails->delivery_date   = date("Y-m-d");
//              $orderDetails->save();
//          }
            
             

            
//          // Deleting the session key
//             Session::forget('county_name_quote');
//             Session::forget('town_name_quote');
//             Session::forget('county_name_quote');
//             Session::forget('quantity_name_quote');
//             Session::forget('session_billing_address_id');
//             Session::forget('session_delivery_address_id');
//             //Session::forget('session_delivery_date');
//             Session::forget('session_delivery_notes');
//             Session::forget('applied_discount_code');
//             Session::forget('applied_discount_amount');
//             Session::forget('applied_discount_code_type');
//             Session::forget('applied_discount_value');
//             Session::forget('session_order_id');
//          // Storing session for success or failed page
//          $employee = Employee::find(1);
//             if ($serialized_result['status'] == 'requires_payment_method' || $serialized_result['status'] == 'requires_confirmation') {
//                 try {
//                     //  \Mail::to($customer_data)->send(new SendOrderToCustomerMailable($orderDetails));
//                      \Mail::to($employee)->send(new sendEmailNotificationToAdminMailable($orderDetails));
//                  }
//                  catch(Exception $e) {
                    
//                  }
//              session([ 'session_success_page' => 1 ]);
//              Session::flash('message', "Payment successfull!");
//              return redirect()->route('quoues.checkout.success');
//             } else {
//              session([ 'session_failed_page' => 1 ]);
//              return redirect()->route('quoues.checkout.failed');
//             }
//      }
//     }
public function submit_payment(Request $request) {
    if (!$request->session()->has('session_order_id')) {
        if ($request->session()->has('county_name_quote') && $request->session()->has('session_billing_address_id')) {

            $county_id = session()->get('county_name_quote');
            $town_id = session()->get('town_name_quote');
            $product_id = session()->get('product_name_quote');
            $product_attribiute_id = session()->get('quantity_name_quote');
            $billing_address_id = session()->get('session_billing_address_id');
            $delivery_address_id = session()->get('session_delivery_address_id');
            $delivery_date = session()->get('session_delivery_date');
            $delivery_notes = session()->get('session_delivery_notes');
            // For discount
            $applied_discount_code = session()->get('applied_discount_code');
            $applied_discount_amount = session()->get('applied_discount_amount');
            $applied_discount_code_type = session()->get('applied_discount_code_type');
            $applied_discount_value = session()->get('applied_discount_value');
            $today_date = date('Y-m-d');
            $del_date = strtr($delivery_date, '/', '-');
            $date1=date_create($today_date);
            $delivery_date = date("Y-m-d", strtotime($del_date)); 
            $date2=date_create($delivery_date);
            
            $diff=date_diff($date1,$date2);
           
            session()->put('session_delivery_date',$delivery_date);
        } else {
            return redirect()->route('home');
        }
        $customer_data = Customer::find(Auth::id());
        if ($product_attribiute_id =="fill the tank") {
            $initial_quote_price = $this->fill_the_tank_price();
        } else {
            $initial_quote_price  = $this->home_controller->get_initial_price($product_attribiute_id);
        }
        if ($product_attribiute_id == "fill the tank") {
            $quantity = "fill the tank";
        } else {
            $quantity = $this->get_quantity($product_attribiute_id);
        }
        
        // Fetching the productdata that is in session
        $product_session_data = Product::find($product_id);
        $product_id = $product_session_data->id;
        $product_name = "Product Name: ".$product_session_data->name;
        // If order is not fill the tank option we are initially capturing maximum tank price but will reset after setting the quantity at time of delivery
        $maximum_tank_price = $this->fill_the_tank_price();
        // VAT and Order Total Calculation
        $product_data = Product::find($product_id);
        // If some discount is available, deduct that amount from total
        if ($applied_discount_code != '' && $applied_discount_amount != '') {
            // $vat_value = ( ( $product_data->tax / 100 ) * ( $initial_quote_price - $applied_discount_amount ) );
            $vat_value = (($initial_quote_price * $product_data->tax) / 100);
            $order_total =  $initial_quote_price  + $vat_value;
            $order_total = $order_total - $applied_discount_amount;
        } else {
            // $vat_value     = ($product_data->tax/100)*$initial_quote_price;
            $vat_value    = (($initial_quote_price * $product_data->tax) / 100);
            $order_total  =  $initial_quote_price  + $vat_value;
        }
        // Adding tax in maximum tank price for stripe pre authorization
        $maximum_tank_tax = ($product_data->tax/100) * $maximum_tank_price;
        $address = Address::where('id',$billing_address_id)->first();
        if($request->has('payment_option') && $request->input('payment_option') == 'Credit Card'){
            $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');
            $elav_order_total = round($order_total,2);
            $elav_order_total = $order_total * 100;
            
            $ch = curl_init();
            $header = array();
            // echo gettype($elav_order_total); die;
            $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');
            $ts_typ = $product_attribiute_id == "fill the tank" ? 'Deferred' : 'Payment';
            $payment_payload = json_encode( array(
                "transactionType"=> $ts_typ,
                "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,
                "billingAddress"=>array("address1"=>$address->address_1,"postalCode"=>$address->zip,"city"=> $address->town,"country"=> 'IE'),
                "entryMethod"=> "Ecommerce",
                "apply3DSecure"=> "Force",
                "strongCustomerAuthentication"=>array("notificationURL"=> route('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);
            \Log::info(print_r($serialized_result,true));
            if(isset($serialized_result->status) && $serialized_result->status == '3DAuth'){
                $transData = [];
                $transData['paReq'] = $serialized_result->cReq;
                $transData['acsUrl'] = $serialized_result->acsUrl;
                $transData['ref'] = $serialized_result->transactionId;
                $transData['url'] = route('threed.secure');
                $transData['threeCode'] = base64_encode(rand());
                return view('auth.threedsecure',$transData);
            }else if(isset($serialized_result->status) && $serialized_result->status == 'Ok'){
                $obj = new Order();
                $obj->reference = $this->random_string(32);
                $obj->courier_id = 1;
                $obj->customer_id = $customer_data->id;
                $obj->address_id = $billing_address_id;
                if ($serialized_result->status == 'Ok') {
                $obj->order_status_id = 1; # on-delivery
                } else {
                $obj->order_status_id = 3;
                } # error
                $obj->payment              = $request->has('payment_option') ? $request->input('payment_option') :'Credit Card';
                // $obj->total             = $initial_quote_price;
                $obj->total                = $order_total;
                $obj->total_paid           = $order_total;
                // for admin order
                $obj->total_products       = $initial_quote_price;
                // For discount
                $obj->discount_coupon_code = $applied_discount_code;
                $obj->discount_coupon_type = $applied_discount_code_type;
                $obj->discount_value       = $applied_discount_value;
                $obj->discounts            = isset($applied_discount_amount) ? $applied_discount_amount: 0;
                $obj->discount_amount      = isset($applied_discount_amount) ? $applied_discount_amount: 0;
                $obj->billing_address_id   = $billing_address_id;
                $obj->delivery_address_id  = $delivery_address_id;
                $obj->order_county_id      = $county_id;
                $obj->order_town_id        = $town_id;
                // $obj->initial_price        = $initial_quote_price;
                // Initially we pre authorizing all arders for maximum tank parice and storing it in this column
                $obj->initial_price    = $maximum_tank_price;
                if($product_attribiute_id =="fill the tank"){ $obj->fill_the_tank_status = 1; }
                $obj->transaction_id       = $serialized_result->transactionId;
                $obj->stripe_customer_id   = '';
                $obj->transaction_status   = (isset($serialized_result->transactionType) && $serialized_result->transactionType != '') ? 'requires_confirmation' : 'other_payment';
                $obj->delivery_date        = $delivery_date;
                $obj->delivery_note        = $delivery_notes;
                $obj->oil_type_order       = 1;
                $obj->created_at           = date("Y-m-d H:i:s");
                // For tax
                $obj->tax_percentage = $product_data->tax;
                $obj->tax = $vat_value;
                $obj->tax_value = $vat_value;
                $obj->payment_option = $request->has('payment_option') ? $request->input('payment_option') :'Credit Card';
                $obj->save();
                $order_id = $obj->id;
                
            }
        }else{
            $obj = new Order();
                $obj->reference = $this->random_string(32);
                $obj->courier_id = 1;
                $obj->customer_id = $customer_data->id;
                $obj->address_id = $billing_address_id;
                $obj->order_status_id = 2;
                $obj->payment              = $request->has('payment_option') ? $request->input('payment_option') :'Credit Card';
                // $obj->total             = $initial_quote_price;
                $obj->total                = $order_total;
                $obj->total_paid           = $order_total;
                // for admin order
                $obj->total_products       = $initial_quote_price;
                // For discount
                $obj->discount_coupon_code = $applied_discount_code;
                $obj->discount_coupon_type = $applied_discount_code_type;
                $obj->discount_value       = $applied_discount_value;
                $obj->discounts            = isset($applied_discount_amount) ? $applied_discount_amount: 0;
                $obj->discount_amount      = isset($applied_discount_amount) ? $applied_discount_amount: 0;
                $obj->billing_address_id   = $billing_address_id;
                $obj->delivery_address_id  = $delivery_address_id;
                $obj->order_county_id      = $county_id;
                $obj->order_town_id        = $town_id;
                // $obj->initial_price        = $initial_quote_price;
                // Initially we pre authorizing all arders for maximum tank parice and storing it in this column
                $obj->initial_price    = $maximum_tank_price;
                if($product_attribiute_id =="fill the tank"){ $obj->fill_the_tank_status = 1; }
                $obj->transaction_id       = '';
                $obj->stripe_customer_id   = '';
                $obj->transaction_status   = (isset($serialized_result->transactionType) && $serialized_result->transactionType != '') ? $serialized_result['status'] : 'other_payment';
                $obj->delivery_date        = $delivery_date;
                $obj->delivery_note        = $delivery_notes;
                $obj->oil_type_order       = 1;
                $obj->created_at           = date("Y-m-d H:i:s");
                // For tax
                $obj->tax_percentage = $product_data->tax;
                $obj->tax = $vat_value;
                $obj->tax_value = $vat_value;
                $obj->payment_option = $request->has('payment_option') ? $request->input('payment_option') :'Credit Card';
                $obj->save();
                $order_id = $obj->id;
                $serialized_result = new \stdClass();
                $serialized_result->transactionType = 'requires_confirmation';
                $serialized_result->status = 'Ok';
        }
        // Save data to order_product table
            $obj_det = new OrderProduct();
            $obj_det->order_id              =  $order_id;
            $obj_det->product_id            =  $product_id;
            if($product_attribiute_id != "fill the tank"){ $obj_det->product_attribute_id  =  $product_attribiute_id; }
            if($quantity != "fill the tank"){ $obj_det->quantity  =  $quantity; }else{
            $fill_tank_data = FillTank::find(1);
            $obj_det->quantity = $fill_tank_data->quantity;
            }
            $obj_det->product_name          =  $product_session_data->name;
            $obj_det->product_sku           =  $product_session_data->sku;
            $obj_det->product_description   =  $product_session_data->description;
            $obj_det->product_price         =  $initial_quote_price;
            $obj_det->save();

               

           

            

            // Save to order table if status == 'is_succeeded'
            
            // Deleting the session key
            Session::forget('county_name_quote');
            Session::forget('town_name_quote');
            Session::forget('county_name_quote');
            Session::forget('quantity_name_quote');
            Session::forget('session_billing_address_id');
            Session::forget('session_delivery_address_id');
            //Session::forget('session_delivery_date');
            Session::forget('session_delivery_notes');
            Session::forget('applied_discount_code');
            Session::forget('applied_discount_amount');
            Session::forget('applied_discount_code_type');
            Session::forget('applied_discount_value');
            Session::forget('session_order_id');
            $employee = Employee::find(1);
            $data['emailFrom'] = \Config::get('values.MAIL_FROM');
            // Storing session for success or failed page
            if ($serialized_result->status == 'Ok') {
                $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();
                    }
                }
                session([ 'session_success_page' => 1 ]);
                // try {
                //     //  \Mail::to($customer_data)->send(new SendOrderToCustomerMailable($obj));
                //      \Mail::to(config('constants.ADMIN_EMAIL'))->send(new sendEmailNotificationToAdminMailable($obj));
                //  }
                //  catch(Exception $e) {
                //      \Log::info('Message: ' .$e->getMessage());
                //  }
                return redirect()->route('quoues.checkout.success');
            } else {
                session([ 'session_failed_page' => 1,'message'=>$serialized_result->statusDetail  ]);
                return redirect()->route('quoues.checkout.failed');
            }        
    }else{
        $orderId = session()->get('session_order_id');
        $orderDetails = Order::find($orderId);
        $orderProduct = OrderProduct::where(['order_id' => $orderId])->first();
        $productDetails = Product::find($orderProduct->product_id);
        $customer_data = Customer::find(Auth::id());
        $billing_address_id = $orderDetails->address_id;
        $trans_type = $orderDetails->fill_the_tank_status == '1' ? 'Deferred' : 'Payment';
        if($orderDetails->payment_option == 'Credit Card'){
            $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');
            
                //$elav_order_total = round($orderDetails->total,2)*100;
                $order_total = round($orderDetails->total,2);
                $elav_order_total = $order_total * 100;
                $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');
                $address = Address::where('id',$billing_address_id)->first();
                $payment_payload = json_encode( array(
                    "transactionType"=> $trans_type,
                    "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,
                    "billingAddress"=>array("address1"=>$address->address_1,"postalCode"=>$address->zip,"city"=> $address->town,"country"=> 'IE'),
                    "entryMethod"=> "Ecommerce",
                    "strongCustomerAuthentication"=>array("notificationURL"=> route('confirm.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);   
                \Log::info(print_r($serialized_result,true));
                    //dd($serialized_result);
                if(isset($serialized_result->status) && $serialized_result->status == '3DAuth'){
                    $transData = [];
                    $transData['paReq'] = $serialized_result->cReq;
                    $transData['acsUrl'] = $serialized_result->acsUrl;
                    $transData['ref'] = $serialized_result->transactionId;
                    $transData['url'] = route('confirm.threed.secure');
                    return view('auth.threedsecure',$transData);
                }else if(isset($serialized_result->status) && $serialized_result->status == 'Ok'){
                    $orderDetails->order_status_id = 1;     # on-delivery
                    $orderDetails->transaction_id       = $serialized_result->transactionId;
                    $orderDetails->stripe_customer_id   = null;
                    $orderDetails->transaction_status   = ($serialized_result->transactionType) ? $serialized_result->transactionType : null;
                    $orderDetails->delivery_date   = date("Y-m-d");
                }else{
                    $orderDetails->order_status_id = 3; # error
                //         //$orderDetails->transaction_id         = $serialized_result->transactionId;
                //         //$orderDetails->stripe_customer_id   = null;
                         $orderDetails->transaction_status   = ($serialized_result->status) ? $serialized_result->status : null;
                         $orderDetails->delivery_date   = date("Y-m-d");
                }
                
                //if ($serialized_result['status'] == 'requires_payment_method' || $serialized_result['status'] == 'requires_confirmation') {
                // try{
                //     if ($serialized_result->status == 'Ok') {
                //         $orderDetails->order_status_id = 2;     # on-delivery
                //         $orderDetails->transaction_id       = $serialized_result->transactionId;
                //         $orderDetails->stripe_customer_id   = null;
                //         $orderDetails->transaction_status   = ($serialized_result->transactionType) ? $serialized_result->transactionType : null;
                //         $orderDetails->delivery_date   = date("Y-m-d");
                //     } else {
                //         $orderDetails->order_status_id = 3; # error
                //         //$orderDetails->transaction_id         = $serialized_result->transactionId;
                //         //$orderDetails->stripe_customer_id   = null;
                //         $orderDetails->transaction_status   = ($serialized_result->status) ? $serialized_result->status : null;
                //         $orderDetails->delivery_date   = date("Y-m-d");
                //     }
                // }
                // catch(Exception $e) {
                //      \Log::info('Message: ' .$e->getMessage());
                //     session([ 'session_failed_page' => 1,'message'=>$serialized_result->statusDetail ]);
                //     return redirect()->route('quoues.checkout.failed');
                // }
                
                /*$orderDetails->transaction_id         = $serialized_result['id'];
                $orderDetails->stripe_customer_id   = $serialized_result['customer'];
                $orderDetails->transaction_status   = $serialized_result['status'];*/
                
                $orderDetails->save();
        }else{
            $orderDetails->order_status_id = 2;
            $orderDetails->transaction_id       = '';
            $orderDetails->stripe_customer_id   = '';
            $orderDetails->transaction_status   = '';
            $orderDetails->delivery_date   = date("Y-m-d");
            $orderDetails->save();
            $serialized_result = NULL;
            $serialized_result->transactionType = 'requires_confirmation';
            $serialized_result->status = 'Ok';
        }
        Session::forget('county_name_quote');
        Session::forget('town_name_quote');
        Session::forget('county_name_quote');
        Session::forget('quantity_name_quote');
        Session::forget('session_billing_address_id');
        Session::forget('session_delivery_address_id');
        //Session::forget('session_delivery_date');
        Session::forget('session_delivery_notes');
        Session::forget('applied_discount_code');
        Session::forget('applied_discount_amount');
        Session::forget('applied_discount_code_type');
        Session::forget('applied_discount_value');
        Session::forget('session_order_id');
        // Storing session for success or failed page
        $employee = Employee::find(1);
        if ($serialized_result->status == 'Ok') {
                // try {
                //     //  \Mail::to($customer_data)->send(new SendOrderToCustomerMailable($orderDetails));
                //      \Mail::to($employee)->send(new sendEmailNotificationToAdminMailable($orderDetails));
                //  }
                //  catch(Exception $e) {
                    
                //  }
                session([ 'session_success_page' => 1 ]);
                Session::flash('message', "Payment successfull!");
                return redirect()->route('quoues.checkout.success');
            } else {
                session([ 'session_failed_page' => 1 ]);
                return redirect()->route('quoues.checkout.failed');
            }
    }
}


// public function submit_payment(Request $request) {
    
//         if (!$request->session()->has('session_order_id')) {
            
//             // Checking the session if not exist then redirect to home page
//             if ($request->session()->has('county_name_quote') && $request->session()->has('session_billing_address_id')) {
//                 $county_id = session()->get('county_name_quote');
//                 $town_id = session()->get('town_name_quote');
//                 $product_id = session()->get('product_name_quote');
//                 $product_attribiute_id = session()->get('quantity_name_quote');
//                 $billing_address_id = session()->get('session_billing_address_id');
//                 $delivery_address_id = session()->get('session_delivery_address_id');
//                 $delivery_date = session()->get('session_delivery_date');
//                 $delivery_notes = session()->get('session_delivery_notes');
//                 // For discount
//                 $applied_discount_code = session()->get('applied_discount_code');
//                 $applied_discount_amount = session()->get('applied_discount_amount');
//                 $applied_discount_code_type = session()->get('applied_discount_code_type');
//                 $applied_discount_value = session()->get('applied_discount_value');
//                 $today_date = date('Y-m-d');
//                 $del_date = strtr($delivery_date, '/', '-');
//                 $date1=date_create($today_date);
//                 $delivery_date = date("Y-m-d", strtotime($del_date)); 
//                 $date2=date_create($delivery_date);
                
//                 $diff=date_diff($date1,$date2);
               
//                 session()->put('session_delivery_date',$delivery_date);
//             } else {
//                 return redirect()->route('home');
//             }
//             $customer_data = Customer::find(Auth::id());
            
//             // Fetching necessary data for payment
//             // Fetching price
//             if ($product_attribiute_id =="fill the tank") {
//                 $initial_quote_price = $this->fill_the_tank_price();
//             } else {
//                 $initial_quote_price  = $this->home_controller->get_initial_price($product_attribiute_id);
//             }
//             // Fetching quantity
//             if ($product_attribiute_id == "fill the tank") {
//                 $quantity = "fill the tank";
//             } else {
//                 $quantity = $this->get_quantity($product_attribiute_id);
//             }
//             // Fetching the productdata that is in session
//             $product_session_data = Product::find($product_id);
//             $product_id = $product_session_data->id;
//             $product_name = "Product Name: ".$product_session_data->name;
//             // If order is not fill the tank option we are initially capturing maximum tank price but will reset after setting the quantity at time of delivery
//             $maximum_tank_price = $this->fill_the_tank_price();
//             // VAT and Order Total Calculation
//             $product_data = Product::find($product_id);
//             // If some discount is available, deduct that amount from total
//             if ($applied_discount_code != '' && $applied_discount_amount != '') {
//                 // $vat_value = ( ( $product_data->tax / 100 ) * ( $initial_quote_price - $applied_discount_amount ) );
//                 $vat_value = (($initial_quote_price * $product_data->tax) / 100);
//                 $order_total =  $initial_quote_price  + $vat_value;
//                 $order_total = $order_total - $applied_discount_amount;
//             } else {
//                 // $vat_value     = ($product_data->tax/100)*$initial_quote_price;
//                 $vat_value    = (($initial_quote_price * $product_data->tax) / 100);
//                 $order_total  =  $initial_quote_price  + $vat_value;
//             }
//             // Adding tax in maximum tank price for stripe pre authorization
//             $maximum_tank_tax = ($product_data->tax/100) * $maximum_tank_price;
//             $address = Address::where('id',$billing_address_id)->first();
//             if($request->has('payment_option') && $request->input('payment_option') == 'Credit Card'){
//                 $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');
//           $elav_order_total = round($order_total,2);
//           $elav_order_total = $order_total * 100;
           
//             $ch = curl_init();
//             $header = array();
//           // echo gettype($elav_order_total); die;
//             $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');
//                 $ts_typ = $product_attribiute_id == "fill the tank" ? 'Deferred' : 'Payment';
//                 $payment_payload = json_encode( array(
//                     "transactionType"=> $ts_typ,
//                     "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,
//                     "billingAddress"=>array("address1"=>$address->address_1,"postalCode"=>$address->zip,"city"=> $address->town,"country"=> 'IE'),
//                     "entryMethod"=> "Ecommerce"
//                 ));
//                 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);
//                 \Log::info(print_r($serialized_result,true));
//                 $obj = new Order();
//                 $obj->reference = $this->random_string(32);
//                 $obj->courier_id = 1;
//                 $obj->customer_id = $customer_data->id;
//                 $obj->address_id = $billing_address_id;
//                 if ($serialized_result->status == 'Ok') {
//                 $obj->order_status_id = 2; # on-delivery
//                 } else {
//                 $obj->order_status_id = 3;
//                 } # error
//                 $obj->payment              = $request->has('payment_option') ? $request->input('payment_option') :'Credit Card';
//                 // $obj->total             = $initial_quote_price;
//                 $obj->total                = $order_total;
//                 $obj->total_paid           = $order_total;
//                 // for admin order
//                 $obj->total_products       = $initial_quote_price;
//                 // For discount
//                 $obj->discount_coupon_code = $applied_discount_code;
//                 $obj->discount_coupon_type = $applied_discount_code_type;
//                 $obj->discount_value       = $applied_discount_value;
//                 $obj->discounts            = isset($applied_discount_amount) ? $applied_discount_amount: 0;
//                 $obj->discount_amount      = isset($applied_discount_amount) ? $applied_discount_amount: 0;
//                 $obj->billing_address_id   = $billing_address_id;
//                 $obj->delivery_address_id  = $delivery_address_id;
//                 $obj->order_county_id      = $county_id;
//                 $obj->order_town_id        = $town_id;
//                 // $obj->initial_price        = $initial_quote_price;
//                 // Initially we pre authorizing all arders for maximum tank parice and storing it in this column
//                 $obj->initial_price    = $maximum_tank_price;
//                 if($product_attribiute_id =="fill the tank"){ $obj->fill_the_tank_status = 1; }
//                 $obj->transaction_id       = $serialized_result->transactionId;
//                 $obj->stripe_customer_id   = '';
//                 $obj->transaction_status   = (isset($serialized_result->transactionType) && $serialized_result->transactionType != '') ? 'requires_confirmation' : 'other_payment';
//                 $obj->delivery_date        = $delivery_date;
//                 $obj->delivery_note        = $delivery_notes;
//                 $obj->oil_type_order       = 1;
//                 $obj->created_at           = date("Y-m-d H:i:s");
//                 // For tax
//                 $obj->tax_percentage = $product_data->tax;
//                 $obj->tax = $vat_value;
//                 $obj->tax_value = $vat_value;
//                 $obj->payment_option = $request->has('payment_option') ? $request->input('payment_option') :'Credit Card';
//                 $obj->save();
//                 $order_id = $obj->id;
                    
//             }else{
//                 $obj = new Order();
//                 $obj->reference = $this->random_string(32);
//                 $obj->courier_id = 1;
//                 $obj->customer_id = $customer_data->id;
//                 $obj->address_id = $billing_address_id;
//                 $obj->order_status_id = 2;
//                 $obj->payment              = $request->has('payment_option') ? $request->input('payment_option') :'Credit Card';
//                 // $obj->total             = $initial_quote_price;
//                 $obj->total                = $order_total;
//                 $obj->total_paid           = $order_total;
//                 // for admin order
//                 $obj->total_products       = $initial_quote_price;
//                 // For discount
//                 $obj->discount_coupon_code = $applied_discount_code;
//                 $obj->discount_coupon_type = $applied_discount_code_type;
//                 $obj->discount_value       = $applied_discount_value;
//                 $obj->discounts            = isset($applied_discount_amount) ? $applied_discount_amount: 0;
//                 $obj->discount_amount      = isset($applied_discount_amount) ? $applied_discount_amount: 0;
//                 $obj->billing_address_id   = $billing_address_id;
//                 $obj->delivery_address_id  = $delivery_address_id;
//                 $obj->order_county_id      = $county_id;
//                 $obj->order_town_id        = $town_id;
//                 // $obj->initial_price        = $initial_quote_price;
//                 // Initially we pre authorizing all arders for maximum tank parice and storing it in this column
//                 $obj->initial_price    = $maximum_tank_price;
//                 if($product_attribiute_id =="fill the tank"){ $obj->fill_the_tank_status = 1; }
//                 $obj->transaction_id       = '';
//                 $obj->stripe_customer_id   = '';
//                 $obj->transaction_status   = (isset($serialized_result->transactionType) && $serialized_result->transactionType != '') ? $serialized_result['status'] : 'other_payment';
//                 $obj->delivery_date        = $delivery_date;
//                 $obj->delivery_note        = $delivery_notes;
//                 $obj->oil_type_order       = 1;
//                 $obj->created_at           = date("Y-m-d H:i:s");
//                 // For tax
//                 $obj->tax_percentage = $product_data->tax;
//                 $obj->tax = $vat_value;
//                 $obj->tax_value = $vat_value;
//                 $obj->payment_option = $request->has('payment_option') ? $request->input('payment_option') :'Credit Card';
//                 $obj->save();
//                 $order_id = $obj->id;
//                 $serialized_result = new \stdClass();
//                 $serialized_result->transactionType = 'requires_confirmation';
//               // $serialized_result->transactionType = 'requires_confirmation';        
//             }
//             // Save data to order_product table
//             $obj_det = new OrderProduct();
//             $obj_det->order_id              =  $order_id;
//             $obj_det->product_id            =  $product_id;
//             if($product_attribiute_id != "fill the tank"){ $obj_det->product_attribute_id  =  $product_attribiute_id; }
//             if($quantity != "fill the tank"){ $obj_det->quantity  =  $quantity; }else{
//             $fill_tank_data = FillTank::find(1);
//             $obj_det->quantity = $fill_tank_data->quantity;
//             }
//             $obj_det->product_name          =  $product_session_data->name;
//             $obj_det->product_sku           =  $product_session_data->sku;
//             $obj_det->product_description   =  $product_session_data->description;
//             $obj_det->product_price         =  $initial_quote_price;
//             $obj_det->save();

               

           

            

//             // Save to order table if status == 'is_succeeded'
            
//             // Deleting the session key
//             Session::forget('county_name_quote');
//             Session::forget('town_name_quote');
//             Session::forget('county_name_quote');
//             Session::forget('quantity_name_quote');
//             Session::forget('session_billing_address_id');
//             Session::forget('session_delivery_address_id');
//             //Session::forget('session_delivery_date');
//             Session::forget('session_delivery_notes');
//             Session::forget('applied_discount_code');
//             Session::forget('applied_discount_amount');
//             Session::forget('applied_discount_code_type');
//             Session::forget('applied_discount_value');
//             Session::forget('session_order_id');
//             $employee = Employee::find(1);
//             $data['emailFrom'] = \Config::get('values.MAIL_FROM');
//             // Storing session for success or failed page
//             if ($serialized_result->status == 'Ok') {
//                 $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();
//                     }
//                 }
//                 session([ 'session_success_page' => 1 ]);
//                 // try {
//                 //     //  \Mail::to($customer_data)->send(new SendOrderToCustomerMailable($obj));
//                 //      \Mail::to(config('constants.ADMIN_EMAIL'))->send(new sendEmailNotificationToAdminMailable($obj));
//                 //  }
//                 //  catch(Exception $e) {
//                 //      \Log::info('Message: ' .$e->getMessage());
//                 //  }
//                 return redirect()->route('quoues.checkout.success');
//             } else {
//                 session([ 'session_failed_page' => 1,'message'=>$serialized_result->statusDetail  ]);
//                 return redirect()->route('quoues.checkout.failed');
//             }
//         } else {
//             $orderId = session()->get('session_order_id');
//             $orderDetails = Order::find($orderId);
//             $orderProduct = OrderProduct::where(['order_id' => $orderId])->first();
//             $productDetails = Product::find($orderProduct->product_id);
//             $customer_data = Customer::find(Auth::id());
//             $billing_address_id = $orderDetails->address_id;
//             $trans_type = $orderDetails->fill_the_tank_status == '1' ? 'Deferred' : 'Payment';
//             if($orderDetails->payment_option == 'Credit Card'){
//                 $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');
            
//                 //$elav_order_total = round($orderDetails->total,2)*100;
//                 $order_total = round($orderDetails->total,2);
//                 $elav_order_total = $order_total * 100;
//                 $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');
//                 $address = Address::where('id',$billing_address_id)->first();
//                 $payment_payload = json_encode( array(
//                     "transactionType"=> $trans_type,
//                     "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,
//                     "billingAddress"=>array("address1"=>$address->address_1,"postalCode"=>$address->zip,"city"=> $address->town,"country"=> 'IE'),
//                     "entryMethod"=> "Ecommerce",
//                     "apply3DSecure"=> "Disable",
                   
//                 ));
//                 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);   
// //dd($serialized_result);
                
                
//                 //if ($serialized_result['status'] == 'requires_payment_method' || $serialized_result['status'] == 'requires_confirmation') {
//                 try{
//                     if ($serialized_result->status == 'Ok') {
//                         $orderDetails->order_status_id = 2;     # on-delivery
//                         $orderDetails->transaction_id       = $serialized_result->transactionId;
//                         $orderDetails->stripe_customer_id   = null;
//                         $orderDetails->transaction_status   = ($serialized_result->transactionType) ? $serialized_result->transactionType : null;
//                         $orderDetails->delivery_date   = date("Y-m-d");
//                     } else {
//                         $orderDetails->order_status_id = 3; # error
//                         //$orderDetails->transaction_id         = $serialized_result->transactionId;
//                         //$orderDetails->stripe_customer_id   = null;
//                         $orderDetails->transaction_status   = ($serialized_result->status) ? $serialized_result->status : null;
//                         $orderDetails->delivery_date   = date("Y-m-d");
//                     }
//                 }
//                 catch(Exception $e) {
//                      \Log::info('Message: ' .$e->getMessage());
//                     session([ 'session_failed_page' => 1,'message'=>$serialized_result->statusDetail ]);
//                     return redirect()->route('quoues.checkout.failed');
//                 }
                
//                 /*$orderDetails->transaction_id         = $serialized_result['id'];
//                 $orderDetails->stripe_customer_id   = $serialized_result['customer'];
//                 $orderDetails->transaction_status   = $serialized_result['status'];*/
                
//                 $orderDetails->save();

//             }else{
//                 $orderDetails->order_status_id = 2;
//                 $orderDetails->transaction_id       = '';
//                 $orderDetails->stripe_customer_id   = '';
//                 $orderDetails->transaction_status   = '';
//                 $orderDetails->delivery_date   = date("Y-m-d");
//                 $orderDetails->save();
//                 $serialized_result = NULL;
//                 $serialized_result->transactionType = 'requires_confirmation';
//             }
            
             

            
//             // Deleting the session key
//             Session::forget('county_name_quote');
//             Session::forget('town_name_quote');
//             Session::forget('county_name_quote');
//             Session::forget('quantity_name_quote');
//             Session::forget('session_billing_address_id');
//             Session::forget('session_delivery_address_id');
//             //Session::forget('session_delivery_date');
//             Session::forget('session_delivery_notes');
//             Session::forget('applied_discount_code');
//             Session::forget('applied_discount_amount');
//             Session::forget('applied_discount_code_type');
//             Session::forget('applied_discount_value');
//             Session::forget('session_order_id');
//             // Storing session for success or failed page
//             $employee = Employee::find(1);
//             if ($serialized_result->transactionType == 'requires_payment_method' || $serialized_result->transactionType == 'requires_confirmation' || $serialized_result->transactionType == 'Deferred' || $serialized_result->transactionType == 'Payment') {
//                 // try {
//                 //     //  \Mail::to($customer_data)->send(new SendOrderToCustomerMailable($orderDetails));
//                 //      \Mail::to($employee)->send(new sendEmailNotificationToAdminMailable($orderDetails));
//                 //  }
//                 //  catch(Exception $e) {
                    
//                 //  }
//                 session([ 'session_success_page' => 1 ]);
//                 Session::flash('message', "Payment successfull!");
//                 return redirect()->route('quoues.checkout.success');
//             } else {
//                 session([ 'session_failed_page' => 1 ]);
//                 return redirect()->route('quoues.checkout.failed');
//             }
//         }
//     }

    public function addCustomer($customerDetailsAry) {
        $customer = new Stripe_customer();
        $customerDetails = $customer->create($customerDetailsAry);
        return $customerDetails;
    }

    public function random_string($n) { 
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; 
        $randomString = '';
        for ($i = 0; $i < $n; $i++) { 
            $index = rand(0, strlen($characters) - 1); 
            $randomString .= $characters[$index]; 
        } 
        return $randomString; 
    } 

    public function success(Request $request) {
        // Checking the session if not exist then redirect to home page

        if ($request->session()->has('session_success_page')) {
            Session::forget('session_success_page');
            $delivery_date  = session()->get('session_delivery_date');
            $messages = DB::table('messages')->first();
        
            return view('front.quote.success',['delivery_date'=>$delivery_date,'messages'=>$messages]);
        } else {
            return redirect()->route('home');
        }
    }

    public function failed() {
        // Checking the session if not exist then redirect to home page
        Session::forget('session_failed_page');
        if(Session::has('message')){
            $message = session()->get('message');    
        }
        else{
            $message = '';
        }
        Session::forget('message');
        $data['message'] = $message;
        return view('front.quote.failed');
    }

    public function fill_the_tank_price() {
        $fill_tank_data = FillTank::find(1);
        if (!empty($fill_tank_data->price)) {
            return $fill_tank_data->price;
        }
    }
    
    public function handlePaymentSubmission(Request $request){
       \Log::info(print_r($request->all(),true));
        $pares = $request->input('cres');
        $transaction_id = $request->input('threeDSSessionData');
        $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');
         $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/".$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'){
            $county_id = session()->get('county_name_quote');
			$town_id = session()->get('town_name_quote');
			$product_id = session()->get('product_name_quote');
			$product_attribiute_id = session()->get('quantity_name_quote');
			$billing_address_id = session()->get('session_billing_address_id');
			$delivery_address_id = session()->get('session_delivery_address_id');
			$delivery_date = session()->get('session_delivery_date');
			$delivery_notes = session()->get('session_delivery_notes');
			// For discount
			$applied_discount_code = session()->get('applied_discount_code');
			$applied_discount_amount = session()->get('applied_discount_amount');
			$applied_discount_code_type = session()->get('applied_discount_code_type');
			$applied_discount_value = session()->get('applied_discount_value');
			$today_date = date('Y-m-d');
			$del_date = strtr($delivery_date, '/', '-');
			$date1=date_create($today_date);
			$delivery_date = date("Y-m-d", strtotime($del_date)); 
            $date2=date_create($delivery_date);
            
            $diff=date_diff($date1,$date2);
            $customer_data = Customer::find(Auth::id());
            if ($product_attribiute_id =="fill the tank") {
	            $initial_quote_price = $this->fill_the_tank_price();
	        } else {
	            $initial_quote_price  = $this->home_controller->get_initial_price($product_attribiute_id);
	        }
	        // Fetching quantity
	        if ($product_attribiute_id == "fill the tank") {
	        	$quantity = "fill the tank";
	        } else {
	        	$quantity = $this->get_quantity($product_attribiute_id);
	        }
	        // Fetching the productdata that is in session
			$product_session_data = Product::find($product_id);
			$product_id = $product_session_data->id;
			$product_name = "Product Name: ".$product_session_data->name;
			// If order is not fill the tank option we are initially capturing maximum tank price but will reset after setting the quantity at time of delivery
			$maximum_tank_price = $this->fill_the_tank_price();
			// VAT and Order Total Calculation
	        $product_data = Product::find($product_id);
	        // If some discount is available, deduct that amount from total
	        if ($applied_discount_code != '' && $applied_discount_amount != '') {
	        	// $vat_value = ( ( $product_data->tax / 100 ) * ( $initial_quote_price - $applied_discount_amount ) );
	        	$vat_value = (($initial_quote_price * $product_data->tax) / 100);
	        	$order_total =  $initial_quote_price  + $vat_value;
	        	$order_total = $order_total - $applied_discount_amount;
	        } else {
	        	// $vat_value 	  = ($product_data->tax/100)*$initial_quote_price;
	        	$vat_value 	  = (($initial_quote_price * $product_data->tax) / 100);
	        	$order_total  =  $initial_quote_price  + $vat_value;
	        }
		    // Adding tax in maximum tank price for stripe pre authorization
		    $maximum_tank_tax = ($product_data->tax/100) * $maximum_tank_price;
		    $address = Address::where('id',$billing_address_id)->first();
            $obj = new Order();
			$obj->reference = $this->random_string(32);
			$obj->courier_id = 1;
			$obj->customer_id = $customer_data->id;
			$obj->address_id = $billing_address_id;
			$obj->order_status_id = 1;
			$obj->payment         	   = 'Credit Card';
			// $obj->total 		  	   = $initial_quote_price;
			$obj->total 		  	   = $order_total;
			$obj->total_paid 	  	   = $order_total;
			// for admin order
			$obj->total_products 	   = $initial_quote_price;
			// For discount
			$obj->discount_coupon_code = $applied_discount_code;
			$obj->discount_coupon_type = $applied_discount_code_type;
			$obj->discount_value 	   = $applied_discount_value;
			$obj->discounts 	   	   = isset($applied_discount_amount) ? $applied_discount_amount: 0;
			$obj->discount_amount 	   = isset($applied_discount_amount) ? $applied_discount_amount: 0;
			$obj->billing_address_id   = $billing_address_id;
			$obj->delivery_address_id  = $delivery_address_id;
			$obj->order_county_id      = $county_id;
			$obj->order_town_id  	   = $town_id;
			// $obj->initial_price        = $initial_quote_price;
			// Initially we pre authorizing all arders for maximum tank parice and storing it in this column
			$obj->initial_price    = $maximum_tank_price;
			if($product_attribiute_id =="fill the tank"){ $obj->fill_the_tank_status = 1; }
			$obj->transaction_id       = $transaction_id;
			$obj->stripe_customer_id   = '';
			$obj->transaction_status   = ($product_attribiute_id =="fill the tank") ? 'requires_confirmation' : 'succeeded';
			$obj->delivery_date        = $delivery_date;
			$obj->delivery_note        = $delivery_notes;
			$obj->oil_type_order       = 1;
			$obj->created_at           = date("Y-m-d H:i:s");
			// For tax
			$obj->tax_percentage = $product_data->tax;
			$obj->tax = $vat_value;
			$obj->tax_value = $vat_value;
			$obj->payment_option = 'Credit Card';
			$obj->save();
			$order_id = $obj->id;
			$obj_det = new OrderProduct();
			$obj_det->order_id  			=  $order_id;
			$obj_det->product_id            =  $product_id;
			if($product_attribiute_id != "fill the tank"){ $obj_det->product_attribute_id  =  $product_attribiute_id; }
			if($quantity != "fill the tank"){ $obj_det->quantity  =  $quantity; }else{
			$fill_tank_data = FillTank::find(1);
			$obj_det->quantity = $fill_tank_data->quantity;
			}
			$obj_det->product_name          =  $product_session_data->name;
			$obj_det->product_sku          	=  $product_session_data->sku;
			$obj_det->product_description  	=  $product_session_data->description;
			$obj_det->product_price         =  $initial_quote_price;
			$obj_det->save();

	        // Save to order table if status == 'is_succeeded'
	        
		    // Deleting the session key
	        Session::forget('county_name_quote');
	        Session::forget('town_name_quote');
	        Session::forget('county_name_quote');
	        Session::forget('quantity_name_quote');
	        Session::forget('session_billing_address_id');
	        Session::forget('session_delivery_address_id');
	        //Session::forget('session_delivery_date');
	        Session::forget('session_delivery_notes');
	        Session::forget('applied_discount_code');
	        Session::forget('applied_discount_amount');
	        Session::forget('applied_discount_code_type');
	        Session::forget('applied_discount_value');
	        Session::forget('session_order_id');
	        $employee = Employee::find(1);
	        $data['emailFrom'] = \Config::get('values.MAIL_FROM');
		   	// Storing session for success or failed page
	        
	            $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();
	                }
	            }
	        	session([ 'session_success_page' => 1 ]);
        		try {
                    //  \Mail::to($customer_data)->send(new SendOrderToCustomerMailable($obj));
                     //\Mail::to(config('constants.ADMIN_EMAIL'))->send(new sendEmailNotificationToAdminMailable($obj));
                 }
                 catch(Exception $e) {
                     \Log::info('Message: ' .$e->getMessage());
                 }
	        	return redirect()->route('quoues.checkout.success');
	        

        }
        else{
            session([ 'session_failed_page' => 1 ]);
        	return redirect()->route('quoues.checkout.failed');
        }
    }
    
    public function confirmPaymentSubmission(Request $request){
        $pares = $request->input('cres');
        $transaction_id = $request->input('threeDSSessionData');
        $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');
         $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/".$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);
        if(isset($serialized_result->status) && $serialized_result->status == 'Ok'){
            $orderId = session()->get('session_order_id');
            $orderDetails = Order::find($orderId);
            $orderProduct = OrderProduct::where(['order_id' => $orderId])->first();
            $productDetails = Product::find($orderProduct->product_id);
            $customer_data = Customer::find(Auth::id());
            $billing_address_id = $orderDetails->address_id;
            $trans_type = $orderDetails->fill_the_tank_status == '1' ? 'Deferred' : 'Payment';
            $orderDetails->order_status_id = 1;     # on-delivery
            $orderDetails->transaction_id       = $serialized_result->transactionId;
            $orderDetails->stripe_customer_id   = null;
            $orderDetails->transaction_status   = ($serialized_result->transactionType) ? $serialized_result->transactionType : null;
            $orderDetails->delivery_date   = date("Y-m-d");
            $orderDetails->save();
            Session::forget('county_name_quote');
            Session::forget('town_name_quote');
            Session::forget('county_name_quote');
            Session::forget('quantity_name_quote');
            Session::forget('session_billing_address_id');
            Session::forget('session_delivery_address_id');
            //Session::forget('session_delivery_date');
            Session::forget('session_delivery_notes');
            Session::forget('applied_discount_code');
            Session::forget('applied_discount_amount');
            Session::forget('applied_discount_code_type');
            Session::forget('applied_discount_value');
            Session::forget('session_order_id');
            session([ 'session_success_page' => 1 ]);
            Session::flash('message', "Payment successfull!");
            return redirect()->route('quoues.checkout.success');
        }else{
             session([ 'session_failed_page' => 1 ]);
        	return redirect()->route('quoues.checkout.failed');
        }
    }
}

Spamworldpro Mini