<?php
ini_set('display_errors', 1);
header('Content-Type: application/json');

require_once '/home/rejoicebilldesk/public_html/rjllearning_development/resources/base_path_include.php';
require_once $base_path_to_learning_resources  . "includes/connect.php"; // use require for mandatory files
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';

//valdation file
require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
//db access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';


require_once $base_path_to_learning_resources . "includes/pg_credentials_encryption_key.php";
require_once $base_path_to_learning_resources . 'payment_gateway/icici_bank/icici_bank_function.php';
require_once $base_path_to_learning_resources . "payment_gateway/ccavenue/ccavenue_bank_function.php";
require_once $base_path_to_learning_resources . "payment_gateway/wordline/wordline_function.php";
require_once $base_path_to_learning_resources . "payment_gateway/whitelist/function.php";
require_once $base_path_to_learning_resources . "payment_gateway/easebuzz/function.php";

require_once $base_path_to_learning_resources . 'external_requests/finware_curl/groups_ledgers/curl_function_branch_students.php';
require_once $base_path_to_learning_resources . "external_requests/finware_curl/student/curl_student_transaction_finware.php";
require_once $base_path_to_learning_resources . "payment_gateway/student_payment_gateway_finware_transaction.php";
// Raw input and decode
$rawInput = file_get_contents("php://input");
$data = json_decode($rawInput, true);
// Debug log

// For debugging purpose (can be removed in production)
try {
   
    $gateway = detectPaymentGateway($data);
    

    if ($gateway != 'wordline') {
        $order_id = extractOrderId($data, $gateway);
    } else {
        $order_id = $data['order_id'];
    }

    if (empty($order_id)) {
        errorreturn("Unable to extract order ID");
    }

    // Parse order_id
    $parts = explode('_', $order_id);
    if (count($parts) < 5) {
        errorreturn("Invalid order_id format");
    }

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

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

    if (!$pg_vendor) {
        errorreturn("PG Vendor not found for this branch");
    }

    // Set transaction isolation level
    $conn_rjllearning->exec("SET TRANSACTION ISOLATION LEVEL READ COMMITTED");

    // Begin transaction
    $conn_rjllearning->beginTransaction();

    switch ($gateway) {
        case 'ccavenue':
            handleCcavenueDecryptedResponse($data, $pg_vendor, $workspace_id, $institution_id, $branch_id, $conn_rjllearning);
            break;

        case 'icici':
            handleIciciResponse($data, $pg_vendor, $workspace_id, $institution_id, $branch_id, $conn_rjllearning);
            break;

        case 'wordline':
            handleWordlineResponse($data, $pg_vendor, $workspace_id, $institution_id, $branch_id, $conn_rjllearning);
            break;
            
        case 'easebuzz':
             handleEasebuzzResponse($data, $pg_vendor, $workspace_id, $institution_id, $branch_id, $conn_rjllearning);
            break;

        default:
            errorreturn("Unsupported payment gateway.$gateway");
    }

    // Commit
    $conn_rjllearning->commit();
} catch (Exception $e) {
    if ($conn_rjllearning->inTransaction()) {
        $conn_rjllearning->rollBack();
    }
    errorreturn("Internal server error: " . $e->getMessage());
}
