<?php

namespace App\Http\Controllers\Payment\causes;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Front\CausesController;
use App\Http\Controllers\Front\EventController;
use App\Language;
use App\PaymentGateway;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Omnipay\Omnipay;

class AuthorizeController extends Controller
{
    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, $amount, $item_number)
    {
        // try {
        $cancel_url = route('course.paypal.cancel');

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

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



        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', $amount),
                'currency' => $bex->base_currency_text,
                'transactionId' => $transactionId,
                'opaqueDataDescriptor' => $request->opaqueDataDescriptor,
                'opaqueDataValue' => $request->opaqueDataValue
            ])->send();

            if ($response->isSuccessful()) {
                //success process will be go here
                $paymentFor = Session::get('paymentFor');
                $response = json_encode($response, true);
                $transaction_details = null;
                if ($paymentFor == "Cause") {

                    $cause = new CausesController;
                    $donation = $cause->store($request, $item_number, $transaction_details, $amount, $bex);
                    $file_name = $cause->makeInvoice($donation);
                    $cause->sendMailPHPMailer($request, $file_name, $be);
                    session()->flash('success', 'Payment completed!');
                    Session::forget('success_url');
                    Session::forget('cancel_url');
                    Session::forget('request');
                    Session::forget('paymentFor');
                    return [
                        'status' => 'success',
                        'url' => route('front.cause_details', [$request["donation_slug"]])
                    ];
                } elseif ($paymentFor == "Event") {
                    $amount = $request["total_cost"];
                    $event = new EventController;
                    $event_details = $event->store($request, $item_number, $transaction_details, $amount, $bex);
                    $file_name = $event->makeInvoice($event_details);
                    $event->sendMailPHPMailer($request, $file_name, $be);


                    return redirect()->route('front.event_details', [$request["event_slug"]]);
                }
            } 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($cancel_url);
        // }
    }

    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);
    }
}
