<?php
// Ensure no extra whitespace before this tag
include('includes/session.php');
include('includes/dbconnection.php');

// Security: Clear any previous output buffers
ob_clean(); 
header('Content-Type: application/json');

if (isset($_GET['account_number'])) {
    $acc_num = trim($_GET['account_number']);
    $current_student_id = $_SESSION['student_id'];

    // Exclude sender's own account using their account number if provided,
    // otherwise fall back to session student_id — handles multi-tab scenarios.
    $own_acc = isset($_GET['own_account']) ? trim($_GET['own_account']) : null;

    if ($own_acc) {
        $stmt = $con->prepare("
            SELECT account_name 
            FROM wallets 
            WHERE account_number = ? AND account_number != ?
        ");
        $stmt->bind_param("ss", $acc_num, $own_acc);
    } else {
        $stmt = $con->prepare("
            SELECT account_name 
            FROM wallets 
            WHERE account_number = ? AND student_id != ?
        ");
        $stmt->bind_param("si", $acc_num, $current_student_id);
    }
    $stmt->execute();
    $result = $stmt->get_result();

    if ($row = $result->fetch_assoc()) {
        // Return the account_name from the wallet table
        echo json_encode([
            'success' => true, 
            'name' => strtoupper($row['account_name'])
        ]);
    } else {
        echo json_encode([
            'success' => false, 
            'message' => 'Account not found'
        ]);
    }
    $stmt->close();
} else {
    echo json_encode(['success' => false, 'message' => 'No account number provided']);
}
exit();
?>