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

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /home/corals/mcoil.corals.io/app/Http/Controllers/Driver/OrderController.php
<?php
namespace App\Http\Controllers\Driver;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Shop\Orders\Order;
use App\Shop\OrderProducts\OrderProduct;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use \Stripe\Stripe;
use \Stripe\Customer as Stripe_customer;
use \Stripe\ApiOperations\Create;
use \Stripe\Charge;
use \Stripe\PaymentIntent;
use App\Shop\FillTanks\FillTank;
use App\Shop\WebsiteSettings\WebsiteSetting;
use Illuminate\Support\Facades\File;
use App\Shop\Products\Product;
use App\Shop\Customers\Customer;
use \Stripe\StripeClient;
use App\Shop\Addresses\Address;

class OrderController extends Controller
{
    private $apiKey;
    private $stripeService;

    public function __construct()
    {
        // $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');
    }

    public function index()
    {
        $todaysDate = date('Y-m-d');
        $orders = DB::table('orders')->leftJoin('customers', 'customers.id', '=', 'orders.customer_id')
            ->leftJoin('order_statuses', 'order_statuses.id', '=', 'orders.order_status_id')
            ->leftJoin('order_product', 'order_product.order_id', '=', 'orders.id')
            ->leftJoin('addresses', 'addresses.id', '=', 'orders.delivery_address_id')
            ->select('orders.id', 'orders.delivery_date', 'orders.fill_the_tank_status', 'orders.total', 'order_statuses.id as status', 'order_statuses.name as order_status_name', 'order_statuses.color', 'customers.name', 'orders.transaction_status', 'orders.delivery_note', 'customers.email', 'order_product.quantity', 'order_product.product_name', 'addresses.address_1', 'addresses.address_2', 'addresses.county', 'addresses.town', 'addresses.zip', 'addresses.phone')
            ->where('orders.oil_type_order', 1)
            ->where('orders.order_status', 0)
            ->where('orders.driver_id', Auth::id())
            ->whereDate('orders.delivery_date', '<=', $todaysDate)->orderBy('id', 'ASC')
            ->get();
        $completed_orders = DB::table('orders')->leftJoin('customers', 'customers.id', '=', 'orders.customer_id')
            ->leftJoin('order_statuses', 'order_statuses.id', '=', 'orders.order_status_id')
            ->leftJoin('order_product', 'order_product.order_id', '=', 'orders.id')
            ->leftJoin('addresses', 'addresses.id', '=', 'orders.delivery_address_id')
            ->select('orders.id', 'orders.delivery_date', 'orders.fill_the_tank_status', 'orders.total', 'order_statuses.name as order_status_name', 'order_statuses.color', 'customers.name', 'orders.transaction_status', 'customers.email', 'order_product.quantity', 'order_product.product_name', 'addresses.address_1', 'addresses.address_2', 'addresses.county', 'addresses.town', 'addresses.zip', 'addresses.phone')
            ->where('orders.oil_type_order', 1)
            ->where('orders.order_status', 1)
            ->where('orders.driver_id', Auth::id())
            ->orderBy('id', 'DESC')
            ->get();
        $produc_order_details = [];
        $products = Product::where('status', '1')->get();
        if (count($products) > 0)
        {
            foreach ($products as $product)
            {
                $fill_in_tank_orders = DB::table('orders')->join('order_product', 'order_product.order_id', '=', 'orders.id')
                    ->where('orders.driver_id', Auth::id())
                    ->whereDate('orders.delivery_date', '<=', $todaysDate)->where('orders.order_status', 0)
                    ->where('orders.fill_the_tank_status', '1')
                    ->where('order_product.product_id', $product->id)
                    ->count();

                $quantity_orders = DB::table('orders')->join('order_product', 'order_product.order_id', '=', 'orders.id')
                    ->where('orders.driver_id', Auth::id())
                    ->whereDate('orders.delivery_date', '<=', $todaysDate)->where('orders.order_status', 0)
                    ->where('fill_the_tank_status', '0')
                    ->where('order_product.product_id', $product->id)
                    ->sum('order_product.quantity');

                $total_quantity = DB::table('orders')->join('order_product', 'order_product.order_id', '=', 'orders.id')
                    ->where('orders.driver_id', Auth::id())
                    ->whereDate('orders.delivery_date', '<=', $todaysDate)->where('orders.order_status', 0)
                    ->where('fill_the_tank_status', '0')
                    ->where('order_product.product_id', $product->id)
                    ->count();
                $fill_tank_data = FillTank::first();

                $total_fill_in_tank_quantity = $fill_in_tank_orders * $fill_tank_data->quantity;

                $total_orders_quantity = $total_fill_in_tank_quantity + $quantity_orders;

                $total_orders = $fill_in_tank_orders + $total_quantity;
                $produc_order_details[$product->id]['name'] = $product->name;
                $produc_order_details[$product->id]['total_quantity'] = $total_orders_quantity;
                $produc_order_details[$product->id]['total_orders'] = $total_orders;
                $produc_order_details[$product->id]['cover'] = $product->cover;
            }
        }

        // echo $fill_in_tank_orders."<br>"; die;
        // echo $quantity_orders."<br>"; die;
        return view('driver.orders.order', ['orders' => $orders, 'completed_orders' => $completed_orders, 'total_quantity' => $total_orders_quantity, 'total_orders' => $total_orders, 'produc_order_details' => $produc_order_details]);
    }

    public function show_payment(Request $request, $orderId)
    {
       
        // Get the logged-in driver id
        $driverId = Auth::id();

        $order_data = DB::table('orders')->leftJoin('customers', 'customers.id', '=', 'orders.customer_id')
            ->leftJoin('order_product', 'order_product.order_id', '=', 'orders.id')
            ->leftJoin('addresses', 'addresses.id', '=', 'orders.delivery_address_id')
            ->leftJoin('products', 'products.id', '=', 'order_product.product_id')
            ->where('orders.id', $orderId)->select('orders.id','orders.order_status', 'orders.fill_the_tank_status', 'orders.total', 'orders.tax_percentage', 'orders.tax_value', 'orders.total_paid', 'orders.initial_price', 'orders.transaction_status', 'orders.delivery_date', 'orders.delivery_note', 'customers.name', 'customers.email', 'order_product.quantity', 'order_product.product_name', 'order_product.product_id', 'addresses.address_1', 'addresses.address_2', 'addresses.county', 'addresses.town', 'addresses.zip', 'addresses.phone', 'orders.discount_coupon_code', 'orders.discount_amount', 'orders.discount_coupon_type', 'orders.discount_value', 'orders.discounts', 'orders.total_products', 'orders.driver_id', 'orders.payment_option', 'orders.order_status_id', 'products.cover')
            ->first();

        if ($order_data)
        {
            if ($order_data->fill_the_tank_status == "1")
            {
                $fill_tank_data = FillTank::find(1);
                if (!empty($fill_tank_data->quantity))
                {
                    $maxQty = $fill_tank_data->quantity;
                }
                else
                {
                    $maxQty = 0;
                }
            }
            else
            {
                $maxQty = $order_data->quantity;
            }

            if ($driverId == $order_data->driver_id)
            {
                $elavon_user_name = config('elavon.key');
                $elavon_user_password = config('elavon.secret');

                $base_inc = base64_encode($elavon_user_name . ':' . $elavon_user_password);
                $vendor_name = config('elavon.vendorName');

                $ch = curl_init();
                $header = array();

                $header[] = 'Content-type: application/json';
                $header[] = 'Authorization: Basic ' . $base_inc;
                $payload = json_encode(array(
                    "vendorName" => $vendor_name
                ));

                curl_setopt($ch, CURLOPT_URL, $this->elavonUrl."/api/v1/merchant-session-keys");
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
                //curl_setopt($ch, CURLOPT_POSTFIELDS,"vendorName=Juvotest");
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                $server_output = curl_exec($ch);
                $out = json_decode($server_output);

                $merchantSessionKey = $out->merchantSessionKey;
                return view('driver.orders.payment', ['order_data' => $order_data, 'merchantSessionKey' => $merchantSessionKey, 'maxQty' => $maxQty]);
            }
            else
            {
                return redirect('driver/orders?tab=pending-orders')->with('error', 'You are not authorize to access this order.');
            }
        }
        else
        {
            return redirect('driver/orders?tab=pending-orders')
                ->with('error', 'Invalid order.');
        }
    }

    // public function receive_payment(Request $request) {
    //   $fill_the_tank_quantity = $request->fill_the_tank_quantity;
    //     $fill_the_tank_price = $request->fill_the_tank_amount;
    //     $fill_the_tank_tax_value = $request->fill_the_tank_tax_value;
    //     $fill_the_tank_final_amount = $request->fill_the_tank_final_amount;
    //     // Updated discount amount
    //     $discount_amount = $request->discount_amount;
    //   $subTotal = ( $fill_the_tank_final_amount - ( $fill_the_tank_tax_value - $request->discount_amount ) );
    //     if($request->token){
    //         $orderId = $request->order_id;
    //         $orderDetails = Order::find($orderId);
    //         $orderProduct = OrderProduct::where(['order_id' => $orderId])->first();
    //         $productDetails = Product::find($orderProduct->product_id);
    //         $customer_data = Customer::find($orderDetails->customer_id);
    //         // Adding stripe customer
    //         try {
    //           $stripe_client = new StripeClient($this->apiKey);
    //           $payment_data = $stripe_client->paymentMethods->create([
    //             'type' => 'card',
    //             'card' => [
    //               'number' => base64_decode($request->input('number')),
    //               'exp_month' => base64_decode($request->input('month')),
    //               'exp_year' => base64_decode($request->input('year')),
    //               'cvc' => base64_decode($request->input('track_id')),
    //             ],
    //              'billing_details'=> [
    //                  'name'=> $request->input('name')
    //                  ]
    //           ]);
    //           $customerDetailsAry = array(
    //             'email' => $customer_data->email,
    //             'source' => $request->token,
    //         );
    //          $customerResult = $this->addCustomer($customerDetailsAry);
    //              // Retrieve a payment Intent
    //          $payment_intent = new PaymentIntent();
    //             $payment_intent_data = array(
    //                 'customer'              => $customerResult->id,
    //                 'amount'                => $orderDetails->total_paid * 100, // Tax is added here
    //                 'currency'              => $request->currency_code,
    //                 'description'           => $productDetails->name,
    //                 'payment_method_types'  => ['card'],
    //                 'capture_method'        => 'manual',
    //                 'payment_method'=>$payment_data->id,
    //                 'metadata'              => array(
    //                     'order_id'    => $orderId
    //                 ),
    //                 'shipping' => [
    //                     'name' => $customer_data->name,
    //                     'address' => [
    //                       'line1' => $orderDetails->address->address_1,
    //                       'postal_code' => $orderDetails->address->zip,
    //                       'city' => $orderDetails->address->town,
    //                       'state' => $orderDetails->address->town,
    //                       'country' => 'IE',
    //                     ],
    //                 ],
    //             );
    //             $result = $payment_intent->create($payment_intent_data);
    //  // Updating the order table
    //         } 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('driver.capture.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('driver.capture.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('driver.capture.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('driver.capture.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('driver.capture.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('driver.capture.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('driver.capture.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->completed_date   = date('Y-m-d H:i:s');
    //         $orderDetails->save();
    //     }
    //  // Fetching order data
    //  $order_data = Order::find($request->order_id);
    //  $order_data_product = OrderProduct::where('order_id',$order_data->id)->first();
    //  if ($order_data->payment_option == 'Credit Card') {
    //      try {
    //    $customer_data = Customer::find($order_data->customer_id);
    //         $stripe_customer = new Stripe_customer();
    //         $strie_cus_det = $stripe_customer->retrieve($order_data->stripe_customer_id);
    

    //              // Retrieve a payment Intent
    //      $intent_result = \Stripe\PaymentIntent::retrieve($order_data->transaction_id);
    //      /*echo '<pre>';
    //      print_r($intent_result); die;*/
    //  // Confirming the payment intent
    //      $intent_result->confirm();
    //  // Capture payment intent
    //      $intent_result->capture(['amount_to_capture' => $fill_the_tank_final_amount * 100]);
    //  $serialized_result = $intent_result->jsonSerialize();
    //  // Updating the order table
    //         } 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('driver.capture.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('driver.capture.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('driver.capture.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('driver.capture.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('driver.capture.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('driver.capture.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('driver.capture.failed')->with('error', $e->getError()->message);
    //           // Something else happened, completely unrelated to Stripe
    //         }
    

    //         if ( $serialized_result['status'] == 'succeeded' ) {
    //             $order_data->transaction_status = $serialized_result['status'];
    //             $order_data->order_status_id = 1;
    //             $order_data->fill_the_tank_quantity = $fill_the_tank_quantity;
    //             $order_data->fill_the_tank_price = $fill_the_tank_price;
    //             $order_data->total = $fill_the_tank_final_amount;
    //             $order_data->tax_value = $fill_the_tank_tax_value;
    //             $order_data->tax = $fill_the_tank_tax_value;
    //             $order_data->total_paid = $fill_the_tank_final_amount;
    //             $order_data->discount_amount = $discount_amount;
    //             $order_data->discounts = $request->discount_amount;
    //             $order_data->total_products = $subTotal;
    //             $order_data->order_status = 1;
    //             $order_data->delivery_date = date("Y-m-d");
    //             $order_data->completed_date   = date('Y-m-d H:i:s');
    //             $order_data->save();
    //         }
    //         // Updating the order_product_table
    //         if ( $serialized_result['status'] == 'succeeded' ) {
    //             $order_data_product->quantity = $fill_the_tank_quantity;
    //             $order_data_product->product_price = $subTotal;
    //             $order_data_product->save();
    //             /* Start Send Invoice to Customer */
    //             $setting = WebsiteSetting::first();
    //             $address = DB::table('addresses')->where('id', $order_data->delivery_address_id)->first();
    //             $data = [
    //                 'order' => $order_data,
    //                 'products' => $order_data->products,
    //                 'customer' => $order_data->customer,
    //                 'courier' => $order_data->courier,
    //                 'address'   => $address,
    //                 'status' => $order_data->orderStatus,
    //                 'payment' => $order_data->paymentMethod,
    //                 'setting' => $setting
    //             ];
    //             $destinationPath = public_path().'/invoices';
    //             if(!File::exists($destinationPath)) {
    //                 File::makeDirectory($destinationPath, $mode = 0777, true, true);
    //             }
    //             $pdfName = $request->order_id.'.pdf';
    //             $target = public_path('/invoices/').$pdfName;
    //             $pdf = app()->make('dompdf.wrapper');
    //             $pdf->loadView('invoices.orders', $data);
    //             $pdf->save($target);
    //             $customer = $order_data->customer;
    //             $attachment = public_path('/invoices/'.$pdfName);
    //             $data = [
    //                 "customer_name" => $customer->name,
    //                 "order_date" => $order_data->created_at,
    //                 "delevery_date" => $order_data->delevery_date,
    //                 "final_amount" => $fill_the_tank_final_amount
    //             ];
    //             /*Mail::send('emails.customer.emailInvoicetoCustomer', $data, function ($message) use ($customer, $order_data, $attachment) {
    //                 $message->from(config('constants.ADMIN_EMAIL'));
    //                 $message->to($customer->email,$customer->name)->subject('#'.$order_data->id.' Order Invoice');
    //                 $message->attach($attachment);
    //             });*/
    //             /* End Send Invoice to Customer */
    //         }
    //  if ( $serialized_result['status'] == 'succeeded' ) {
    //      session([ 'session_receive_success_page' => 1 ]);
    //      return redirect()->route('driver.capture.success')->with("success","Payment charged to Credit Card Successfully");
    //  } else {
    //         session([ 'session_receive_failed_page' => 1 ]);
    //         return redirect()->route('driver.capture.failed');
    //     }
    // }
    // else{
    

    //             $order_data->fill_the_tank_quantity = $fill_the_tank_quantity;
    //             $order_data->fill_the_tank_price = $fill_the_tank_price;
    //             $order_data->total = $fill_the_tank_final_amount;
    //             $order_data->tax_value = $fill_the_tank_tax_value;
    //             $order_data->tax = $fill_the_tank_tax_value;
    //             $order_data->total_paid = $fill_the_tank_final_amount;
    //             $order_data->discount_amount = $discount_amount;
    //             $order_data->discounts = $request->discount_amount;
    //             $order_data->total_products = $subTotal;
    //             $order_data->order_status = 1;
    //             $order_data->delivery_date = date("Y-m-d");
    //              $order_data->transaction_status = 'succeeded';
    //              $order_data->completed_date   = date('Y-m-d H:i:s');
    //             $order_data->save();
    //             $order_data_product->quantity = $fill_the_tank_quantity;
    //             $order_data_product->product_price = $subTotal;
    //             $order_data_product->save();
    //             /* Start Send Invoice to Customer */
    //             $setting = WebsiteSetting::first();
    //             $address = DB::table('addresses')->where('id', $order_data->delivery_address_id)->first();
    //             $data = [
    //                 'order' => $order_data,
    //                 'products' => $order_data->products,
    //                 'customer' => $order_data->customer,
    //                 'courier' => $order_data->courier,
    //                 'address'   => $address,
    //                 'status' => $order_data->orderStatus,
    //                 'payment' => $order_data->paymentMethod,
    //                 'setting' => $setting
    //             ];
    //             $destinationPath = public_path().'/invoices';
    //             if(!File::exists($destinationPath)) {
    //                 File::makeDirectory($destinationPath, $mode = 0777, true, true);
    //             }
    //             $pdfName = $request->order_id.'.pdf';
    //             $target = public_path('/invoices/').$pdfName;
    //             $pdf = app()->make('dompdf.wrapper');
    //             $pdf->loadView('invoices.orders', $data);
    //             $pdf->save($target);
    //             $customer = $order_data->customer;
    //             $attachment = public_path('/invoices/'.$pdfName);
    //             $data = [
    //                 "customer_name" => $customer->name,
    //                 "order_date" => $order_data->created_at,
    //                 "delevery_date" => $order_data->delevery_date,
    //                 "final_amount" => $fill_the_tank_final_amount
    //             ];
    //             /*Mail::send('emails.customer.emailInvoicetoCustomer', $data, function ($message) use ($customer, $order_data, $attachment) {
    //                 $message->from(config('constants.ADMIN_EMAIL'));
    //                 $message->to($customer->email,$customer->name)->subject('#'.$order_data->id.' Order Invoice');
    //                 $message->attach($attachment);
    //             });*/
    //             /* End Send Invoice to Customer */
    //             session([ 'session_receive_success_page' => 1 ]);
    //         if($order_data->payment_option == 'Cash'){
    //           $responseMessage = "Payment taken by Cash Successfully";
    //         }
    //         elseif($order_data->payment_option == 'Cheque'){
    //           $responseMessage = "Payment taken by Cheque Successfully";
    //         }
    //         elseif($order_data->payment_option == 'Credit Account'){
    //           $responseMessage = "Payment added to Credit Account Successfully";
    //         }
    //         else{
    //           $responseMessage = "Payment charged to Credit Card Successfully";
    //         }
    //      return redirect()->route('driver.capture.success')->with("success",$responseMessage);
    // }
    // }
    public function receive_payment(Request $request)
    {
       
        $fill_the_tank_quantity = $request->fill_the_tank_quantity;
        $fill_the_tank_price = $request->fill_the_tank_amount;
        $fill_the_tank_tax_value = $request->fill_the_tank_tax_value;
        $fill_the_tank_final_amount = $request->fill_the_tank_final_amount;
       
        // Updated discount amount
        $discount_amount = $request->discount_amount;
        $subTotal = ($fill_the_tank_final_amount - ($fill_the_tank_tax_value - $request->discount_amount));

        // Fetching order data
        $order_data = Order::find($request->order_id);

        $order_data_product = OrderProduct::where('order_id', $order_data->id)
            ->first();
        if ($request->has('merchent_key'))
        {
            $address = Address::where('customer_id', $order_data->customer_id)
                ->first();
            $elavon_user_name = config('elavon.key');
            $elavon_user_password = config('elavon.secret');
            $base_inc = base64_encode($elavon_user_name . ':' . $elavon_user_password);
            $vendor_name = config('elavon.vendorName');
            $customer_data = Customer::where('id', $order_data->customer_id)
                ->first();
            $fill_the_tank_final_amount = round($fill_the_tank_final_amount,2);    
            $elav_order_total = $fill_the_tank_final_amount * 100;
            
            //$elav_order_total = number_format($elav_order_total,2);
             
            $ch = curl_init();
            $header = array();

            $header[] = 'Content-type: application/json';
            $header[] = 'Authorization: Basic ' . $base_inc;
            $payload = json_encode(array(
                "vendorName" => $vendor_name
            ));
            $card_identifier = $request->input('card-identifier');
            $ms = $request->input('merchent_key');

            $payment_payload = json_encode(array(
                "transactionType" => "Payment",
                "paymentMethod" => array(
                    'card' => array(
                        "merchantSessionKey" => $ms,
                        "cardIdentifier" => $card_identifier,
                        "save" => false
                    )
                ) ,
                "vendorTxCode" => "oil-" . rand() ,
                "amount" => (int)$elav_order_total,
                "currency" => "EUR",
                "description" => "Oil Order",
                "customerFirstName" => $customer_data->fname,
                "customerLastName" => $customer_data->lname,
                "customerEmail" => $customer_data->email,
                "billingAddress" => array(
                    "address1" => $address->address_1,
                    "postalCode" => $address->zip,
                    "city" => $address->town,
                    "country" => 'IE'
                ) ,
                "entryMethod" => "Ecommerce",
                "apply3DSecure"=> "Force",
                "strongCustomerAuthentication"=>array("notificationURL"=> route('driver.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'] = $request->order_id;
                $transData['url'] = route('driver.threed.secure');
                $order_data->fill_the_tank_quantity = $fill_the_tank_quantity;
                $order_data->fill_the_tank_price = $fill_the_tank_price;
                $order_data->total = $fill_the_tank_final_amount;
                $order_data->tax_value = $fill_the_tank_tax_value;
                $order_data->tax = $fill_the_tank_tax_value;
                $order_data->total_paid = $fill_the_tank_final_amount;
                $order_data->discount_amount = $discount_amount;
                $order_data->discounts = $request->discount_amount;
                $order_data->total_products = $subTotal;
                $order_data->transaction_id = $serialized_result->transactionId;
                $order_data->order_status = 1;
                $order_data->delivery_date = date("Y-m-d");
                $order_data->completed_date = date('Y-m-d H:i:s');
                $order_data->save();
                return view('auth.threedsecure',$transData);
            }else if(isset($serialized_result->status) && $serialized_result->status == 'Ok'){
                $transaction_id = $serialized_result->transactionId;
                Order::where('id', $request->order_id)
                ->update(['transaction_id' => $transaction_id]);
            }   
            // $transaction_id = $serialized_result->transactionId;
            // Order::where('id', $request->order_id)
            //     ->update(['transaction_id' => $transaction_id]);
        }
        else
        {
            $transaction_id = $order_data->transaction_id;
        }

        if ($order_data->payment_option == 'Credit Card')
        {

            try
            {
                $customer_data = Customer::find($order_data->customer_id);

                $serialized_result = $this->recievePayment($transaction_id, $fill_the_tank_final_amount);

                // Updating the order table
                if (isset($serialized_result->instructionType))
                {

                    if ($serialized_result->instructionType == 'release')
                    {
                        $order_data->transaction_status = 'succeeded';
                        $order_data->order_status_id = 1;
                        $order_data->fill_the_tank_quantity = $fill_the_tank_quantity;
                        $order_data->fill_the_tank_price = $fill_the_tank_price;
                        $order_data->total = $fill_the_tank_final_amount;
                        $order_data->tax_value = $fill_the_tank_tax_value;
                        $order_data->tax = $fill_the_tank_tax_value;
                        $order_data->total_paid = $fill_the_tank_final_amount;
                        $order_data->discount_amount = $discount_amount;
                        $order_data->discounts = $request->discount_amount;
                        $order_data->total_products = $subTotal;
                        $order_data->order_status = 1;
                        $order_data->delivery_date = date("Y-m-d");
                        $order_data->completed_date = date('Y-m-d H:i:s');
                        $order_data->save();
                    }
                    // Updating the order_product_table
                    if ($serialized_result->instructionType == 'release')
                    {

                        $order_data_product->quantity = $fill_the_tank_quantity;
                        $order_data_product->product_price = $subTotal;
                        $order_data_product->save();

                        /* Start Send Invoice to Customer */
                        $setting = WebsiteSetting::first();
                        $address = DB::table('addresses')->where('id', $order_data->delivery_address_id)
                            ->first();
                        $data = ['order' => $order_data, 'products' => $order_data->products, 'customer' => $order_data->customer, 'courier' => $order_data->courier, 'address' => $address, 'status' => $order_data->orderStatus, 'payment' => $order_data->paymentMethod, 'setting' => $setting];

                        $destinationPath = public_path() . '/invoices';
                        if (!File::exists($destinationPath))
                        {
                            File::makeDirectory($destinationPath, $mode = 0777, true, true);
                        }

                        $pdfName = $request->order_id . '.pdf';
                        $target = public_path('/invoices/') . $pdfName;
                        $pdf = app()->make('dompdf.wrapper');
                        $pdf->loadView('invoices.orders', $data);
                        $pdf->save($target);
                        $customer = $order_data->customer;
                        $attachment = public_path('/invoices/' . $pdfName);

                        $data = ["customer_name" => $customer->name, "order_date" => $order_data->created_at, "delevery_date" => $order_data->delevery_date, "final_amount" => $fill_the_tank_final_amount];

                        /*Mail::send('emails.customer.emailInvoicetoCustomer', $data, function ($message) use ($customer, $order_data, $attachment) {
                            $message->from(config('constants.ADMIN_EMAIL'));
                            $message->to($customer->email,$customer->name)->subject('#'.$order_data->id.' Order Invoice');
                            $message->attach($attachment);
                        });*/

                        /* End Send Invoice to Customer */
                    }
                    if ($serialized_result->instructionType == 'release')
                    {
                        session(['session_receive_success_page' => 1]);
                        return redirect()
                            ->route('driver.capture.success')
                            ->with("success", "Payment charged to Credit Card Successfully");
                    }
                    else
                    {
                        session(['session_receive_failed_page' => 1]);
                        return redirect()
                            ->route('driver.capture.failed');
                    }
                }
                else
                {
                    session(['session_receive_failed_page' => 1]);
                    return redirect()
                        ->route('driver.capture.failed')
                        ->with('error', $serialized_result->description);
                }
            }
            catch(Exception $e)
            {
                // Since it's a decline, \Stripe\Exception\CardException will be caught
                session(['session_receive_failed_page' => 1]);
                return redirect()->route('driver.capture.failed')
                    ->with('error', $e->getError()
                    ->message);
            }
        }
        else
        {

            $order_data->fill_the_tank_quantity = $fill_the_tank_quantity;
            $order_data->fill_the_tank_price = $fill_the_tank_price;
            $order_data->total = $fill_the_tank_final_amount;
            $order_data->tax_value = $fill_the_tank_tax_value;
            $order_data->tax = $fill_the_tank_tax_value;
            $order_data->total_paid = $fill_the_tank_final_amount;
            $order_data->discount_amount = $discount_amount;
            $order_data->discounts = $request->discount_amount;
            $order_data->total_products = $subTotal;
            $order_data->order_status = 1;
            $order_data->delivery_date = date("Y-m-d");
            $order_data->transaction_status = 'succeeded';
            $order_data->completed_date = date('Y-m-d H:i:s');
            $order_data->save();

            $order_data_product->quantity = $fill_the_tank_quantity;
            $order_data_product->product_price = $subTotal;
            $order_data_product->save();

            /* Start Send Invoice to Customer */
            $setting = WebsiteSetting::first();
            $address = DB::table('addresses')->where('id', $order_data->delivery_address_id)
                ->first();
            $data = ['order' => $order_data, 'products' => $order_data->products, 'customer' => $order_data->customer, 'courier' => $order_data->courier, 'address' => $address, 'status' => $order_data->orderStatus, 'payment' => $order_data->paymentMethod, 'setting' => $setting];

            $destinationPath = public_path() . '/invoices';
            if (!File::exists($destinationPath))
            {
                File::makeDirectory($destinationPath, $mode = 0777, true, true);
            }

            $pdfName = $request->order_id . '.pdf';
            $target = public_path('/invoices/') . $pdfName;
            $pdf = app()->make('dompdf.wrapper');
            $pdf->loadView('invoices.orders', $data);
            $pdf->save($target);
            $customer = $order_data->customer;
            $attachment = public_path('/invoices/' . $pdfName);

            $data = ["customer_name" => $customer->name, "order_date" => $order_data->created_at, "delevery_date" => $order_data->delevery_date, "final_amount" => $fill_the_tank_final_amount];

            /*Mail::send('emails.customer.emailInvoicetoCustomer', $data, function ($message) use ($customer, $order_data, $attachment) {
                    $message->from(config('constants.ADMIN_EMAIL'));
                    $message->to($customer->email,$customer->name)->subject('#'.$order_data->id.' Order Invoice');
                    $message->attach($attachment);
                });*/

            /* End Send Invoice to Customer */

            session(['session_receive_success_page' => 1]);

            if ($order_data->payment_option == 'Cash')
            {
                $responseMessage = "Payment taken by Cash Successfully";
            }
            elseif ($order_data->payment_option == 'Cheque')
            {
                $responseMessage = "Payment taken by Cheque Successfully";
            }
            elseif ($order_data->payment_option == 'Credit Account')
            {
                $responseMessage = "Payment added to Credit Account Successfully";
            }
            else
            {
                $responseMessage = "Payment charged to Credit Card Successfully";
            }

            return redirect()->route('driver.capture.success')
                ->with("success", $responseMessage);
        }
    }

    // public function receive_payment_fill_the_tank(Request $request) {
    //  $fill_the_tank_quantity = $request->fill_the_tank_quantity;
    //  $fill_the_tank_price = $request->fill_the_tank_amount;
    //     $fill_the_tank_tax_value = $request->fill_the_tank_tax_value;
    //     $fill_the_tank_final_amount = $request->fill_the_tank_final_amount;
    //      $subTotal = ( $fill_the_tank_final_amount - ( $fill_the_tank_tax_value - $request->discount_amount ) );
    //  // Fetching order data
    //  $order_data = Order::find($request->order_id);
    //  $order_data_product = OrderProduct::where('order_id',$order_data->id)->first();
    

    //     if($request->token){
    //         $orderId = $request->order_id;
    //         $orderDetails = Order::find($orderId);
    //         $orderProduct = OrderProduct::where(['order_id' => $orderId])->first();
    //         $productDetails = Product::find($orderProduct->product_id);
    //         $customer_data = Customer::find($orderDetails->customer_id);
    //         // Adding stripe customer
    //         $paymentInstanceId = $order_data->transaction_id;
    

    //         try {
    //           $stripe_client = new StripeClient($this->apiKey);
    //           $payment_data = $stripe_client->paymentMethods->create([
    //             'type' => 'card',
    //             'card' => [
    //               'number' => base64_decode($request->input('number')),
    //               'exp_month' => base64_decode($request->input('month')),
    //               'exp_year' => base64_decode($request->input('year')),
    //               'cvc' => base64_decode($request->input('track_id')),
    //             ],
    //              'billing_details'=> [
    //                  'name'=> $request->input('name')
    //                  ]
    //           ]);
    //           $customerDetailsAry = array(
    //             'email' => $customer_data->email,
    //             'source' => $request->token,
    //         );
    //          $customerResult = $this->addCustomer($customerDetailsAry);
    //             // Retrieve a payment Intent
    //         $payment_intent = new PaymentIntent();
    //             $payment_intent_data = array(
    //                 'customer'              => $customerResult->id,
    //                 'amount'                => $orderDetails->total_paid * 100, // Tax is added here
    //                 'currency'              => $request->currency_code,
    //                 'description'           => $productDetails->name,
    //                 'payment_method_types'  => ['card'],
    //                 'capture_method'        => 'manual',
    //                 'payment_method'=>$payment_data->id,
    //                 'metadata'              => array(
    //                     'order_id'    => $orderId
    //                 ),
    //                 'shipping' => [
    //                     'name' => $customer_data->name,
    //                     'address' => [
    //                       'line1' => $orderDetails->address->address_1,
    //                       'postal_code' => $orderDetails->address->zip,
    //                       'city' => $orderDetails->address->town,
    //                       'state' => $orderDetails->address->town,
    //                       'country' => 'IE',
    //                     ],
    //                 ],
    //             );
    //             $result = $payment_intent->create($payment_intent_data);
    //     // Updating the order table
    //         } 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('driver.capture.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('driver.capture.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('driver.capture.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('driver.capture.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('driver.capture.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('driver.capture.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('driver.capture.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->completed_date   = date('Y-m-d H:i:s');
    //         $orderDetails->save();
    //         $paymentInstanceId = $serialized_result['id'];
    //     }
    //  if($order_data->payment_option == 'Credit Card'){
    //      if ($order_data->transaction_status == 'requires_payment_method' || $order_data->transaction_status == 'requires_confirmation') {
    //  // Retrieve a payment Intent
    //     try{
    //      $intent_result = \Stripe\PaymentIntent::retrieve($order_data->transaction_id);
    //      // Confirming the payment intent
    //      $intent_result->confirm();
    //      // Capture payment intent
    //      $intent_result->capture(['amount_to_capture' => $fill_the_tank_final_amount * 100]);
    //      $serialized_result = $intent_result->jsonSerialize();
    //     }
    //     catch (Exception $e) {
    //         \Log::info(print_r($e->getError()->message,true));
    //       session([ 'session_receive_failed_page' => 1 ]);
    //         return redirect()->route('driver.capture.failed')->with('error', $e->getError()->message." Please try again.");
    //       // Something else happened, completely unrelated to Stripe
    //     }
    //  // Updating the order table
    //  if ( $serialized_result['status'] == 'succeeded' ) {
    //       $order_data->transaction_status = $serialized_result['status'];
    //      $order_data->order_status_id = 1;
    //      $order_data->fill_the_tank_quantity = $fill_the_tank_quantity;
    //      $order_data->fill_the_tank_price = $fill_the_tank_price;
    //      $order_data->total = $fill_the_tank_final_amount;
    //      $order_data->total_paid = $fill_the_tank_final_amount;
    //      $order_data->total_products = $subTotal;
    //      $order_data->tax_value = $fill_the_tank_tax_value;
    //      $order_data->tax = $fill_the_tank_tax_value;
    //      // Discount
    //      $order_data->discounts = $request->discount_amount;
    //      $order_data->discount_amount = $request->discount_amount;
    //       $order_data->order_status = 1;
    //       $order_data->delivery_date = date("Y-m-d");
    //       $order_data->completed_date   = date('Y-m-d H:i:s');
    //       $order_data->save();
    //  }
    //  // Updating the prder_product_table
    //         if ( $serialized_result['status'] == 'succeeded' ) {
    //          $order_data_product->quantity = $fill_the_tank_quantity;
    //          $order_data_product->product_price = $subTotal;
    //      $order_data_product->save();
    //             /* Start Send Invoice to Customer */
    //             $setting = WebsiteSetting::first();
    //             $address = DB::table('addresses')->where('id', $order_data->delivery_address_id)->first();
    //             $data = [
    //                 'order' => $order_data,
    //                 'products' => $order_data->products,
    //                 'customer' => $order_data->customer,
    //                 'courier' => $order_data->courier,
    //                 'address'   => $address,
    //                 'status' => $order_data->orderStatus,
    //                 'payment' => $order_data->paymentMethod,
    //                 'setting' => $setting
    //             ];
    //             $destinationPath = public_path().'/invoices';
    //             if(!File::exists($destinationPath)) {
    //                 File::makeDirectory($destinationPath, $mode = 0777, true, true);
    //             }
    //             $pdfName = $request->order_id.'.pdf';
    //             $target = public_path('/invoices/').$pdfName;
    //             $pdf = app()->make('dompdf.wrapper');
    //             $pdf->loadView('invoices.orders', $data);
    //             $pdf->save($target);
    //             $customer = $order_data->customer;
    //             $attachment = public_path('/invoices/'.$pdfName);
    //             $data = [
    //                 "customer_name" => $customer->name,
    //                 "order_date" => $order_data->created_at,
    //                 "delevery_date" => $order_data->delevery_date,
    //                 "final_amount" => $fill_the_tank_final_amount
    //             ];
    //             /*Mail::send('emails.customer.emailInvoicetoCustomer', $data, function ($message) use ($customer, $order_data, $attachment) {
    //                 $message->from(config('constants.ADMIN_EMAIL'));
    //                 $message->to($customer->email,$customer->name)->subject('#'.$order_data->id.' Order Invoice');
    //                 $message->attach($attachment);
    //             });*/
    //             /* End Send Invoice to Customer */
    //         }
    //  if ( $serialized_result['status'] == 'succeeded' ) {
    //      session([ 'session_receive_success_page' => 1 ]);
    //       return redirect()->route('driver.capture.success')->with("success","Payment charged to Credit Card Successfully");
    //  } else {
    //      session([ 'session_receive_failed_page' => 1 ]);
    //      return redirect()->route('driver.capture.failed');
    //  }
    // }
    //  }else{
    //      $order_data->fill_the_tank_quantity = $fill_the_tank_quantity;
    //      $order_data->fill_the_tank_price = $fill_the_tank_price;
    //      $order_data->total = $fill_the_tank_final_amount;
    //      $order_data->total_paid = $fill_the_tank_final_amount;
    //      $order_data->total_products = $subTotal;
    //      $order_data->tax_value = $fill_the_tank_tax_value;
    //      $order_data->tax = $fill_the_tank_tax_value;
    //      $order_data->transaction_status = 'succeeded';
    //      // Discount
    //      $order_data->discounts = $request->discount_amount;
    //      $order_data->discount_amount = $request->discount_amount;
    //       $order_data->order_status = 1;
    //       $order_data->delivery_date = date("Y-m-d");
    //       $order_data->completed_date   = date('Y-m-d H:i:s');
    //       $order_data->save();
    //             $order_data_product->quantity = $fill_the_tank_quantity;
    //          $order_data_product->product_price = $subTotal;
    //      $order_data_product->save();
    //             /* Start Send Invoice to Customer */
    //             $setting = WebsiteSetting::first();
    //             $address = DB::table('addresses')->where('id', $order_data->delivery_address_id)->first();
    //             $data = [
    //                 'order' => $order_data,
    //                 'products' => $order_data->products,
    //                 'customer' => $order_data->customer,
    //                 'courier' => $order_data->courier,
    //                 'address'   => $address,
    //                 'status' => $order_data->orderStatus,
    //                 'payment' => $order_data->paymentMethod,
    //                 'setting' => $setting
    //             ];
    //             $destinationPath = public_path().'/invoices';
    //             if(!File::exists($destinationPath)) {
    //                 File::makeDirectory($destinationPath, $mode = 0777, true, true);
    //             }
    //             $pdfName = $request->order_id.'.pdf';
    //             $target = public_path('/invoices/').$pdfName;
    //             $pdf = app()->make('dompdf.wrapper');
    //             $pdf->loadView('invoices.orders', $data);
    //             $pdf->save($target);
    //             $customer = $order_data->customer;
    //             $attachment = public_path('/invoices/'.$pdfName);
    //             $data = [
    //                 "customer_name" => $customer->name,
    //                 "order_date" => $order_data->created_at,
    //                 "delevery_date" => $order_data->delevery_date,
    //                 "final_amount" => $fill_the_tank_final_amount
    //             ];
    //             /*Mail::send('emails.customer.emailInvoicetoCustomer', $data, function ($message) use ($customer, $order_data, $attachment) {
    //                 $message->from(config('constants.ADMIN_EMAIL'));
    //                 $message->to($customer->email,$customer->name)->subject('#'.$order_data->id.' Order Invoice');
    //                 $message->attach($attachment);
    //             });*/
    //             session([ 'session_receive_success_page' => 1 ]);
    //         if($order_data->payment_option == 'Cash'){
    //           $responseMessage = "Payment taken by Cash Successfully";
    //         }
    //         elseif($order_data->payment_option == 'Cheque'){
    //           $responseMessage = "Payment taken by Cheque Successfully";
    //         }
    //         elseif($order_data->payment_option == 'Credit Account'){
    //           $responseMessage = "Payment added to Credit Account Successfully";
    //         }
    //         else{
    //           $responseMessage = "Payment charged to Credit Card Successfully";
    //         }
    //         return redirect()->route('driver.capture.success')->with("success",$responseMessage);
    //  }
    // }
    public function receive_payment_fill_the_tank(Request $request)
    {
        
        $fill_the_tank_quantity = $request->fill_the_tank_quantity;
        $fill_the_tank_price = $request->fill_the_tank_amount;
        $fill_the_tank_tax_value = $request->fill_the_tank_tax_value;
        $fill_the_tank_final_amount = $request->fill_the_tank_final_amount;

        $subTotal = ($fill_the_tank_final_amount - ($fill_the_tank_tax_value - $request->discount_amount));
        // Fetching order data
        $order_data = Order::find($request->order_id);
        $order_data_product = OrderProduct::where('order_id', $order_data->id)
            ->first();

        if ($request->has('merchent_key'))
        {
            $address = Address::where('customer_id', $order_data->customer_id)
                ->first();
            $elavon_user_name = config('elavon.key');
            $elavon_user_password = config('elavon.secret');
            $base_inc = base64_encode($elavon_user_name . ':' . $elavon_user_password);
            $vendor_name = config('elavon.vendorName');
            $customer_data = Customer::where('id', $order_data->customer_id)
                ->first();
            $elav_order_total = round($fill_the_tank_final_amount,2);
            $elav_order_total = $elav_order_total * 100;
            
            //$elav_order_total = number_format($order_total,2);
            
            $ch = curl_init();
            $header = array();

            $header[] = 'Content-type: application/json';
            $header[] = 'Authorization: Basic ' . $base_inc;
            $payload = json_encode(array(
                "vendorName" => $vendor_name
            ));
            $card_identifier = $request->input('card-identifier');
            $ms = $request->input('merchent_key');

            $payment_payload = json_encode(array(
                "transactionType" => "Payment",
                "paymentMethod" => array(
                    'card' => array(
                        "merchantSessionKey" => $ms,
                        "cardIdentifier" => $card_identifier,
                        "save" => false
                    )
                ) ,
                "vendorTxCode" => "oil-" . rand() ,
                "amount" => (int)$elav_order_total,
                "currency" => "EUR",
                "description" => "Oil Order",
                "customerFirstName" => $customer_data->fname,
                "customerLastName" => $customer_data->lname,
                "customerEmail" => $customer_data->email,
                "billingAddress" => array(
                    "address1" => $address->address_1,
                    "postalCode" => $address->zip,
                    "city" => $address->town,
                    "country" => 'IE'
                ) ,
                "entryMethod" => "Ecommerce",
                "apply3DSecure"=> "Force",
                "strongCustomerAuthentication"=>array("notificationURL"=> route('driver.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'] = $request->order_id;
                
                $order_data->fill_the_tank_quantity = $fill_the_tank_quantity;
                $order_data->fill_the_tank_price = $fill_the_tank_price;
                $order_data->total = $fill_the_tank_final_amount;
                $order_data->total_paid = $fill_the_tank_final_amount;
                $order_data->total_products = $subTotal;
                $order_data->tax_value = $fill_the_tank_tax_value;
                $order_data->tax = $fill_the_tank_tax_value;
                // Discount
                $order_data->discounts = $request->discount_amount;
                $order_data->discount_amount = $request->discount_amount;
                $order_data->order_status = 1;
                $order_data->delivery_date = date("Y-m-d");
                $order_data->completed_date = date('Y-m-d H:i:s');
                $order_data->transaction_id = $serialized_result->transactionId;
                $order_data->save();
                $transData['url'] = route('driver.threed.secure');
                return view('auth.threedsecure',$transData);
            }else if(isset($serialized_result->status) && $serialized_result->status == 'Ok'){
                $transaction_id = $serialized_result->transactionId;
                // Order::where('id', $request->order_id)
                // ->update(['transaction_id' => $transaction_id,
                // 'transaction_status' => 'succeeded',
                // 'order_status_id' => '1',
                // 'fill_the_tank_quantity' => $fill_the_tank_quantity,
                // 'fill_the_tank_price' => $fill_the_tank_price,
                // 'total' => $fill_the_tank_final_amount,
                // 'total_paid' => $fill_the_tank_final_amount,
                //     'total_products' => $subTotal,
                //     'tax_value' => $fill_the_tank_tax_value,
                //     'tax' => $fill_the_tank_tax_value,
                //     // Discount
                //     'discounts' => $request->discount_amount,
                //     'discount_amount' => $request->discount_amount,
                //     'order_status' => 1,
                //     'delivery_date' => date("Y-m-d"),
                //     'completed_date' => date('Y-m-d H:i:s')
                // ]);
                $order_data->transaction_status = 'succeeded';
                    $order_data->order_status_id = 1;
                    $order_data->fill_the_tank_quantity = $fill_the_tank_quantity;
                    $order_data->fill_the_tank_price = $fill_the_tank_price;
                    $order_data->total = $fill_the_tank_final_amount;
                    $order_data->total_paid = $fill_the_tank_final_amount;
                    $order_data->total_products = $subTotal;
                    $order_data->tax_value = $fill_the_tank_tax_value;
                    $order_data->tax = $fill_the_tank_tax_value;
                    // Discount
                    $order_data->discounts = $request->discount_amount;
                    $order_data->discount_amount = $request->discount_amount;
                    $order_data->order_status = 1;
                    $order_data->delivery_date = date("Y-m-d");
                    $order_data->completed_date = date('Y-m-d H:i:s');
                    $order_data->transaction_id = $transaction_id;
                    $order_data->save();
            }else{
                return redirect()->back();
            }
        }
        else
        {
            $transaction_id = $order_data->transaction_id;
        }

        if ($order_data->payment_option == 'Credit Card')
        {
            if ($order_data->transaction_status == 'requires_payment_method' || $order_data->transaction_status == 'requires_confirmation' || $order_data->transaction_status == 'Deferred')
            {
                // Retrieve a payment Intent
                try
                {
                    $amount = $fill_the_tank_final_amount;

                    $serialized_result = $this->recievePayment($transaction_id, $amount);

                }
                catch(Exception $e)
                {

                    session(['session_receive_failed_page' => 1]);
                    return redirect()->route('driver.capture.failed')
                        ->with('error', $e->getError()->message . " Please try again.");
                    // Something else happened, completely unrelated to Stripe
                    
                }
                \Log::info(print_r($serialized_result,true));
                // Updating the order table
                if (isset($serialized_result->instructionType) && $serialized_result->instructionType == 'release')
                {
                    $order_data->transaction_status = 'succeeded';
                    $order_data->order_status_id = 1;
                    $order_data->fill_the_tank_quantity = $fill_the_tank_quantity;
                    $order_data->fill_the_tank_price = $fill_the_tank_price;
                    $order_data->total = $fill_the_tank_final_amount;
                    $order_data->total_paid = $fill_the_tank_final_amount;
                    $order_data->total_products = $subTotal;
                    $order_data->tax_value = $fill_the_tank_tax_value;
                    $order_data->tax = $fill_the_tank_tax_value;
                    // Discount
                    $order_data->discounts = $request->discount_amount;
                    $order_data->discount_amount = $request->discount_amount;
                    $order_data->order_status = 1;
                    $order_data->delivery_date = date("Y-m-d");
                    $order_data->completed_date = date('Y-m-d H:i:s');
                    $order_data->save();
                }

                // Updating the prder_product_table
                if (isset($serialized_result->instructionType) && $serialized_result->instructionType == 'release')
                {
                    $order_data_product->quantity = $fill_the_tank_quantity;
                    $order_data_product->product_price = $subTotal;
                    $order_data_product->save();

                    /* Start Send Invoice to Customer */
                    $setting = WebsiteSetting::first();
                    $address = DB::table('addresses')->where('id', $order_data->delivery_address_id)
                        ->first();
                    $data = ['order' => $order_data, 'products' => $order_data->products, 'customer' => $order_data->customer, 'courier' => $order_data->courier, 'address' => $address, 'status' => $order_data->orderStatus, 'payment' => $order_data->paymentMethod, 'setting' => $setting];

                    $destinationPath = public_path() . '/invoices';
                    if (!File::exists($destinationPath))
                    {
                        File::makeDirectory($destinationPath, $mode = 0777, true, true);
                    }

                    $pdfName = $request->order_id . '.pdf';
                    $target = public_path('/invoices/') . $pdfName;
                    $pdf = app()->make('dompdf.wrapper');
                    $pdf->loadView('invoices.orders', $data);
                    $pdf->save($target);
                    $customer = $order_data->customer;
                    $attachment = public_path('/invoices/' . $pdfName);

                    $data = ["customer_name" => $customer->name, "order_date" => $order_data->created_at, "delevery_date" => $order_data->delevery_date, "final_amount" => $fill_the_tank_final_amount];

                    /*Mail::send('emails.customer.emailInvoicetoCustomer', $data, function ($message) use ($customer, $order_data, $attachment) {
                    $message->from(config('constants.ADMIN_EMAIL'));
                    $message->to($customer->email,$customer->name)->subject('#'.$order_data->id.' Order Invoice');
                    $message->attach($attachment);
                    });*/

                    /* End Send Invoice to Customer */

                }
                if (isset($serialized_result->instructionType) && $serialized_result->instructionType == 'release')
                {
                    session(['session_receive_success_page' => 1]);

                    return redirect()
                        ->route('driver.capture.success')
                        ->with("success", "Payment charged to Credit Card Successfully");
                }
                else
                {
                    session(['session_receive_failed_page' => 1]);
                    return redirect()
                        ->route('driver.capture.failed');
                }
            }
        }
        else
        {

            $order_data->fill_the_tank_quantity = $fill_the_tank_quantity;
            $order_data->fill_the_tank_price = $fill_the_tank_price;
            $order_data->total = $fill_the_tank_final_amount;
            $order_data->total_paid = $fill_the_tank_final_amount;
            $order_data->total_products = $subTotal;
            $order_data->tax_value = $fill_the_tank_tax_value;
            $order_data->tax = $fill_the_tank_tax_value;
            $order_data->transaction_status = 'succeeded';
            // Discount
            $order_data->discounts = $request->discount_amount;
            $order_data->discount_amount = $request->discount_amount;
            $order_data->order_status = 1;
            $order_data->delivery_date = date("Y-m-d");
            $order_data->completed_date = date('Y-m-d H:i:s');
            $order_data->save();

            $order_data_product->quantity = $fill_the_tank_quantity;
            $order_data_product->product_price = $subTotal;
            $order_data_product->save();

            /* Start Send Invoice to Customer */
            $setting = WebsiteSetting::first();
            $address = DB::table('addresses')->where('id', $order_data->delivery_address_id)
                ->first();
            $data = ['order' => $order_data, 'products' => $order_data->products, 'customer' => $order_data->customer, 'courier' => $order_data->courier, 'address' => $address, 'status' => $order_data->orderStatus, 'payment' => $order_data->paymentMethod, 'setting' => $setting];

            $destinationPath = public_path() . '/invoices';
            if (!File::exists($destinationPath))
            {
                File::makeDirectory($destinationPath, $mode = 0777, true, true);
            }

            $pdfName = $request->order_id . '.pdf';
            $target = public_path('/invoices/') . $pdfName;
            $pdf = app()->make('dompdf.wrapper');
            $pdf->loadView('invoices.orders', $data);
            $pdf->save($target);
            $customer = $order_data->customer;
            $attachment = public_path('/invoices/' . $pdfName);

            $data = ["customer_name" => $customer->name, "order_date" => $order_data->created_at, "delevery_date" => $order_data->delevery_date, "final_amount" => $fill_the_tank_final_amount];

            /*Mail::send('emails.customer.emailInvoicetoCustomer', $data, function ($message) use ($customer, $order_data, $attachment) {
                    $message->from(config('constants.ADMIN_EMAIL'));
                    $message->to($customer->email,$customer->name)->subject('#'.$order_data->id.' Order Invoice');
                    $message->attach($attachment);
                });*/
            session(['session_receive_success_page' => 1]);

            if ($order_data->payment_option == 'Cash')
            {
                $responseMessage = "Payment taken by Cash Successfully";
            }
            elseif ($order_data->payment_option == 'Cheque')
            {
                $responseMessage = "Payment taken by Cheque Successfully";
            }
            elseif ($order_data->payment_option == 'Credit Account')
            {
                $responseMessage = "Payment added to Credit Account Successfully";
            }
            else
            {
                $responseMessage = "Payment charged to Credit Card Successfully";
            }

            return redirect()->route('driver.capture.success')
                ->with("success", $responseMessage);
        }
    }

    public function receive_success(Request $request)
    {
        // Checking the session if not exist then redirect to home page
        if ($request->session()
            ->has('session_receive_success_page'))
        {
            Session::forget('session_receive_success_page');
            return view('driver.orders.success');
        }
        else
        {
            return redirect()
                ->route('driver.orders', ["tab" => "pending-orders"]);
        }
    }

    public function receive_failed(Request $request)
    {

        // Checking the session if not exist then redirect to home page
        if ($request->session()
            ->has('session_receive_failed_page'))
        {

            Session::forget('session_receive_failed_page');
            return view('driver.orders.failed');
        }
        else
        {
            return redirect()
                ->route('driver.orders', ["tab" => "pending-orders"]);
        }
    }

    // Fetch price according to algorithm
    public function fetch_price(Request $request)
    {
        // -----------  Algorithm Calculation for unique quantity values ------------ //
        // Price Per Litre
        // (High Threshold Price - Low Threshold Price) / (High Threshold Litres - Low Threshold Litres)
        // (€150.00 - €100.00) / (300 - 200) = €0.50 cents
        // Fill Price
        // (Price Per Litre x (Fill Litres - Low Threshold Litres)) + Low Threshold Price
        // (€0.50 x (220 - 200)) + €100.00 = €110
        // -----------  Algorithm Calculation for unique quantity values ------------ //
        $order_id = $request->order_id;
        $product_id = $request->product_id;
        $demanded_quantity = $request->quantity;
        // Fetching the available quantity array for the product
        

        $quantity_data = DB::table('order_product_prices')->leftJoin('attribute_value_product_attribute', 'attribute_value_product_attribute.product_attribute_id', '=', 'order_product_prices.attribute_id')
            ->leftJoin('attribute_values', 'attribute_values.id', '=', 'attribute_value_product_attribute.attribute_value_id')
            ->where('order_product_prices.product_id', $product_id)->where('order_product_prices.order_id', $order_id)->select('attribute_values.value')
            ->orderBy('attribute_values.value', 'ASC')
            ->get();
        if (count($quantity_data) == 0)
        {
            $quantity_data = DB::table('product_attributes')->leftJoin('attribute_value_product_attribute', 'attribute_value_product_attribute.product_attribute_id', '=', 'product_attributes.id')
                ->leftJoin('attribute_values', 'attribute_values.id', '=', 'attribute_value_product_attribute.attribute_value_id')
                ->where('product_attributes.product_id', $product_id)->select('attribute_values.value')
                ->orderBy('attribute_values.value', 'ASC')
                ->get();
        }
        // Array Of all quantities
        $quantities = [];
        foreach ($quantity_data as $quantity)
        {
            $quantities[] = $quantity->value;
        }
        // Case 1st : When demanded_quantity is in the array then fetch the price directly
        if (in_array($demanded_quantity, $quantities))
        {
            // Fetching the price according to quantity
            $price = $this->fetch_price_according_quantity($product_id, $demanded_quantity, $order_id);
            echo json_encode(floatval($price));
            // Case 2nd : When demanded_quantity is greater than all the quantities
            
        }
        elseif ($demanded_quantity > max($quantities))
        {
            $array_length = count($quantities);
            $high_threshold_liter = max($quantities);
            // if ($array_length > 1)
            // {
            //     $low_threshold_liter = $quantities[$array_length - 2];
            // }
            // else
            // {
            //     $low_threshold_liter = max($quantities);
            // }
           $high_threshold_price = $this->fetch_price_according_quantity($product_id, $high_threshold_liter,$order_id);
            // $low_threshold_price = $this->fetch_price_according_quantity($product_id, $low_threshold_liter, $order_id);
            // $low_thresh_val = DB::table('order_product_prices')->leftJoin('product_attributes', 'product_attributes.id', '=', 'order_product_prices.attribute_id')
            //     ->where('order_id', $order_id)->where('order_product_prices.product_id', $product_id)->where('product_attributes.quantity', '<', $demanded_quantity)->orderBy('product_attributes.quantity', 'desc')
            //     ->select('order_product_prices.price', 'product_attributes.quantity')
            //     ->first();
            // if (!$low_thresh_val)
            // {
            //     $low_thresh_val = DB::table('product_attributes')->leftJoin('attribute_value_product_attribute', 'attribute_value_product_attribute.product_attribute_id', '=', 'product_attributes.id')
            //         ->leftJoin('attribute_values', 'attribute_values.id', '=', 'attribute_value_product_attribute.attribute_value_id')
            //         ->where('product_attributes.product_id', $product_id)->where('product_attributes.quantity', '<', $demanded_quantity)->orderBy('product_attributes.quantity', 'desc')

            //         ->first();
            // }
            // Calculating the price per liter
           $price_per_liter = $high_threshold_price  / $high_threshold_liter;
    		//echo $price_per_liter; die;
    		//$price_per_liter = number_format($price_per_liter,2);
    	
    		// Calculating the price that will be paid
    		//Fill Price
			$fill_price = $price_per_liter * $demanded_quantity;
            echo json_encode($fill_price);
            // Case 3rd : When demanded_quantity is less than all the quantities
            
        }
        elseif ($demanded_quantity < min($quantities))
        {
            $array_length = count($quantities);
            $low_threshold_liter = min($quantities);
            if ($array_length > 1)
            {
                $high_threshold_liter = $quantities[1];
            }
            else
            {
                $high_threshold_liter = min($quantities);
            }
            $high_threshold_price = $this->fetch_price_according_quantity($product_id, $high_threshold_liter, $order_id);
            $low_threshold_price = $this->fetch_price_according_quantity($product_id, $low_threshold_liter, $order_id);
            // Calculating the price per liter
            $price_per_liter = ($high_threshold_price - $low_threshold_price) / ($high_threshold_liter - $low_threshold_liter);
            $price_per_liter = round($price_per_liter, 2);
            // Calculating the price that will be paid
            //Fill Price
            $fill_price = ($price_per_liter * ($demanded_quantity - $low_threshold_liter)) + $low_threshold_price;
            echo json_encode($fill_price);
            // Case 4th :  When demanded_quantity is in middle of existimg quantity
            
        }
        else
        {
            
              
            $low_threshold_liter = $this->fetch_minimum_quantity($demanded_quantity, $quantities);
            $high_threshold_liter = $this->fetch_maximum_quantity($demanded_quantity, $quantities);
            $cal_low_diff = $demanded_quantity - $low_threshold_liter;
            if($cal_low_diff < 50){
                 $price = $this->fetch_price_according_quantity($product_id, $low_threshold_liter,$order_id);
                 $price_per_liter = $price  / $low_threshold_liter;     
            }else{
                $price = $this->fetch_price_according_quantity($product_id, $high_threshold_liter,$order_id);
                 $price_per_liter = $price  / $high_threshold_liter; 
            }
            // $high_threshold_price = $this->fetch_price_according_quantity($product_id, $high_threshold_liter, $order_id);
            // $low_threshold_price = $this->fetch_price_according_quantity($product_id, $low_threshold_liter, $order_id);
            // Calculating the price per liter
          
            // Calculating the price that will be paid
            //Fill Price
            $fill_price = $price_per_liter * $demanded_quantity;
            echo json_encode($fill_price);
        }
        //echo json_encode($quantities);
        
    }


    public function fetch_price_according_quantity($product_id, $quantity, $order_id)
    {
        $quantity = round($quantity, 0);
        $price_data = DB::table('order_product_prices')->leftJoin('attribute_value_product_attribute', 'attribute_value_product_attribute.product_attribute_id', '=', 'order_product_prices.attribute_id')
            ->leftJoin('attribute_values', 'attribute_values.id', '=', 'attribute_value_product_attribute.attribute_value_id')
            ->where('order_product_prices.product_id', $product_id)->where('order_product_prices.order_id', $order_id)->where('attribute_values.value', $quantity)->select('order_product_prices.price')
            ->first();
        if (!$price_data)
        {
            $price_data = DB::table('product_attributes')->leftJoin('attribute_value_product_attribute', 'attribute_value_product_attribute.product_attribute_id', '=', 'product_attributes.id')
                ->leftJoin('attribute_values', 'attribute_values.id', '=', 'attribute_value_product_attribute.attribute_value_id')
                ->where('product_attributes.product_id', $product_id)->where('attribute_values.value', $quantity)->select('product_attributes.price')
                ->first();
        }
        return $price_data->price;
    }

    public function fetch_minimum_quantity($value, $search_array)
    {
        $min = 0;
        foreach ($search_array as $search)
        {
            if ($search > $value)
            {
                break;
            }
            $min = $search;
        }
        return $min;
    }

    public function fetch_maximum_quantity($value, $search_array)
    {
        $max = 0;
        foreach ($search_array as $search)
        {
            if ($search > $value)
            {
                $max = $search;
                break;
            }
        }
        return $max;
    }

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

    public function recievePayment($transaction_id, $amount)
    {
       
        $ch = curl_init();
        $elavon_user_name = config('elavon.key');
        $elavon_user_password = config('elavon.secret');
        $base_inc = base64_encode($elavon_user_name.':'.$elavon_user_password);
        $order_total = round($amount,2);
        //$amount = number_format($order_total * 100,2);
       $amount = $order_total * 100;
        $header = array();

        $header[] = 'Content-type: application/json';
        $header[] = 'Authorization: Basic ' . $base_inc;
        $payload = json_encode(array(
            "instructionType" => "release",
            "amount" => (int)$amount
        ));

        curl_setopt($ch, CURLOPT_URL, $this->elavonUrl."/api/v1/transactions/" . $transaction_id . "/instructions");
        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('release deffered payment');
        \Log::info(print_r($out,true));
        return $out;
    }
    
    public function handlePaymentSubmission(Request $request){
       
        $pares = $request->input('cres');
        $order_id = $request->input('threeDSSessionData');
        $elavon_user_name = config('elavon.key');
        $elavon_user_password = config('elavon.secret');
        $order_data = Order::find($order_id);
        $base_inc = base64_encode($elavon_user_name.':'.$elavon_user_password);
        $vendor_name = config('elavon.vendorName');
         $payment_payload = json_encode( array(
                "cRes"=> $pares
                

            ));
       
        $ch = curl_init();
        $header[] = 'Content-type: application/json';
        $header[] = 'Authorization: Basic '.$base_inc;
        curl_setopt($ch, CURLOPT_URL,$this->elavonUrl."/api/v1/transactions/".$order_data->transaction_id."/3d-secure-challenge");
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payment_payload);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
        $server_output_pay = curl_exec($ch);
        $serialized_result = json_decode($server_output_pay);
        \Log::info(print_r($serialized_result,true));
        if(isset($serialized_result->status) && $serialized_result->status == 'Ok'){
            $order_data->transaction_status = 'succeeded';
            $order_data->order_status_id = 1;
            $order_data->save();
            $order_data_product = OrderProduct::where('order_id', $order_id)
            ->first();
            $order_data_product->quantity = $order_data->fill_the_tank_quantity;
            $order_data_product->product_price = $order_data->total_products;
            $order_data_product->save();

            /* Start Send Invoice to Customer */
            $setting = WebsiteSetting::first();
            $address = DB::table('addresses')->where('id', $order_data->delivery_address_id)
                ->first();
            $data = ['order' => $order_data, 'products' => $order_data->products, 'customer' => $order_data->customer, 'courier' => $order_data->courier, 'address' => $address, 'status' => $order_data->orderStatus, 'payment' => $order_data->paymentMethod, 'setting' => $setting];

            $destinationPath = public_path() . '/invoices';
            if (!File::exists($destinationPath))
            {
                File::makeDirectory($destinationPath, $mode = 0777, true, true);
            }

            $pdfName = $request->order_id . '.pdf';
            $target = public_path('/invoices/') . $pdfName;
            $pdf = app()->make('dompdf.wrapper');
            $pdf->loadView('invoices.orders', $data);
            $pdf->save($target);
            $customer = $order_data->customer;
            $attachment = public_path('/invoices/' . $pdfName);

            $data = ["customer_name" => $customer->name, "order_date" => $order_data->created_at, "delevery_date" => $order_data->delevery_date, "final_amount" => $order_data->fill_the_tank_final_amount];
             /*Mail::send('emails.customer.emailInvoicetoCustomer', $data, function ($message) use ($customer, $order_data, $attachment) {
                    $message->from(config('constants.ADMIN_EMAIL'));
                    $message->to($customer->email,$customer->name)->subject('#'.$order_data->id.' Order Invoice');
                    $message->attach($attachment);
                    });*/
                    session(['session_receive_success_page' => 1]);

                    return redirect()
                        ->route('driver.capture.success')
                        ->with("success", "Payment charged to Credit Card Successfully");
        }else{
             session(['session_receive_failed_page' => 1]);
                    return redirect()
                        ->route('driver.capture.failed');
        }
    }
    
    public function deliver(Request $request){
        $order_data = Order::find($request->order_id);
        $order_data->order_status = 1;
                        $order_data->delivery_date = date("Y-m-d");
                        $order_data->completed_date = date('Y-m-d H:i:s');
                        $order_data->save();
        session(['session_receive_success_page' => 1]);
                        return redirect()
                            ->route('driver.capture.success')
                            ->with("success", "Order Delivered Successfully");
                        
    }
}


Spamworldpro Mini