<?php

namespace App\Http\Controllers\Frontend;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use net\authorize\api\contract\v1 as AnetAPI;
use net\authorize\api\controller as AnetController;
use App\Http\Authorize_payment_gateway\Autoload;
use App\Http\Authorize_payment_gateway\Constants;
use Auth;
use DB;
use App\Models\Superadmin\Plans\Plans;

class AuthorizenetController extends Controller
{
    public function __construct()
    {

    }

    function Card(Request $request)
    {
        $plan_id = $request->plan_id;

        $user = Auth::user();

        if ($user) {
            $user_f_name = $user->first_name;
            $user_l_name = $user->last_name;
            $user_email = $user->email;
        }
        else{
            $last = DB::table('users')->latest()->first();
            $last_f_name = $last->first_name;
            $last_l_name = $last->last_name;
            $last_email = $last->email;
        }

        /* Create a merchantAuthenticationType object with authentication details

           retrieved from the constants file */
        $authorize_login= DB::table('dx_settings')->where('key','general.paymentgateway_api_login_id')->first();
        $authorize_trans_key= DB::table('dx_settings')->where('key','general.paymentgateway_transaction_key')->first();
        $merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
        $merchantAuthentication->setName($authorize_login);
        $merchantAuthentication->setTransactionKey($authorize_trans_key);

        // Set the transaction's refId
        $refId = 'ref' . time();

        // Create the payment data for a credit card
        $creditCard = new AnetAPI\CreditCardType();
        $creditCard->setCardNumber($request->card_no);
        $creditCard->setExpirationDate($request->exp_date);
        $creditCard->setCardCode($request->card_code);

        // Add the payment data to a paymentType object
        $paymentOne = new AnetAPI\PaymentType();
        $paymentOne->setCreditCard($creditCard);

        // Create order information
        $order = new AnetAPI\OrderType();
        $order->setInvoiceNumber(mt_rand(10000, 99999)); //generate random invoice number
        $order->setDescription('Test Plugin');

        // Set the customer's Bill To address

        $customerAddress = new AnetAPI\CustomerAddressType();
        if ($user){
            $customerAddress->setFirstName($user_f_name);
            $customerAddress->setLastName($user_l_name);
        }
        else{
            $customerAddress->setFirstName($last_f_name);
            $customerAddress->setLastName($last_l_name);
        }

        $customerAddress->setAddress('101 main street');
        $customerAddress->setCity('Pecan Springs');
        $customerAddress->setState('TX');
        $customerAddress->setZip($request->zip);
        $customerAddress->setCountry('USA');

        // Set the customer's identifying information
        $customerData = new AnetAPI\CustomerDataType();
        $customerData->setType("individual");
        $customerData->setId(mt_rand(10000, 99999)); //try to set unique id here
        if ($user){
            $customerData->setEmail($user_email);
        }
        else{
            $customerData->setEmail($last_email);
        }

        // Create a TransactionRequestType object and add the previous objects to it
        $transactionRequestType = new AnetAPI\TransactionRequestType();
        $transactionRequestType->setTransactionType("authCaptureTransaction");
        $transactionRequestType->setAmount($request->amount);
        $transactionRequestType->setOrder($order);
        $transactionRequestType->setPayment($paymentOne);
        $transactionRequestType->setBillTo($customerAddress);
        $transactionRequestType->setCustomer($customerData);

        // Assemble the complete transaction request
        $request = new AnetAPI\CreateTransactionRequest();
        $request->setMerchantAuthentication($merchantAuthentication);
        $request->setRefId($refId);
        $request->setTransactionRequest($transactionRequestType);
        // Create the controller and get the response
        $controller = new AnetController\CreateTransactionController($request);
        $response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);

        if ($response != null)
        {
            // Check to see if the API request was successfully received and acted upon

            if ($response->getMessages()->getResultCode() == 'Ok')
            {
                // Since the API request was successful, look for a transaction response

                // and parse it to display the results of authorizing the card

                $tresponse = $response->getTransactionResponse();
                if ($tresponse != null && $tresponse->getMessages() != null)
                {
                    $user = Auth::user();
                    if ($user)
                    {
                        $check = DB::table('user_customer_details')->where('user_id', $user->id)->first();
                        if ($check==NULL)
                        {
                                $last = DB::table('users')->latest()->first();
                                $plan = Plans::where('id', $last->plan_id)->first();
                                $values = array('user_id'=>$last->id,'plan_id' => $plan->id,'sms_limit' => $plan->smslimit,
                                'plan_price'=>$plan->price,'plan_expiration'=>$plan->expiry,'verification_code' => 1,
                                'no_allowed_task'=>$plan->allowedtask,'no_allowed_driver'=>$plan->drivercount);
                                DB::table('user_customer_details')->insert($values);
                                return redirect()->route('frontend.thankyou');
                        }
                        else
                        {

                                $plan = Plans::where('id', $plan_id)->first();
                                DB::table('user_customer_details')->where('user_id', $user->id)->update
                                (['plan_id' => $plan->id, 'sms_limit' => $plan->smslimit,
                                'plan_price' => $plan->price, 'plan_expiration' => $plan->expiry, 'verification_code' => 1,
                                'no_allowed_task' => $plan->allowedtask,
                                'no_allowed_driver' => $plan->drivercount]);
                                return redirect()->route('frontend.thankyou');
                         }
                    }
                    else
                    {
                                    $last = DB::table('users')->latest()->first();
                                    $plan = Plans::where('id', $last->plan_id)->first();
                                    $values = array('user_id'=>$last->id,'plan_id' => $plan->id,'sms_limit' => $plan->smslimit,
                                    'plan_price'=>$plan->price,'plan_expiration'=>$plan->expiry,'verification_code' => 1,
                                    'no_allowed_task'=>$plan->allowedtask,'no_allowed_driver'=>$plan->drivercount);
                                    DB::table('user_customer_details')->insert($values);
                                    return redirect()->route('frontend.thankyou');
                    }
                }
                else
                {
                                    return back()->withInput()->withFlashSuccess(trans('Transaction Failed'));
                }

                    // Or, print errors if the API request wasn't successful

            }
            else
            {
                                    return back()->withInput()->withFlashSuccess(trans('Card No is Invalid'));
            }

        }
        else
        {

                                    return back()->withInput()->withFlashSuccess(trans('No response returned'));
        }
//                                    return $response;
    }

}