<?php
require_once './config/db_config.php';
require_once './sdk/payGate/paygate.payweb3.php';
require_once './sdk/payGate/global.inc.php';

class PayGatePaymentGateway
{
    public $domainURL;
    public $payWeb3;
    public function __construct()
    {
        $this->domainURL = domainURL;
        $this->payWeb3 = new PayGate_PayWeb3();
    }

    public function createOrder($data)
    {
        
        $gatewayJson = json_decode($data['gatewayConfig'], true);
        $paygateId = $gatewayJson['paygateId'];
        $encryptionKey = $gatewayJson['encryptionKey'];
        $currencyCode = $gatewayJson['currencyCode'];
        $reference = $gatewayJson['reference'];        
        $country = $gatewayJson['country'];        
        $fields = [
            'PAYGATE_ID'       => $paygateId,
            'REFERENCE'        => $reference,
            'AMOUNT'           => $data['amount'] * 100,
            'CURRENCY'         => $currencyCode,
            'RETURN_URL'       => $this->domainURL.'/paymentResponse.php?payGateReference='.$reference,
            'TRANSACTION_DATE' => date('Y-m-d H:i:s'),
            'LOCALE'           => 'en-za',
            'COUNTRY' => array_key_exists($country, generateCountrySelectOptions()) ? $country : 'ZAF',
            'EMAIL'            => $data['email'],
        ];       
        $this->payWeb3->setDebug(true);
        $this->payWeb3->setEncryptionKey($encryptionKey);
        $this->payWeb3->setInitiateRequest($fields);
        $result = $this->payWeb3->doInitiate();    
        if (!$result || $result === false) {
            return [
                'status' => 'ERROR',
                'description' => $this->payWeb3->lastError ?? 'Initiate request failed (check PayGate logs or network)'
            ];
        }
        $response = $this->payWeb3->initiateResponse;
        $isValid = $this->payWeb3->validateChecksum($response);
        if (!$isValid) {
            return [
                'status'=>'ERROR',
                'description'=> "Invalid Checksum"
            ];            
        }
        
        if (!empty($response['ERROR'])) {
            return [
                'status'=>'ERROR',
                'description'=> $response['ERROR']
            ];           
        }      
        
        return [
            'status'=>'SUCCESS',
            'PAY_REQUEST_ID' => $response['PAY_REQUEST_ID'],
            'REFERENCE'      => $response['REFERENCE'],
            'CHECKSUM'       => $response['CHECKSUM'],
            'action_url'     => PayGate_PayWeb3::$process_url,
            'form_fields'    => [
                'PAY_REQUEST_ID' => $response['PAY_REQUEST_ID'],
                'CHECKSUM'       => $response['CHECKSUM'],
            ]
        ];
    }

    public function fetchOrder($data)
    {
        $gatewayJson = json_decode($data['gatewayConfig'], true);
        $paymentJson = json_decode($data['paymentRequest'], true);

        if(!isset($gatewayJson) || empty($gatewayJson) || !isset($paymentJson) || empty($paymentJson))
        {
            return [
                'Status' => 'Error, empty payment table',
                'txnID' => null,
                'txnStatus' => null,
                'reference' => null,
                'jsonResponse'=> null
            ];
        }
        // Extract required fields
        $paygateId = $gatewayJson['paygateId'];
        $encryptionKey = $gatewayJson['encryptionKey'];
        $payRequestId = $paymentJson['PAY_REQUEST_ID'];
        $reference = $paymentJson['REFERENCE'];
        

        // Prepare data for checksum
        $data = array(
            'PAYGATE_ID' => $paygateId,
            'PAY_REQUEST_ID' => $payRequestId,
            'REFERENCE' => $reference
        );
    
        // Generate checksum
        $checksum = md5(implode('', $data) . $encryptionKey);
        $data['CHECKSUM'] = $checksum;
 
        $fieldsString = http_build_query($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://secure.paygate.co.za/payweb3/query.trans');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldsString);
        curl_setopt($ch, CURLOPT_REFERER, $_SERVER['HTTP_HOST']);
        $result = curl_exec($ch);
        curl_close($ch);
    
        // Parse response
        $paymentResponse = array();
        if ($result) {
            $resultArr = explode('&', $result);
            foreach ($resultArr as $value) {
                $resultNew = explode('=', $value);
                if (count($resultNew) == 2) {
                    $paymentResponse[$resultNew[0]] = $resultNew[1];
                }
            }
        }
        if (isset($paymentResponse['ERROR'])) {
            return [
                'Status' => 'error',
                'txnID' => null,
                'txnStatus' => null,
                'reference' => $reference,
                'jsonResponse'=> $paymentResponse
            ];
        }
    
        // Map transaction status
        $txnStatusMap = [
            1 => 'Approved',
            2 => 'Declined',
            0 => 'Declined',
            4 => 'Cancelled'
        ];
        $txnStatus = isset($paymentResponse['TRANSACTION_STATUS']) 
            ? ($txnStatusMap[$paymentResponse['TRANSACTION_STATUS']] ?? 'Unknown')
            : 'Unknown';
        return [
            'Status' => 'success',
            'txnID' => $paymentResponse['TRANSACTION_ID'] ?? null,
            'txnStatus' => $txnStatus,
            'reference' => $paymentResponse['REFERENCE'] ?? $reference,
            'jsonResponse'=> $paymentResponse
        ];
    }
}