<?php
ini_set('display_errors', 1);


require_once '/home/rejoicebilldesk/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/easebuzz/function.php";

require_once $base_path_to_learning_resources . "payment_gateway/whitelist/function.php";

require_once $base_path_to_learning_resources . 'external_requests/finware_curl/groups_ledgers/curl_check_student_ledgers_finware.php';
require_once $base_path_to_learning_resources . 'external_requests/finware_curl/groups_ledgers/curl_function_branch_students.php';

$postdata = json_decode(file_get_contents("php://input"), true);

checkIfNoPhpContentsReceive();

// Validate required fields
$required_fields = ['student_id', 'amount', 'institution_id', 'branch_id'];

foreach ($required_fields as $field) {
    if (empty($postdata[$field])) {
        errorreturn("Missing required field: $field");
    }
}

validateApiSignature($postdata['api_signature']);

$jwt_token = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwt_token);

$userid       = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username     = $jwt_validate->data->username;
$role         = $jwt_validate->data->role;

// Fetch and validate input data
$student_id = $postdata['student_id'];
$amount = $postdata['amount'];
$institution_id = $postdata['institution_id'];
$branch_id = $postdata['branch_id'];
$Fees_header = $postdata['Fees_header'] ?? 0;


// if (!is_numeric($amount) || $amount <= 10) {
//     errorreturn("Invalid amount. Amount should be numeric and greater than 10.");
// }

// Validate student existence and active status
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ['superadmin', 'student'], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

checkStudentLedgerByUserId($conn_rjllearning_specific, $workspace_id, $userid, $institution_id);
// Fetch student details
$stmt = $conn_rjllearning_specific->prepare("
    SELECT id,institution_id,branch_id,admission_number, name, fathername, class_id, section_id, mobile ,user_id , email
    FROM students 
    WHERE user_id = ? AND status = 1
");
$stmt->execute([$student_id]);
$student = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$student) errorreturn("Student not found or inactive.");

// Fetch payment gateway setup
$stmt = $conn_rjllearning->prepare("
    SELECT id, pg_vendor,credentials, return_url, redirection_url, institution_id, branch_id ,white_label_url
    FROM payment_gateway_setup 
    WHERE workspace_id = ? and institution_id = ? and branch_id =? and status = 1
");
$stmt->execute([$workspace_id, $institution_id, $branch_id]);
$pg_setup = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$pg_setup) errorreturn("Payment gateway is not configured.");

$white_label_url = $pg_setup['white_label_url'];
// Remove trailing slash if present to avoid double slashes
$white_label_url = rtrim($white_label_url, '/');

// Append the desired endpoint
// $api_url = $white_label_url . '/send_request.php';

// $payment_gateway_id = $pg_setup['id'];


switch (strtolower($pg_setup['pg_vendor'])) {
    case 'icici':
        generateICICIPaymentLink($student, $pg_setup, $amount, $white_label_url, $userid, $paymentGatewayCredentialKey, $conn_rjllearning);
        // print_R($icici);
        break;

    case 'ccavenue':
        generateCCAvenuePaymentLink($student, $pg_setup, $amount, $white_label_url, $userid, $paymentGatewayCredentialKey, $conn_rjllearning);
        //  print_R($adrsh);
        break;
    case 'wordline':
        generateWordlinePaymentLink($student, $pg_setup, $amount,$white_label_url, $userid, $paymentGatewayCredentialKey, $conn_rjllearning);
        
    case 'easebuzz':
        easebuzzInitiatePayment($student,$pg_setup, $amount,$white_label_url, $userid, $paymentGatewayCredentialKey, $conn_rjllearning);
    //  print_R($adrsh);
    break;

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