<?php

namespace twa\omnipay\controllers;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use twa\ecomcart\models\EcomPurchasesAttemptModel;

class BenefitController
{
    public $data;

    public $provider;

    public function __construct($data, $provider)
    {
        $this->provider = $provider;

        $required_data = ['resource_path'];
        \twa\omnipay\controllers\GeneralFunctions::checkRequiredData($data, $required_data);
        $this->data = collect($data);
    }

    public function getSession()
    {
        return true;
    }

    public function createPayment($id, $value, $currency, $customer_name, $customer_email, $url_success, $url_cancel)
    {
        $myObj = new \twa\omnipay\repositories\benefit\iPayBenefitPipe();

        // Do NOT change the values of the following parameters at all.
        $myObj->setAction('1');
        $myObj->setCurrency('048');
        $myObj->setLanguage('USA');
        $myObj->setType('D');

        // modify the following to reflect your "Alias Name", "resource.cgn" file path, "keystore.pooh" file path.
        $myObj->setAlias('test');

        $myObj->setResourcePath(base_path().$this->data['resource_path']); //only the path that contains the file; do not write the file name
        $myObj->setKeystorePath(base_path().$this->data['resource_path']); //only the path that contains the file; do not write the file name

        // modify the following to reflect your pages URLs
        $myObj->setResponseURL(env('APP_URL').'/omnipay/benefit/response/'.session('login')['token'].'/'.$id);
        $myObj->setErrorURL($url_cancel);

        // set a unique track ID for each transaction so you can use it later to match transaction response and identify transactions in your system and “BENEFIT Payment Gateway” portal.
        $myObj->setTrackId($id);

        // set transaction amount
        $myObj->setAmt($value);


        if (trim($myObj->performPaymentInitializationHTTP()) != 0) {
            echo 'ERROR OCCURED! SEE CONSOLE FOR MORE DETAILS';

            return;
        } else {
            $url = $myObj->getwebAddress();

            return collect(['redirect' => ['link' => $url]]);
        }
    }

    public static function redirectToCheckPayment($token , $paid){
        if(request()->input("trandata")){
            echo "REDIRECT=".env("APP_URL")."/omnipay/response/unknown/".$paid."?t=".$token."&tdata=".request()->input("trandata");
        }else{
            dd(request()->all());
        }
    }


    public function checkPayment()
    {
        $myObj = new \twa\omnipay\repositories\benefit\iPayBenefitPipe();

        // modify the following to reflect your "Alias Name", "resource.cgn" file path, "keystore.pooh" file path.
        $myObj->setAlias('test');
        $myObj->setResourcePath(base_path().$this->data['resource_path']); //only the path that contains the file; do not write the file name
        $myObj->setKeystorePath(base_path().$this->data['resource_path']); //only the path that contains the file; do not write the file name

        $trandata = "";
        $paymentID = "";
        $result = "";
        $responseCode = "";
        $response = "";
        $transactionID = "";
        $referenceID = "";
        $trackID = "";
        $amount = "";
        $UDF1 = "";
        $UDF2 = "";
        $UDF3 = "";
        $UDF4 = "";
        $UDF5 = "";
        $authCode = "";
        $postDate = "";
        $errorCode = "";
        $errorText = "";

        $trandata = request()->input('tdata');

        if ($trandata != "")
        {
            $returnValue = $myObj->parseEncryptedRequest($trandata);
            if ($returnValue == 0)
            {
                $paymentID = $myObj->getPaymentId();
                $result = $myObj->getresult();
                $responseCode = $myObj->getAuthRespCode();
                $transactionID = $myObj->getTransId();
                $referenceID = $myObj->getRef();
                $trackID = $myObj->getTrackId();
                $amount = $myObj->getAmt();
                $UDF1 = $myObj->getUdf1();
                $UDF2 = $myObj->getUdf2();
                $UDF3 = $myObj->getUdf3();
                $UDF4 = $myObj->getUdf4();
                $UDF5 = $myObj->getUdf5();
                $authCode = $myObj->getAuth();
                $postDate = $myObj->getDate();
                $errorCode = $myObj->getError();
                $errorText = $myObj->getError_text();

            }
            else
            {
                $errorText = $myObj->getError_text();
            }
        }
        else if (isset($_POST["ErrorText"]))
        {
            $paymentID = $_POST["paymentid"];
            $trackID = $_POST["trackid"];
            $amount = $_POST["amt"];
            $UDF1 = $_POST["udf1"];
            $UDF2 = $_POST["udf2"];
            $UDF3 = $_POST["udf3"];
            $UDF4 = $_POST["udf4"];
            $UDF5 = $_POST["udf5"];
            $errorText = $_POST["ErrorText"];
        }
        else
        {
            $errorText = "Unknown Exception";
        }


        // Remove any HTML/CSS/javascrip from the page. Also, you MUST NOT write anything on the page EXCEPT the word "REDIRECT=" (in upper-case only) followed by a URL.
        // If anything else is written on the page then you will not be able to complete the process.
        if ($myObj->getResult() == "CAPTURED")
        {
            return response(['status' => 'success', 'response' => $myObj->getResult()], 200);
        }
        else if ($myObj->getResult() == "NOT CAPTURED" || $myObj->getResult() == "CANCELED" || $myObj->getResult() == "DENIED BY RISK" || $myObj->getResult() == "HOST TIMEOUT")
        {
            if ($myObj->getResult() == "NOT CAPTURED")
            {
                switch ($myObj->getAuthRespCode())
                {
                    case "05":
                        $response = "Please contact issuer";
                        break;
                    case "14":
                        $response = "Invalid card number";
                        break;
                    case "33":
                        $response = "Expired card";
                        break;
                    case "36":
                        $response = "Restricted card";
                        break;
                    case "38":
                        $response = "Allowable PIN tries exceeded";
                        break;
                    case "51":
                        $response = "Insufficient funds";
                        break;
                    case "54":
                        $response = "Expired card";
                        break;
                    case "55":
                        $response = "Incorrect PIN";
                        break;
                    case "61":
                        $response = "Exceeds withdrawal amount limit";
                        break;
                    case "62":
                        $response = "Restricted Card";
                        break;
                    case "65":
                        $response = "Exceeds withdrawal frequency limit";
                        break;
                    case "75":
                        $response = "Allowable number PIN tries exceeded";
                        break;
                    case "76":
                        $response = "Ineligible account";
                        break;
                    case "78":
                        $response = "Refer to Issuer";
                        break;
                    case "91":
                        $response = "Issuer is inoperative";
                        break;
                    default:
                        // for unlisted values, please generate a proper user-friendly message
                        $response = "Unable to process transaction temporarily. Try again later or try using another card.";
                        break;
                }
            }
            else if ($myObj->getResult() == "CANCELED")
            {
                $response = "Transaction was canceled by user.";
            }
            else if ($myObj->getResult() == "DENIED BY RISK")
            {
                $response = "Maximum number of transactions has exceeded the daily limit.";
            }
            else if ($myObj->getResult() == "HOST TIMEOUT")
            {
                $response = "Unable to process transaction temporarily. Try again later.";
            }
            return response(['status' => 'fail', 'response' => $response], 400);
        }
        else
        {
            //Unable to process transaction temporarily. Try again later or try using another card.
            return response(['status' => 'fail', 'response' => "Unable to process transaction temporarily. Try again later or try using another card"], 400);
        }
    }
}
