<?php
function curlStudenttransaction($finalArray)
{
    try {
        // Initialize cURL session
        $ch = curl_init();
        
        // Get cURL URL and API signature information
        $curl_info = curlStudenttransactionurl();
        
        $url = $curl_info['url'];
        $api_signature = $curl_info['api_signature'];

        // Prepare the payload to send
        $payload = json_encode(array("data" => $finalArray, "api_signature" => $api_signature));
        // Set cURL options
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Execute cURL request
        $result = curl_exec($ch);
        
        // Check if there was an error during cURL execution
        if ($result === false) {
            $error_msg = curl_error($ch);
            curl_close($ch);  // Close cURL handle
            echo json_encode(array('status' => 0, 'error' => 'cURL error: ' . $error_msg));
            die();
        }

        // Close cURL handle after executing
        curl_close($ch);
        
        $order_id = $finalArray['student_learning']['transaction_data']['order_id'];  // Replace with actual order ID

        $log_file = __DIR__ . '/curl_transaction_log.txt'; // Save in current directory
        
        $log_entry = "Log for Order $order_id " . PHP_EOL;
        $log_entry .= print_r($result, true) . PHP_EOL;
        $log_entry .= str_repeat('-', 80) . PHP_EOL; // Line separator
        
        file_put_contents($log_file, $log_entry, FILE_APPEND | LOCK_EX);
        
        // Try to decode the JSON response
        $data = json_decode($result, true);
        
        // errorreturn($data);
        if (isset($data['error']) && $data['error']) {
            errorreturnCurlContinue($data['message']);
        } else if (isset($data['status']) and $data['status'] == 0) {
            errorreturnCurlContinue($data['response']);
        }

        // If no error, return the decoded data
        return true;

    } catch (Exception $e) {
        // Catch and display any exception that occurs
        errorreturnCurlContinue("Exception : ".$e->getMessage());

    }
}
function curlStudenttransactionurl()
{
    // Define your cURL URL and API signature here
    $url = $GLOBALS['curl_url_finware'].'resources/external_requests/education_curl/students/curl_student_transaction_finware.php';
    return array('url' => $url, 'api_signature' => 'WR5yGWg6mGxDLvxN');
}
