<?php
require_once "./config/db_config.php";
class MIPSPaymentGateway
{
    public $domainURL;
    public function __construct()
    {
        $this->domainURL = domainURL;
    }

    public function createOrder($data)
    {
        // Decode and validate gateway configuration
        $gatewayJson = json_decode($data['gatewayConfig'], true);
        
        $requiredKeys = ['merchantID', 'entityID', 'operatorID', 'operatorPassword', 'username', 'password', 'environment'];
        foreach ($requiredKeys as $key) {
            if (empty($gatewayJson[$key])) {
                return ['status' => 'ERROR', 'message' => "Missing required gateway parameter: $key"];
            }
        }
    
        // Assign necessary variables
        $merchantID = $gatewayJson['merchantID'];
        $entityID = $gatewayJson['entityID'];
        $operatorID = $gatewayJson['operatorID'];
        $operatorPassword = $gatewayJson['operatorPassword'];
        $username = $gatewayJson['username'];
        $password = $gatewayJson['password'];
        $environment = $gatewayJson['environment'];
        $clinetOrderId = $data['txnId'] ?? ''; // Ensure txnId exists
        $amount = $data['amount'] ?? '0.00'; // Default to zero if missing
        $currency = $data['currency'];
        $customerName = $data['name'] ?? 'N/A'; // Default value for name
        $studentCode = isset($data['code']) ? $data['code'] : $data['studentCode'] ;
        // Authorization header
        $authHeader = 'Authorization: Basic ' . base64_encode("$username:$password");
    
        // API URL
        $apiUrl = rtrim($environment, '/') . '/api/load_payment_zone';
    
        // Request payload
        $payload = json_encode([
            "authentify" => [
                "id_merchant" => $merchantID,
                "id_entity" => $entityID,
                "id_operator" => $operatorID, // Fixed: Was using $entityID incorrectly
                "operator_password" => $operatorPassword
            ],
            "order" => [
                "id_order" => $clinetOrderId,
                "currency" => $currency,
                "amount" => $amount
            ],
            "iframe_behavior" => [
                "height" => 400,
                "width" => 350,
                "custom_redirection_url" => $this->domainURL.'/paymentResponse.php?mipsid='.$clinetOrderId,
                "language" => "EN"
            ],
            "request_mode" => "simple",
            "touchpoint" => "native_app",
            "additional_params" => [
                ["param_name" => "customer_name", "param_value" => $customerName],
                ["param_name" => "order_title", "param_value" => $studentCode]
            ]
        ]);
    
        // Initialize cURL
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $apiUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_HTTPHEADER => [
                'Accept: application/json, text/html, application/xml, multipart/form-data, application/EDIFACT, text/plain',
                'Content-Type: application/json',
                $authHeader
            ],
        ]);
    
        // Execute cURL request
        $response = curl_exec($curl);
        $curlError = curl_error($curl);
        curl_close($curl);
    
        // Handle cURL errors
        if ($curlError) {
            return ['status' => 'ERROR', 'message' => 'cURL Error: ' . $curlError];
        }
    
        // Decode response
        $responseArray = json_decode($response, true);
    
        // Check API response status
        return [
            'status' => isset($responseArray['answer']['operation_status']) && $responseArray['answer']['operation_status'] === 'success' ? 'SUCCESS' : 'ERROR',
            'jsonResponse' => $responseArray
        ];
    }

    public function fetchOrder($data)
    {
        $receivedCryptedData = $data['receivedCryptedData'];
        $gatewayJson  = json_decode($data['gatewayConfig'], true);
        $requiredKeys = ['merchantID', 'entityID', 'operatorID', 'operatorPassword', 'salt', 'cipherKey', 'environment'];
        foreach ($requiredKeys as $key) {
            if (empty($gatewayJson[$key])) {
                return ['status' => 'ERROR', 'message' => "Missing required gateway parameter: $key"];
            }
        }

        // Assign necessary variables
        $merchantID = $gatewayJson['merchantID'];
        $entityID = $gatewayJson['entityID'];
        $operatorID = $gatewayJson['operatorID'];
        $operatorPassword = $gatewayJson['operatorPassword'];
        $salt = $gatewayJson['salt'];
        $cipherKey = $gatewayJson['cipherKey'];
        $environment = $gatewayJson['environment'];
        $username = $gatewayJson['username'];
        $password = $gatewayJson['password'];

        // Authorization header
        $authHeader = 'Authorization: Basic ' . base64_encode("$username:$password");

        // API URL
        $apiUrl = rtrim($environment, '/') . '/api/decrypt_imn_data';

        // Request payload
        $payload = json_encode([
            "authentify" => [
                "id_merchant" => $merchantID,
                "id_entity" => $entityID,
                "id_operator" => $operatorID,
                "operator_password" => $operatorPassword
            ],
            "salt" => $salt,
            "cipher_key" => $cipherKey,
            "received_crypted_data" => $receivedCryptedData
        ]);

        // Initialize cURL
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $apiUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_HTTPHEADER => [
                'Accept: application/json',
                'Content-Type: application/json',
                $authHeader,
                'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
            ],
        ]);

        // Execute cURL request
        $response = curl_exec($curl);
        $curlError = curl_error($curl);
        curl_close($curl);

        // Handle cURL errors
        if ($curlError) {
            return ['status' => 'ERROR', 'message' => 'cURL Error: ' . $curlError];
        }

        // Decode response
        $responseArray = json_decode($response, true);

        // Return API response
        return [
            'status' => isset($responseArray['status']) && $responseArray['status'] ? 'SUCCESS' : 'ERROR',
            'jsonResponse' => isset($responseArray['status']) && $responseArray['status'] ? $responseArray : 'Invalid decrypted response',
        ];
    }

    public function fetchOrderByTxnId($orderData)
    {
        $curl = curl_init();
        $gatewayJson = json_decode($orderData['gatewayConfig'] , true);
        $username = $gatewayJson['username'];
        $password = $gatewayJson['password'];
        $authHeader = 'Authorization: Basic ' . base64_encode("$username:$password");
        echo "<pre>";
        curl_setopt_array($curl, [
            CURLOPT_URL => $gatewayJson['environment']."/api/orders_management",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode([
                "authentify" => [
                    "id_merchant"=> $gatewayJson['merchantID'],
                    "id_entity"=> $gatewayJson['entityID'],
                    "id_operator"=> $gatewayJson['operatorID'],
                    "operator_password"=> $gatewayJson['operatorPassword']
                ],
                "instruction" => "get_order_all_data",
                "order"=> ["id_order" => $orderData['txnId']],
                "description"=> "string"
                
            ]),
            CURLOPT_HTTPHEADER => array(
                'Accept: application/json',
                'Content-Type: application/json',
                'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36',
                $authHeader
            ),
        ]);
        $response = curl_exec($curl);        
        return json_decode($response , true);
    }
}
