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


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/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_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/wordline/wordline_function.php";
require_once $base_path_to_learning_resources . "payment_gateway/student_payment_gateway_finware_transaction.php";
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    errorreturn('Invalid request method');
}

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

try {
    $order_id = $postdata['order_id'] ?? null;
    $pg_vendor = $postdata['payment_gateway'] ?? null;

    if (!$order_id) {
        errorreturn('Order ID is required');
    }

    $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;

    // STEP 1: Check existing transaction to get PG vendor if not passed
    $gateway_id = null;
    if (!$pg_vendor) {
        
        // Query payment_gateway_setup table by workspace_id and branch_id
        $stmt = $conn_rjllearning->prepare("SELECT id, pg_vendor FROM payment_gateway_setup WHERE workspace_id = ? AND institution_id = ? and  branch_id = ? and status = '1'");
        $stmt->execute([$workspace_id,$institution_id, $branch_id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
    
        if ($row && $row['id'] && $row['pg_vendor']) {
            $gateway_id = $row['id'];
            $pg_vendor = $row['pg_vendor'];
        } else {
            errorreturn('Payment gateway not found for given workspace and branch');
        }
    }

    // STEP 2: Call appropriate status check API
    $status_response = checkPGStatus($pg_vendor, $order_id);

    // Extract data
    $order_id       = $status_response['order_no'];
    $order_status   = $status_response['status'];
    $finalstatus    = $status_response['order_status'];
    $amount         = $status_response['amount'];
    $payment_date   = $status_response['payment_date'];
    $vendor_ref     = $status_response['vendor_ref'];
    $failure_msg    = $status_response['order_bank_response'];
    $txn_id         = $status_response['txn_id'];
    $name           = $status_response['name'];
    $email          = $status_response['email'];
    $country        = $status_response['country'];
    $phone          = $status_response['phone'];
    $branch         = $status_response['branch'];
    $class          = $status_response['class'];
    $section        = $status_response['section'];
    $admission_number = $status_response['admission_number'];

    $remarks = "Payment response for order_id: $order_id. Status: $order_status. message: $failure_msg";
    $status = ($finalstatus === 'Successful') ? 1 : -1;

    

    // STEP 3: Begin DB Transaction
    $conn_rjllearning->exec("SET TRANSACTION ISOLATION LEVEL READ COMMITTED");
    $conn_rjllearning->beginTransaction();

    $stmt = $conn_rjllearning->prepare("SELECT * FROM transactions WHERE reference_no = ?");
    $stmt->execute([$order_id]);
    $existing = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$existing) {
        // Get gateway_id if not already
        if (!$gateway_id) {
            $stmt = $conn_rjllearning->prepare("SELECT id FROM payment_gateway_setup WHERE pg_vendor = ?");
            $stmt->execute([$pg_vendor]);
            $pg_row = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$pg_row) {
                errorreturn("Gateway vendor '$pg_vendor' not found");
            }
            $gateway_id = $pg_row['id'];
        }

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

        $insert->execute([
            $workspace_id,
            $institution_id,
            $branch_id,
            $amount,
            $gateway_id,
            $order_id,
            $remarks,
            $status
        ]);
        
        // update initiated_transactions with positive response
        $sql = "UPDATE initiated_transactions set status = ? where workspace_id = ? and institution_id = ? and order_id = ?";
        $update = $conn_rjllearning->prepare($sql);
        $update->execute(array(1, $workspace_id, $institution_id, $order_id));    
    
    } elseif ($existing['status'] != $status) {
        // UPDATE existing transaction if status changed
        $update = $conn_rjllearning->prepare("UPDATE transactions 
            SET status = ?, remarks = ?, amount = ?, updated_at = NOW() 
            WHERE reference_no = ?");

        $update->execute([$status, $remarks, $amount, $order_id]);
    }

    // if ($finalstatus === 'Successful') {
    //     $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) {
    //         errorreturn("Workspace database info not found");
    //     }

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

    //     SendPaymentSms($conn_rjllearning_specific, $institution_id, $branch_id, $workspace_id, $student_id, $amount, $phone, $conn_rjllearning);
    // }

    // COMMIT transaction
    $conn_rjllearning->commit();

    successreturn([
        'message'          => 'Transaction status updated',
        'branch'           => $branch,
        'name'             => $name,
        'email'            => $email,
        'country'          => $country,
        'phone'            => $phone,
        'class'            => $class,
        'section'          => $section,
        'amount'           => $amount,
        'admission_number' => $admission_number,
        'status'           => $status,
        'remarks'          => $remarks,
        'order_id'         => $order_id,
        'failure_msg'      => $failure_msg,
        'txn_id'           => $txn_id
    ]);
} catch (Exception $e) {
    if ($conn_rjllearning->inTransaction()) {
        $conn_rjllearning->rollBack();
    }
    errorreturn("Internal server error: " . $e->getMessage());
}
