<?php
// important functionr
function errorreturnCurlContinue($x) {
    return json_encode(array('status' => false, 'errormsg' => $x));
}
function createPaymentGatewayTransactionFinware($conn_rjllearning,$workspace_id, $institution_id, $admission_number, $transaction_data, $branch_id, $debug_method = 'webhook') {
    // $transaction_data = [
    //     'order_id' => $order_id,
    //     'amount' => $obj->order_amt ?? '',
    //     'payment_gateway' => "ccavenue",
    // ];
    // Fetch workspace database
   
    $stmt = $conn_rjllearning->prepare("SELECT db_name FROM workspace_database_info WHERE workspace_id = ? AND status = 1");
    $stmt->execute([$workspace_id]);
    $workspace_database_info = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$workspace_database_info) {
        errorreturnCurlContinue("Workspace database info not found");
    }

    $db_name = $workspace_database_info['db_name'];
    $conn_rjllearning_specific = dynamicDbConnection($db_name);

    // Fetch student details
    $stmt = $conn_rjllearning_specific->prepare("SELECT * FROM students WHERE admission_number = ? AND institution_id = ? and branch_id = ?");
    $stmt->execute([$admission_number, $institution_id, $branch_id]);
    $student = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($student) {
        $student_id = $student['id'];
        $branch_id = $student['branch_id'];
        $name = $student['name'];
        $father_name = $student['fathername'];
        $mother_name = $student['mothername'];
        $gender = $student['gender'];
        $username = $student['username'];

        // Fetch branch info
        $branch = getBranchDetails($conn_rjllearning_specific, $branch_id, $institution_id);
        if (!empty($branch)) {
            // Build ledger name
            if (!empty($father_name)) {
                $relation = ($gender === 'M') ? 'S/o' : 'D/o';
                $ledger_name = "$name $relation $father_name - $admission_number";
            } elseif (!empty($mother_name)) {
                $relation = ($gender === 'M') ? 'S/o' : 'D/o';
                $ledger_name = "$name $relation $mother_name - $admission_number";
            } else {
                $ledger_name = "$name - $admission_number";
            }

            $ledger_name = sanitizeInput($ledger_name);

            // Prepare formatted data
            $formattedData = [
                'product_connection_id' => $student_id,
                'ledger_name' => $ledger_name,
                'function_type' => 'check_student',
                'ledger_main_ledgerhead' => 'Sundry Debtors',
                'created_by' => $username,
                'transaction_data' => $transaction_data,
            ];

            $students_data = [
                "workspace_id" => $workspace_id,
                "branch" => $branch,
                "student_learning" => $formattedData,
            ];

            $curl_student_transaction_response = curlStudenttransaction($students_data);
            
            
            $order_id = $transaction_data['order_id'];  // Replace with actual order ID

            $log_file = __DIR__ . '/transaction_log.txt'; // Save in current directory
            
            $log_entry = "Log for Order ID: $order_id via $debug_method" . PHP_EOL;
            $log_entry .= print_r($curl_student_transaction_response, true) . PHP_EOL;
            $log_entry .= str_repeat('-', 80) . PHP_EOL; // Line separator
            
            file_put_contents($log_file, $log_entry, FILE_APPEND | LOCK_EX);
            
            
            // update in initiated_transactions with positive response in finware_verification
            $sql = "UPDATE initiated_transactions set finware_verification = ? where workspace_id = ? and institution_id = ? and order_id = ?";
            $update = $conn_rjllearning->prepare($sql);
            if($curl_student_transaction_response == true || $curl_student_transaction_response == 1) {
                $update->execute(array(1, $workspace_id, $institution_id, $transaction_data['order_id']));
            } else {
                // update initiated_transactions with negative response
                $update->execute(array(-1, $workspace_id, $institution_id, $transaction_data['order_id']));
            }
          
        } else {
            errorreturnCurlContinue("Branch not found for branch_id: $branch_id");
        }
    } else {
        errorreturnCurlContinue("Student not found with admission_number: $admission_number");
    }
} 
?>