<?php

namespace App\Http\Controllers\Payment;

use App\BasicExtra;
use App\Course;
use App\CoursePurchase;
use App\Language;
use App\PaymentGateway;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;
use Omnipay\Omnipay;
use App\Http\Controllers\Payment\PaymentController;
use App\Package;
use App\PackageOrder;
use App\Subscription;
use Illuminate\Support\Str;

class AuthorizeController extends PaymentController
{
    private $gateway;
    public function __construct()
    {
        $data = PaymentGateway::query()->whereKeyword('authorize.net')->first();
        $authorizeNetData = json_decode($data->information, true);
        $this->gateway = Omnipay::create('AuthorizeNetApi_Api');
        $this->gateway->setAuthName($authorizeNetData['login_id']);
        $this->gateway->setTransactionKey($authorizeNetData['transaction_key']);
        if ($authorizeNetData['sandbox_check'] == 1) {
            $this->gateway->setTestMode(true);
        }
    }
    public function paymentProcess(Request $request)
    {
        try {

            Log::info($request->all());

            // Validation Starts

            if (session()->has('lang')) {
                $currentLang = Language::where('code', session()->get('lang'))->first();
            } else {
                $currentLang = Language::where('is_default', 1)->first();
            }

            $bex = $currentLang->basic_extra;
            $be = $currentLang->basic_extended;


            $available_currency = array('USD', 'CAD', 'CHF', 'DKK', 'EUR', 'GBP', 'NOK', 'PLN', 'SEK', 'AUD', 'NZD');

            // checking whether the base currency is allowed or not
            if (!in_array($bex->base_currency_text, $available_currency)) {
                return redirect()->back()->with('error', __('Invalid Currency For authorize.net Payment.'));
            }

            $package_inputs = $currentLang->package_inputs;

            $this->orderValidation($request, $package_inputs);
            // Validation Ends


            // saving datas in database
            $po = $this->saveOrder($request, $package_inputs, 0);

            $package = Package::findOrFail($request->package_id);


            $cancel_url = route('front.payment.cancle', $package->id);



            if ($request->filled('opaqueDataValue') && $request->filled('opaqueDataDescriptor')) {
                // generate a unique merchant site transaction ID
                $transactionId = rand(100000000, 999999999);
                $response = $this->gateway->authorize([
                    'amount' => sprintf('%0.2f', $package->price),
                    'currency' => $bex->base_currency_text,
                    'transactionId' => $transactionId,
                    'opaqueDataDescriptor' => $request->opaqueDataDescriptor,
                    'opaqueDataValue' => $request->opaqueDataValue
                ])->send();

                if ($response->isSuccessful()) {
                    //success process will be go here

                    $order['item_name'] = $package->title . " Order";
                    $order['item_number'] = Str::random(4) . time();
                    $order['item_amount'] = $package->price;
                    $order['order_id'] = $po->id;
                    $order['package_id'] = $package->id;

                    $success_url = route('front.packageorder.confirmation', [$package->id, $po->id]);


                    $bex = BasicExtra::first();
                    if ($bex->recurring_billing == 1) {
                        $sub = Subscription::find($po->id);
                        $package = Package::find($package->id);
                        $po = $this->subFinalize($sub, $package);
                    } else {
                        $po = PackageOrder::findOrFail($po->id);
                        $po->payment_status = 1;
                        $po->save();
                    }

                    // sending mails
                    $this->sendMails($po, $be, $bex);

                    Session::forget('order_payment_id');
                    Session::forget('order_data');


                    return redirect()->route('front.packageorder.confirmation', [$package->id, $po->id]);
                } else {
                    //cancel payment
                    return redirect($cancel_url);
                }
            } else {
                //return cancel url 
                return redirect($cancel_url);
            }
        } catch (\Exception $th) {
            Log::error('Authorize.net payment error: ' . $th->getMessage());
            return redirect()->back()->with('error', __('Payment failed. ' . $th->getMessage()))->withInput();
        }
    }

    public function cancelPayment()
    {
        $requestData = Session::get('request');
        session()->flash('warning', __('Payment Canceled'));

        return redirect()->route('vendor.plan.extend.checkout', ['package_id' => $requestData['package_id']])->withInput($requestData);
    }
}
