<?php

require_once '/home/rejoicebilldesk/public_html/rjllearning_development/resources/payment_gateway/wordline/aes.php';
require_once '/home/rejoicebilldesk/public_html/rjllearning_development/resources/payment_gateway/wordline/requestvalidate.php';
require_once '/home/rejoicebilldesk/public_html/rjllearning_development/resources/payment_gateway/wordline/TransactionRequestBean.php';
require_once '/home/rejoicebilldesk/public_html/rjllearning_development/resources/payment_gateway/wordline/TransactionResponseBean.php';


function generateWordlinePaymentLink($student, $pg_setup, $amount, $white_label_url, $userid, $paymentGatewayCredentialKey, $conn_rjllearning) {
    global $workspace_id;
    global $conn_rjllearning_specific;


    $order_id = $workspace_id . '_' . $student['institution_id'] . '_' . $student['branch_id'] . '_' . $student['admission_number'] . '_' . time();
    $pg_credentials = json_decode(aes128Decrypt($pg_setup['credentials'], $paymentGatewayCredentialKey), true);


    // $merchantCode = $pg_credentials['merchantCode'] ?? '';
    // $key = $pg_credentials['key'] ?? '';
    // $iv = $pg_credentials['iv'] ?? '';
    // $reqDetail = $pg_credentials['schemeCode'] . "_" . number_format(floatval($amount), 2, '.', '') . "_0.0";
  
   

    $reqDetail = 'First' . "_" . number_format(floatval($amount), 2, '.', '') . "_0.0";
    
    
    $currency = 'INR';
    
    $common_url = "https://rejoicebilldesk.in/rjllearning_development/resources/payment_gateway/whitelist/response_whitelist.php?order_id=".$order_id;
    $section_name = getSection($conn_rjllearning_specific, $student['institution_id'], $student['section_id']);
    $class_info = getClass($conn_rjllearning_specific, $student['institution_id'], $student['class_id']);
    $branch_name = getBranchInfo($conn_rjllearning_specific, $student['institution_id'], $student['branch_id'], null);

    // $meta_data = [
    //     'student_name' => $student['name'] ?? '',
    //     'admission_no' => $student['admission_number'] ?? '',
    //     'branch_selected' => $branch_name['name'] ?? '',
    //     'class' => $class_info['class_name'] ?? '',
    //     'section' => $section_name['section_name'] ?? '',
    //     'student_id' => $student['id'] ?? ''
    // ];
     $meta_data = "{student_name:" . $student['name'] . "~admissionno:" . $student['admission_number'] . "~branch_selected:" .  $branch_name['name'] . "~class:" .
     $class_info['class_name'] . "~section:" . $section_name['section_name'] . "~uniqueadm:" . $student['id'] . "}";
    // $data = [
    //     'merchant_id' => $merchantCode,
    //     'order_id' => $order_id,
    //     'amount' => $amount,
    //     'currency' => $currency,
    //     'return_url' => $common_url,
    //     'cancel_url' => $common_url,
    //     'metadata' => json_encode($meta_data),
    //     'pg_url' => "https://www.tpsl-india.in/PaymentGateway/TransactionDetailsNew.wsdl"
    // ];
    // Prepare TransactionRequestBean
    $transactionRequestBean = new TransactionRequestBean();
    $transactionRequestBean->merchantCode = $merchantCode;
    $transactionRequestBean->key = $key;
    $transactionRequestBean->iv = $iv;
       $transactionRequestBean->ITC = $meta_data; // client meta data
    $transactionRequestBean->customerName = $student['id'] ?? '';
    $transactionRequestBean->requestType = 'T';
    $transactionRequestBean->merchantTxnRefNumber = $order_id;
    $transactionRequestBean->amount = $amount;
    $transactionRequestBean->currencyCode = $currency;
    $transactionRequestBean->returnURL = $common_url;
    $transactionRequestBean->shoppingCartDetails = $reqDetail;
    $transactionRequestBean->txnDate = date('d-m-Y');
    $transactionRequestBean->bankCode = '470';
     $transactionRequestBean->webServiceLocator = 'https://www.tpsl-india.in/PaymentGateway/TransactionDetailsNew.wsdl';
    $transactionRequestBean->timeOut = 30;

    $payment_url = $transactionRequestBean->getTransactionToken();
    $encrypted_json = json_encode([
            "pg_url" => $payment_url
        ]);
    if ($payment_url) {
        successreturn([
            "order_id" => $order_id,
            "white_label_url" => "https://gvis.in/test_pg/send_request.php",
            "json_encoded_data" => $encrypted_json,
            "gateway" => "wordline"
        ]);
    } else {
        errorreturn("Failed to generate Wordline transaction token");
    }
}





function handleWordlineResponse($data, $pg_vendor, $workspace_id, $institution_id, $branch_id, $conn_rjllearning) {
  

    // $reqDetail = 'First' . "_" . number_format(floatval($amount), 2, '.', '') . "_0.0";

    if (!$data) {
        return errorreturn("No data received.");
    }

    // Determine source of encrypted data
    if (isset($data['msg']) || isset($data['response'])) {
        $encryptedKey = isset($data['msg']) ? 'msg' : 'response';
        $str = is_array($data) ? $data[$encryptedKey] : $data;

        // Handle query string format if needed
        if (is_string($str) && strstr($str, $encryptedKey . '=')) {
            $outputstr = str_replace($encryptedKey . '=', '', $str);
            $outputArr = explode('&', $outputstr);
            $str = $outputArr[0];
        }
        // Log encrypted string
        $logDir = 'logs/response/';
        if (!file_exists($logDir)) {
            mkdir($logDir, 0777, true);
        }
        file_put_contents("logs/response/encrypted_" . date("j.n.Y") . ".log", "Encrypted [$encryptedKey]: " . $str . PHP_EOL, FILE_APPEND);

        // Decrypt the payload
        $transactionResponseBean = new TransactionResponseBean();
        $transactionResponseBean->setResponsePayload($str);
        $transactionResponseBean->key = $key;
        $transactionResponseBean->iv = $iv;
        $response = $transactionResponseBean->getResponsePayload();

        // Log decrypted response
        file_put_contents("logs/response/log_" . date("j.n.Y") . ".log", "Date: " . date("F j, Y, g:i a") . "; Decrypted Response: " . $response . PHP_EOL, FILE_APPEND);
    } else if (isset($_POST['response'])) {
        $response = $_POST['response'];
        file_put_contents('logs/response/log_' . date("j.n.Y") . '.log', "Date: " . date("F j, Y, g:i a") . "; POST Response: " . $response . PHP_EOL, FILE_APPEND);
    } else {
        errorreturn("Missing 'msg' or 'response' parameter.");
    }

    // Parse decrypted response string
    $keyValuePairs = explode("|", $response);
    $result = [];
    foreach ($keyValuePairs as $pair) {
        $explodedPair = explode("=", $pair, 2);
        $key = $explodedPair[0];
        $value = $explodedPair[1] ?? '';
        $result[$key] = $value;
    }

    // Validate transaction status
    

    // Extract and parse client metadata
   $clnt_rqst_meta = trim($result['clnt_rqst_meta'] ?? '', '{}');
    $meta_parts = explode('}{', $clnt_rqst_meta);
    $itc_part = str_replace("itc:", "", $meta_parts[0] ?? '');
    $custname_part = $meta_parts[1] ?? '';

    $itc_data = [];
    foreach (explode('~', $itc_part) as $pair) {
        list($meta_key, $meta_val) = explode(':', $pair, 2) + ["", ""];
        $itc_data[$meta_key] = $meta_val;
    }

    $result['clnt_rqst_meta'] = [
        'itc' => $itc_data,
        'custname' => $custname_part
    ];

    $order_id   = $result['clnt_txn_ref'] ?? '';
    $admissionno = $itc_data['admissionno'] ?? '';
    $branch      = $itc_data['branch_selected'] ?? '';
    $uniqueadm   = $itc_data['uniqueadm'] ?? '';
    
    // Define an array of the critical identifiers
    $requiredData = [
        'order_id'    => $order_id,
        'admissionno' => $admissionno,
        'branch'      => $branch,
        'uniqueadm'   => $uniqueadm
    ];
    
    // Initialize an array to store missing identifiers
    $missingData = [];
    
    // Loop through each identifier and check if it's missing
    foreach ($requiredData as $key => $value) {
        if (empty($value)) {
            $missingData[] = $key;
        }
    }
    
    // If any critical identifiers are missing, return an error with the list of missing keys
    if (!empty($missingData)) {
        $missingList = implode(', ', $missingData);
        errorreturn("Missing critical identifiers: $missingList");
    }



    // Define order_status and failure message (optional logic based on response)
    $order_status = $result['txn_msg'];
    $failure_msg = '';

    $remarks = "Payment response for order_id: $order_id. Status: $order_status. Failure: $failure_msg";
    $status = ($order_status === 'Success') ? 1 : (($order_status === 'Failure' || $order_status === 'Aborted') ? -1 : 0);

    $insert = $conn_rjllearning->prepare("INSERT INTO transactions 
        (workspace_id, institution_id, branch_id, gateway_id, reference_no, remarks, status, created_at, updated_at) 
        VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");

    $insert->execute([
        $workspace_id,
        $institution_id,
        $branch_id,
        $pg_vendor['id'],
        $order_id,
        $remarks,
        $status
    ]);

    if ($insert->rowCount() === 0) {
        errorreturn("Failed to insert transaction for order_id: $order_id");
    }

    // Final structured response
    return [
        'order_id'         => $order_id,
        'amount'           => floatval($result['txn_amt']),
        'transaction_time' => $result['tpsl_txn_time'],
        'metadata'         => $result['clnt_rqst_meta']
    ];


}


// function checkWorldlineStatus($order_id)
// {
//     global $conn_rjllearning;
//     global $paymentGatewayCredentialKey;

//     $parts = explode('_', $order_id);
//     if (count($parts) < 5) {
//         return ['error' => 'Invalid order_id format'];
//     }

//     list($workspace_id, $institution_id, $branch_id, $student_id, $unique_id) = $parts;

//     // Fetch payment gateway credentials
//     $stmt = $conn_rjllearning->prepare("SELECT pg_vendor, credentials 
//                                         FROM payment_gateway_setup 
//                                         WHERE workspace_id = ? AND institution_id = ? AND branch_id = ? 
//                                         LIMIT 1");
//     $stmt->execute([$workspace_id, $institution_id, $branch_id]);
//     $pg_data = $stmt->fetch(PDO::FETCH_ASSOC);

//     if (!$pg_data) {
//         return ['error' => 'Payment gateway setup not found for this branch'];
//     }

//     $vendor = strtolower($pg_data['pg_vendor']);
//     if (!in_array($vendor, ['worldline', 'wordline'])) {
//         return ['error' => 'Payment gateway vendor is not Worldline'];
//     }

//     $pg_credentials = json_decode(aes128Decrypt($pg_data['credentials'], $paymentGatewayCredentialKey), true);

//     if (empty($pg_credentials['merchantCode']) || empty($pg_credentials['key']) || empty($pg_credentials['iv'])) {
//         return ['error' => 'Incomplete Worldline credentials'];
//     }

//       $merchantCode = 'L1055845';
//     $key = '9833025122VNSMYT';
//     $iv = '3227641951FYXWCB';
//     // $reqDetail = 'First' . "_" . number_format(floatval($amount), 2, '.', '') . "_0.0";

//     $schemeCode = $pg_credentials['schemeCode'] ?? 'First';

//     // API endpoint (usually same for test/prod)
//     $api_url = 'https://www.paynimo.com/api/paynimoV2.req';

//     // Build transaction request payload for order status
//     $txnRequest = [
//         "merchant" => [
//             "identifier" => $merchantCode,
//             // optionally send schemeCode if supported by API
//             // "schemeCode" => $schemeCode
//         ],
//         "transaction" => [
//             "deviceIdentifier" => "S",
//             "currency" => "INR",
//             "identifier" => $order_id,
//             "dateTime" => date('d-m-Y'),
//             "requestType" => "O"  // 'O' means order status inquiry
//         ]
//     ];

//     $jsonData = json_encode($txnRequest);

//     $ch = curl_init($api_url);
//     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//     curl_setopt($ch, CURLOPT_POST, true);
//     curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
//     curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);

//     $response = curl_exec($ch);
//     curl_close($ch);
    
//     if (!$response) {
//         return ['error' => 'No response from Worldline'];
//     }

//     $responseData = json_decode($response, true);
//     print_R($responseData);

//     if (isset($responseData['paymentMethod']['paymentTransaction'])) {
//         $transaction = $responseData['paymentMethod']['paymentTransaction'];
        
//         $status_code = $transaction['statusCode'] ?? '';
//         $status_message = $transaction['statusMessage'] ?? '';
//         $txn_id = $transaction['reference'] ?? '';
//         $amount = $transaction['amount'] ?? '';
    
//         $order_status = in_array($status_code, ['0300', '0399']) ? 'Success' : 'Failed';
    
//         return [
//             'status' => ($status_code === '0300') ? 1 : 0,
//             'order_status' => $order_status,
//             'txn_id' => $txn_id,
//             'amount' => $amount,
//             'payment_date' => date('Y-m-d H:i:s'),
//             'order_no' => $order_id,
//             'order_bank_response' => $status_message,
//             'vendor_ref' => $txn_id
//         ];
//     } else {
//         return ['error' => 'Invalid response structure from Worldline'];
//     }


//     return ['error' => 'Invalid response structure from Worldline'];
// }










function checkWorldlineStatus($order_id)
{
    global $conn_rjllearning;
    global $paymentGatewayCredentialKey;

    $parts = explode('_', $order_id);
    if (count($parts) < 5) {
        return ['error' => 'Invalid order_id format'];
    }

    list($workspace_id, $institution_id, $branch_id, $student_id, $unique_id) = $parts;

    // Fetch payment gateway credentials
    $stmt = $conn_rjllearning->prepare("SELECT pg_vendor, credentials 
                                        FROM payment_gateway_setup 
                                        WHERE workspace_id = ? AND institution_id = ? AND branch_id = ? 
                                        LIMIT 1");
    $stmt->execute([$workspace_id, $institution_id, $branch_id]);
    $pg_data = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$pg_data) {
        return ['error' => 'Payment gateway setup not found for this branch'];
    }

    $vendor = strtolower($pg_data['pg_vendor']);
    if (!in_array($vendor, ['worldline', 'wordline'])) {
        return ['error' => 'Payment gateway vendor is not Worldline'];
    }

    $pg_credentials = json_decode(aes128Decrypt($pg_data['credentials'], $paymentGatewayCredentialKey), true);

    if (empty($pg_credentials['merchantCode']) || empty($pg_credentials['key']) || empty($pg_credentials['iv'])) {
        return ['error' => 'Incomplete Worldline credentials'];
    }


    // $reqDetail = 'First' . "_" . number_format(floatval($amount), 2, '.', '') . "_0.0";

    $schemeCode = $pg_credentials['schemeCode'] ?? 'First';


    // API endpoint (usually same for test/prod)
    $api_url = 'https://www.paynimo.com/api/paynimoV2.req';

    // Build transaction request payload for order status
    $txnRequest = [
        "merchant" => [
            "identifier" => $merchantCode,
            "schemeCode" => $schemeCode,
        ],
        "transaction" => [
            "deviceIdentifier" => "S",
            "currency" => "INR",
            "identifier" => $order_id,
            "dateTime" => date('d-m-Y'),
            "requestType" => "O"  // 'O' means order status inquiry
        ]
    ];

    $jsonData = json_encode($txnRequest);

    // Initialize cURL
    $ch = curl_init($api_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);

    $response = curl_exec($ch);
    curl_close($ch);

    if (!$response) {
        return ['error' => 'No response from Worldline'];
    }

    $responseData = json_decode($response, true);
    if (!$responseData) {
        return ['error' => 'Invalid JSON response from Worldline', 'raw_response' => $response];
    }
    print_R($responseData);

    // Debug: print the full response (you can comment this out after testing)
    // print_r($responseData);

    if (isset($responseData['paymentMethod']['paymentTransaction'])) {
        $transaction = $responseData['paymentMethod']['paymentTransaction'];
        

        $status_code = $transaction['statusCode'] ?? '';
        $status_message = $transaction['statusMessage'] ?? '';
        $txn_id = $transaction['reference'] ?? '';
        $amount = $transaction['amount'] ?? '';

        $order_status = in_array($status_code, ['0300', '0399']) ? 'Success' : 'Failed';

        $result = [
            'status' => ($status_code === '0300') ? 1 : 0,
            'order_status' => $order_status,
            'txn_id' => $txn_id,
            'amount' => $amount,
            'payment_date' => date('Y-m-d H:i:s'),
            'order_no' => $order_id,
            'order_bank_response' => $status_message,
            'vendor_ref' => $txn_id
        ];

        // Try to parse your custom client metadata if present
        if (!empty($transaction['clnt_rqst_meta'])) {
            $clnt_rqst_meta = trim($transaction['clnt_rqst_meta'], '{}');
            $meta_parts = explode('}{', $clnt_rqst_meta);

            $itc_part = str_replace("itc:", "", $meta_parts[0] ?? '');
            $custname_part = $meta_parts[1] ?? '';

            $itc_data = [];
            foreach (explode('~', $itc_part) as $pair) {
                list($meta_key, $meta_val) = explode(':', $pair, 2) + ["", ""];
                $itc_data[$meta_key] = $meta_val;
            }

            $result['clnt_rqst_meta'] = [
                'itc' => $itc_data,
                'custname' => $custname_part
            ];
        }

        return $result;

    } else {
        return ['error' => 'Invalid response structure from Worldline'];
    }

    return ['error' => 'Invalid response structure from Worldline'];
}

