<?php

namespace App\Http\Controllers\Payment\Course;

use App\Course;
use App\CoursePurchase;
use App\Http\Controllers\Controller;
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;

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)
    {
        try {
            $cancel_url = route('course.paypal.cancel');
            $course = Course::findOrFail($request->course_id);
            if (!Auth::user()) {
                Session::put('link', route('course_details', ['slug' => $course->slug]));
                return redirect()->route('user.login');
            }

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

            $bse = $currentLang->basic_extra;

            $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($bse->base_currency_text, $available_currency)) {
                return redirect()->back()->with('error', __('Invalid Currency For authorize.net Payment.'));
            }

            Session::put('request', $request->all());

            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', $course->current_price),
                    'currency' => $bse->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);

                    // storing course purchase information in database
                    $course_purchase = new CoursePurchase();
                    $course_purchase->user_id = Auth::user()->id;
                    $course_purchase->order_number = rand(100, 500) . time();
                    $course_purchase->first_name = Auth::user()->fname;
                    $course_purchase->last_name = Auth::user()->lname;
                    $course_purchase->email = Auth::user()->email;
                    $course_purchase->course_id = $course->id;
                    $course_purchase->currency_code = $bse->base_currency_text;
                    $course_purchase->current_price = $course->current_price;
                    $course_purchase->previous_price = $course->previous_price;
                    $course_purchase->payment_method = 'Authorized.net';
                    $course_purchase->payment_status = 'Completed';
                    $course_purchase->save();

                    // generate an invoice in pdf format
                    $fileName = $course_purchase->order_number . '.pdf';
                    $directory = 'assets/front/invoices/course/';
                    @mkdir($directory, 0775, true);
                    $fileLocated = $directory . $fileName;
                    $order_info = $course_purchase;
                    Pdf::loadView('pdf.course', compact('order_info', 'logo', 'bse'))
                        ->setPaper('a4', 'landscape')->save($fileLocated);

                    // store invoice in database
                    $course_purchase->update([
                        'invoice' => $fileName
                    ]);

                    // send a mail to the buyer with an invoice
                    MailController::sendMail($course_purchase);

                    Session::forget('courseData');
                    Session::forget('currency');
                    Session::forget('paymentId');

                    return redirect()->route('course.paypal.complete');
                } 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);
    }
}
