<?php

namespace App\Http\Controllers\Payment\product;

use App\Http\Controllers\Controller;
use App\Language;
use App\PaymentGateway;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;
use Omnipay\Omnipay;
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 {
            $cancel_url = route('product.payment.cancle');
            $success_url = action('Payment\product\PaymentController@payreturn');

            if (!Session::has('cart')) {
                return view('errors.404');
            }
            $available_currency = array('USD', 'CAD', 'CHF', 'DKK', 'EUR', 'GBP', 'NOK', 'PLN', 'SEK', 'AUD', 'NZD');

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

            $bex = $currentLang->basic_extra;
            $bs = $currentLang->basic_setting;

            if (!in_array($bex->base_currency_text, $available_currency)) {
                return redirect()->back()->with('error', __('Invalid Currency For Flutterwave.'));
            }

            $total = $this->orderTotal($request->shipping_charge);

            if ($this->orderValidation($request)) {
                return $this->orderValidation($request);
            }


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

                if ($response->isSuccessful()) {
                    $txnId = 'txn_' . Str::random(8) . time();
                    $chargeId = 'ch_' . Str::random(9) . time();
                    $order = $this->saveOrder($request, $txnId, $chargeId, 'Completed');
                    $order_id = $order->id;

                    $this->saveOrderedItems($order_id);

                    $orderData['item_name'] = $bs->website_title . " Order";
                    $orderData['item_number'] = Str::random(4) . time();
                    $orderData['item_amount'] = $total;
                    $orderData['order_id'] = $order_id;


                    Session::forget('cart');
                    return redirect($success_url);
                } 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);
    }
}
