<?php
require_once "./config/db_config.php";
include "./sdk/ccaveneue/Crypto.php";

class CCAveneuePaymentGateway
{
    public $domainURL;
    public function __construct()
    {
        $this->domainURL = domainURL;
    }

    private function generateForm($encrypted_data, $access_code, $environment)
    {
        return '
        <form method="post" name="redirect" action="' . $environment . '">
            <input type="hidden" name="encRequest" value="' . htmlspecialchars($encrypted_data) . '">
            <input type="hidden" name="access_code" value="' . htmlspecialchars($access_code) . '">
        </form>
    ';
    }

    public function createOrder($data)
    {
        $gatewayJson  = json_decode($data['gatewayConfig'], true);
        $working_key  = $gatewayJson['workingKey'];
        $access_code  = $gatewayJson['accessCode'];
        $environment  = $gatewayJson['paymentURL'];
        $merchant_id  = $gatewayJson['merchantId'];
        $currencyCode = $gatewayJson['currencyCode'];
        $language     = isset($gatewayJson['language']) ? $gatewayJson['language'] : 'EN';
        if (isset($data['studentCode'])) {
            $data['code'] = $data['studentCode'];
        }
        $student_id                 = isset($data['code']) ? $data['code'] : '';
        $merchantReference          = $student_id . "_" . $data['name'];
        $payload                    = [];
        $payload['tid']             = time();
        $payload['currency']        = $currencyCode;
        $payload['merchant_param1'] = $merchantReference;
        $payload['language']        = $language;
        $payload['redirect_url']    = $this->domainURL . '/paymentResponse.php';
        $payload['cancel_url']      = $this->domainURL . '/paymentResponse.php';
        $payload['merchant_id']     = $merchant_id;
        $payload['access_code']     = $access_code;
        $payload['working_key']     = $working_key;
        $payload['environment']     = $environment;
        $payload['order_id']        = $data['txnId'];
        $payload['amount']          = $data['amount'];

        $encodeRequest = json_encode($$payload);

        foreach ($payload as $key => $value) {
            $merchant_data .= $key . '=' . $value . '&';

        }

        $encrypted_data = encrypt($merchant_data, $working_key); // Method for encrypting the data.

        $decryptValues = ['merchant' => $merchant_data, 'merchant1' => $encrypted_data];

        return [

            'encryptedData' => $encrypted_data,
            'decryptedData' => $decryptValues,
            'form'          => $this->generateForm($encrypted_data, $access_code, $environment),

        ];

    }

    public function fetchOrder($data)
    {       
        $gatewayJson = json_decode($data['gatewayConfig'], true);
        $working_key = $gatewayJson['workingKey'];
        $access_code = $gatewayJson['accessCode'];
        $environment = $gatewayJson['orderStatusURL'];
        $merchant_id = $gatewayJson['merchantId'];

        $merchant_json_data = [
            'order_no' => $data['txnId'],
        ];

        $merchant_data  = json_encode($merchant_json_data);
        $encrypted_data = encrypt($merchant_data, $working_key);
        $final_data     = 'access_code=' . $access_code . '&command=orderStatusTracker&request_type=JSON&response_type=JSON&version=1.2&enc_request=' . $encrypted_data;
        $ch             = curl_init();
        curl_setopt($ch, CURLOPT_URL, $environment);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $final_data);
        $result = curl_exec($ch);
        curl_close($ch);
        $status      = '';
        $information = explode('&', $result);

        $dataSize = sizeof($information);
        for ($i = 0; $i < $dataSize; $i++) {
            $info_value = explode('=', $information[$i]);
            if ($info_value[0] == 'enc_response') {
                $status = decrypt(trim($info_value[1]), $working_key);
            }
        }
        $obj      = json_decode($status , true);        
        $response = [
            "status"         => "UNKNOWN",
            "originalStatus" => $obj['order_status'] ?? '',
            "txnId"          => $obj['order_no'] ?? '',            
            "jsonResponse"   => $obj,
        ];        
        // Wrong transaction (error response from gateway)
        if (isset($obj['error_code']) && $obj['error_code'] != "") {
            $response['status'] = "ERROR";
            $response['error']  = $obj['error_desc'] ?? "Unknown error";
        }
        // Success case
        elseif (isset($obj['order_status']) && in_array(strtolower($obj['order_status']), ["shipped", "success","successful"])) {
            $response['status'] = "SUCCESS";
        }
        // Failure case
        elseif (isset($obj['order_status']) && in_array(strtolower($obj['order_status']), ["aborted", "unsuccessful", "timeout","invalid","failure"])) {
            $response['status'] = "FAILURE";
        }        
        return $response;

    }

}
