<?php

namespace twa\omnipay\controllers;

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

class PaypalProController
{
    private $data;

    private $provider;

    public function __construct($data, $provider)
    {
        $this->provider = $provider;
        $required_data = [
            'apiUsername' , 'apiPassword' , 'apiSignature' , 'apiEndpoint' , 'version'
        ];

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

    public function createPayment($id, $value, $currency, $customer_name = null, $customer_email = null, $url_success = null, $url_cancel = null ,  $creditCard = null)
    {
        return collect(['redirect' => ['link' => env('APP_URL').'/omnipay/response/unknown/'.$id  ] , 'response' => [
            'amount' => $value,
            'currency' => $currency,
            'url_success' => $url_success,
            'url_fail' => $url_cancel
        ]]);
    }

    public function checkPayment($id)
    {

        $attempt = \twa\ecomcart\models\EcomPurchasesAttemptModel::find($id);
        if (! $attempt) {
            return response(['status' => 'fail', 'response' => false ], 400);
        }

        $init = json_decode($attempt->gateway_init , 1);
        $response = $init["response"];

        $creditCard = session("credit_card");
        session(["credit_card" => false ]);

        if(
            !isset($creditCard["name"]) ||
            !isset($creditCard["exp"]) ||
            !isset($creditCard["number"]) ||
            !isset($creditCard["cvv"]) ||
            !isset($creditCard["type"])

        ){
            return response(['status' => 'fail', 'response' => false ], 400);
        }


        if(!$creditCard){
            return response(['status' => 'fail', 'response' => false ], 400);
        }

        $month_year_array = explode('/' , $creditCard['exp']);
        if(!isset($month_year_array[0]) || !isset($month_year_array[1])){
            return response(['status' => 'fail', 'response' => "" ], 400);
        }


        $creditCard['exp_month'] = $month_year_array[0];
        $creditCard['exp_year'] = $month_year_array[1];

        $nameArr = explode(" ", $creditCard["name"]);
        if(!isset($nameArr[0]) || !isset($nameArr[1])){
            return response(['status' => 'fail', 'response' => "" ], 400);
        }

        $firstName = !empty($nameArr[0]) ? $nameArr[0] : '';
        $lastName = !empty($nameArr[1]) ? $nameArr[1] : '';

        $request_params = [
            'METHOD' => 'DoDirectPayment',
            'USER' => $this->data["apiUsername"],
            'PWD' => $this->data["apiPassword"],
            'SIGNATURE' => $this->data["apiSignature"],
            'VERSION' => $this->data["version"],
            'PAYMENTACTION' => 'Sale',
            'IPADDRESS' => request()->ip(),
            'CREDITCARDTYPE' => $creditCard["type"],
            'ACCT' => str_replace( [" "] , [""] , $creditCard["number"]),
            'EXPDATE' => $creditCard["exp_month"].'20'.$creditCard['exp_year'],
            'CVV2' => $creditCard["cvv"],
            'FIRSTNAME' => $firstName,
            'LASTNAME' => $lastName,
            'AMT' => $response['amount'],
            'CURRENCYCODE' => $response['currency'],
            'INVNUM' => $attempt->id
        ];

        $nvp_string = '';
        foreach($request_params as $var=>$val)
        {
            $nvp_string .= '&'.$var.'='.urlencode($val);
        }

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_VERBOSE, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_URL, $this->data['apiEndpoint']);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $nvp_string);

        $result = curl_exec($curl);
        curl_close($curl);

        $nvp_response_array = $this->NVPToArray($result);

        if(isset($nvp_response_array["ACK"]) && strtolower($nvp_response_array["ACK"] ) == "success"){
            return response(['status' => 'success', 'response' => $nvp_response_array ], 200);
        }else{
            return response(['status' => 'fail', 'response' => $nvp_response_array ], 400);
        }

    }

    public function NVPToArray($NVPString)
    {
        $proArray = array();
        while(strlen($NVPString))
        {
            // name
            $keypos= strpos($NVPString,'=');
            $keyval = substr($NVPString,0,$keypos);
            // value
            $valuepos = strpos($NVPString,'&') ? strpos($NVPString,'&'): strlen($NVPString);
            $valval = substr($NVPString,$keypos+1,$valuepos-$keypos-1);
            // decoding the respose
            $proArray[$keyval] = urldecode($valval);
            $NVPString = substr($NVPString,$valuepos+1,strlen($NVPString));
        }
        return $proArray;
    }

}
