<?php
/**
 * Admin Payments Management
 * View and manage all user payments
 */

session_start();
require_once '../db_connect.php';

// Allow both admin and user_admin roles
if(!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], ['admin', 'user_admin'])) {
    header('Location: ../login');
    exit;
}

$admin_id = $_SESSION['user_id'];
$error = '';
$success = '';
$current_year = date('Y');

// Get payment settings
$settings_result = mysqli_query($conn, "SELECT setting_key, setting_value FROM payment_settings");
$settings = [];
while($s = mysqli_fetch_assoc($settings_result)) {
    $settings[$s['setting_key']] = $s['setting_value'];
}
$yearly_fee = $settings['yearly_fee'] ?? 50000;

// Handle actions
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $action = $_POST['action'] ?? '';

    if($action == 'add_payment') {
        $user_id = intval($_POST['user_id']);
        $amount = floatval($_POST['amount']);
        $payment_year = intval($_POST['payment_year']);
        $payment_date = mysqli_real_escape_string($conn, $_POST['payment_date']);
        $payment_method = mysqli_real_escape_string($conn, $_POST['payment_method']);
        $reference = mysqli_real_escape_string($conn, trim($_POST['reference_number']));
        $notes = mysqli_real_escape_string($conn, trim($_POST['notes']));

        // Check if payment already exists for this year
        $check = mysqli_query($conn, "SELECT id FROM user_payments WHERE user_id = $user_id AND payment_year = $payment_year AND status = 'confirmed'");
        if(mysqli_num_rows($check) > 0) {
            $error = "Payment for year $payment_year already exists for this user";
        } else {
            $sql = "INSERT INTO user_payments (user_id, amount, payment_year, payment_date, payment_method, reference_number, notes, status, recorded_by, confirmed_by)
                    VALUES ($user_id, $amount, $payment_year, '$payment_date', '$payment_method', '$reference', '$notes', 'confirmed', $admin_id, $admin_id)";

            if(mysqli_query($conn, $sql)) {
                $success = 'Payment recorded successfully';
            } else {
                $error = 'Failed to record payment: ' . mysqli_error($conn);
            }
        }
    }

    if($action == 'cancel_payment') {
        $payment_id = intval($_POST['payment_id']);
        mysqli_query($conn, "UPDATE user_payments SET status = 'cancelled' WHERE id = $payment_id");
        $success = 'Payment cancelled';
    }
}

// Pagination
$per_page = 20;
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($page - 1) * $per_page;

// Filters
$filter_year = isset($_GET['year']) ? intval($_GET['year']) : $current_year;
$filter_status = isset($_GET['status']) ? mysqli_real_escape_string($conn, $_GET['status']) : '';
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

// Build WHERE clause
$where = "WHERE 1=1";
if($filter_year) {
    $where .= " AND up.payment_year = $filter_year";
}
if($filter_status) {
    $where .= " AND up.status = '$filter_status'";
}
if($search) {
    $search_escaped = mysqli_real_escape_string($conn, $search);
    $where .= " AND (u.full_name LIKE '%$search_escaped%' OR u.username LIKE '%$search_escaped%' OR u.phone LIKE '%$search_escaped%')";
}

// Get total count
$count_sql = "SELECT COUNT(*) as total FROM user_payments up JOIN users u ON up.user_id = u.id $where";
$total = mysqli_fetch_assoc(mysqli_query($conn, $count_sql))['total'];
$total_pages = ceil($total / $per_page);

// Get payments
$payments_sql = "SELECT up.*, u.full_name, u.username, u.phone, u.email,
                 admin.full_name as recorded_by_name
                 FROM user_payments up
                 JOIN users u ON up.user_id = u.id
                 LEFT JOIN users admin ON up.recorded_by = admin.id
                 $where
                 ORDER BY up.created_at DESC
                 LIMIT $per_page OFFSET $offset";
$payments = mysqli_query($conn, $payments_sql);

// Statistics
$stats = [
    'total_collected' => mysqli_fetch_assoc(mysqli_query($conn, "SELECT COALESCE(SUM(amount), 0) as total FROM user_payments WHERE payment_year = $current_year AND status = 'confirmed'"))['total'],
    'total_paid' => mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(DISTINCT user_id) as cnt FROM user_payments WHERE payment_year = $current_year AND status = 'confirmed'"))['cnt'],
    'total_users' => mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as cnt FROM users WHERE role IN ('user', 'broker') AND status = 'approved'"))['cnt'],
    'pending' => mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as cnt FROM user_payments WHERE status = 'pending'"))['cnt']
];
$stats['unpaid'] = $stats['total_users'] - $stats['total_paid'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Management - Admin</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../assets/font-awesome/css/all.min.css">
    <link href="../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <style>
        :root {
            --primary: #4f46e5;
            --success: #22c55e;
            --warning: #f59e0b;
            --danger: #ef4444;
        }
        body { font-family: 'Inter', sans-serif; background: #f1f5f9; }
        .sidebar { width: 260px; background: #1e293b; min-height: 100vh; position: fixed; }
        .main-content { margin-left: 260px; padding: 24px; }
        .stat-card { background: white; border-radius: 12px; padding: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
        .stat-card h3 { font-size: 28px; font-weight: 700; margin: 0; }
        .stat-card p { color: #64748b; margin: 4px 0 0; font-size: 13px; }
        .stat-icon { width: 48px; height: 48px; border-radius: 10px; display: flex; align-items: center; justify-content: center; color: white; font-size: 20px; }
        .table-card { background: white; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); overflow: hidden; }
        .table-header { padding: 20px; border-bottom: 1px solid #e2e8f0; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px; }
        .data-table { width: 100%; }
        .data-table th { padding: 12px 16px; background: #f8fafc; font-size: 12px; font-weight: 600; color: #64748b; text-transform: uppercase; }
        .data-table td { padding: 14px 16px; border-bottom: 1px solid #f1f5f9; font-size: 14px; }
        .badge { padding: 4px 10px; border-radius: 20px; font-size: 11px; font-weight: 600; }
        .badge-success { background: rgba(34, 197, 94, 0.1); color: var(--success); }
        .badge-warning { background: rgba(245, 158, 11, 0.1); color: var(--warning); }
        .badge-danger { background: rgba(239, 68, 68, 0.1); color: var(--danger); }
        .btn { padding: 8px 16px; border-radius: 8px; font-size: 13px; font-weight: 500; border: none; cursor: pointer; }
        .btn-primary { background: var(--primary); color: white; }
        .btn-outline { background: transparent; border: 1px solid #e2e8f0; color: #64748b; }
        .btn-danger { background: var(--danger); color: white; }
        .btn-sm { padding: 4px 10px; font-size: 12px; }
        .modal { display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 1000; align-items: center; justify-content: center; }
        .modal.active { display: flex; }
        .modal-content { background: white; border-radius: 16px; width: 90%; max-width: 500px; max-height: 90vh; overflow-y: auto; }
        .modal-header { padding: 20px; border-bottom: 1px solid #e2e8f0; display: flex; justify-content: space-between; align-items: center; }
        .modal-body { padding: 20px; }
        .modal-footer { padding: 16px 20px; border-top: 1px solid #e2e8f0; display: flex; justify-content: flex-end; gap: 10px; }
        .form-group { margin-bottom: 16px; }
        .form-label { display: block; font-size: 13px; font-weight: 600; color: #334155; margin-bottom: 6px; }
        .form-control { width: 100%; padding: 10px 14px; border: 2px solid #e2e8f0; border-radius: 8px; font-size: 14px; }
        .form-control:focus { outline: none; border-color: var(--primary); }
        .filter-bar { display: flex; gap: 12px; flex-wrap: wrap; align-items: center; }
        .filter-bar select, .filter-bar input { padding: 8px 12px; border: 1px solid #e2e8f0; border-radius: 8px; font-size: 13px; }
        .pagination { display: flex; gap: 6px; justify-content: center; padding: 20px; }
        .pagination a, .pagination span { width: 36px; height: 36px; display: flex; align-items: center; justify-content: center; border-radius: 8px; font-size: 13px; text-decoration: none; }
        .pagination a { background: white; color: #64748b; border: 1px solid #e2e8f0; }
        .pagination a:hover { background: #f1f5f9; }
        .pagination .active { background: var(--primary); color: white; }
        .alert { padding: 14px 18px; border-radius: 10px; margin-bottom: 20px; font-size: 14px; }
        .alert-success { background: #d4edda; color: #155724; }
        .alert-danger { background: #f8d7da; color: #721c24; }
        /* User Search Styles */
        .user-search-container { position: relative; }
        .search-results {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border: 1px solid #e2e8f0;
            border-top: none;
            border-radius: 0 0 8px 8px;
            max-height: 200px;
            overflow-y: auto;
            z-index: 100;
            display: none;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        .search-results.active { display: block; }
        .search-result-item {
            padding: 10px 14px;
            cursor: pointer;
            border-bottom: 1px solid #f1f5f9;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .search-result-item:hover { background: #f8fafc; }
        .search-result-item:last-child { border-bottom: none; }
        .search-result-item i { color: #64748b; font-size: 16px; }
        .search-result-item .user-info { flex: 1; }
        .search-result-item .user-name { font-weight: 500; color: #1e293b; }
        .search-result-item .user-phone { font-size: 12px; color: #64748b; }
        .search-result-item .no-results { color: #94a3b8; font-style: italic; text-align: center; padding: 20px; }
        .selected-user {
            display: flex;
            align-items: center;
            justify-content: space-between;
            background: #ecfdf5;
            border: 1px solid #10b981;
            border-radius: 8px;
            padding: 10px 14px;
            margin-top: 10px;
        }
        .selected-user-info { display: flex; align-items: center; gap: 10px; color: #065f46; font-weight: 500; }
        .selected-user-info i { font-size: 20px; color: #10b981; }
        .btn-clear { background: none; border: none; color: #dc2626; cursor: pointer; padding: 4px; }
        .btn-clear:hover { color: #b91c1c; }
        @media (max-width: 768px) {
            .sidebar { display: none; }
            .main-content { margin-left: 0; }
        }
    </style>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <div class="main-content">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h2 class="mb-1">Payment Management</h2>
                <p class="text-muted mb-0">Manage user subscription payments</p>
            </div>
            <button class="btn btn-primary" onclick="openModal()">
                <i class="fas fa-plus mr-2"></i> Record Payment
            </button>
        </div>

        <?php if($error): ?>
        <div class="alert alert-danger"><i class="fas fa-exclamation-circle mr-2"></i><?php echo $error; ?></div>
        <?php endif; ?>
        <?php if($success): ?>
        <div class="alert alert-success"><i class="fas fa-check-circle mr-2"></i><?php echo $success; ?></div>
        <?php endif; ?>

        <!-- Stats -->
        <div class="row mb-4">
            <div class="col-md-3 col-6 mb-3">
                <div class="stat-card">
                    <div class="d-flex align-items-center gap-3">
                        <div class="stat-icon" style="background: linear-gradient(135deg, #22c55e, #16a34a);">
                            <i class="fas fa-money-bill"></i>
                        </div>
                        <div>
                            <h3>TZS <?php echo number_format($stats['total_collected']); ?></h3>
                            <p>Collected <?php echo $current_year; ?></p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3 col-6 mb-3">
                <div class="stat-card">
                    <div class="d-flex align-items-center gap-3">
                        <div class="stat-icon" style="background: linear-gradient(135deg, #3b82f6, #2563eb);">
                            <i class="fas fa-user-check"></i>
                        </div>
                        <div>
                            <h3><?php echo $stats['total_paid']; ?></h3>
                            <p>Users Paid</p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3 col-6 mb-3">
                <div class="stat-card">
                    <div class="d-flex align-items-center gap-3">
                        <div class="stat-icon" style="background: linear-gradient(135deg, #f59e0b, #d97706);">
                            <i class="fas fa-user-clock"></i>
                        </div>
                        <div>
                            <h3><?php echo $stats['unpaid']; ?></h3>
                            <p>Unpaid</p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3 col-6 mb-3">
                <div class="stat-card">
                    <div class="d-flex align-items-center gap-3">
                        <div class="stat-icon" style="background: linear-gradient(135deg, #8b5cf6, #7c3aed);">
                            <i class="fas fa-receipt"></i>
                        </div>
                        <div>
                            <h3>TZS <?php echo number_format($yearly_fee); ?></h3>
                            <p>Yearly Fee</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Payments Table -->
        <div class="table-card">
            <div class="table-header">
                <h5 class="mb-0">Payment Records</h5>
                <form class="filter-bar" method="GET">
                    <input type="text" name="search" placeholder="Search user..." value="<?php echo htmlspecialchars($search); ?>">
                    <select name="year">
                        <?php for($y = $current_year + 1; $y >= $current_year - 5; $y--): ?>
                        <option value="<?php echo $y; ?>" <?php echo $filter_year == $y ? 'selected' : ''; ?>><?php echo $y; ?></option>
                        <?php endfor; ?>
                    </select>
                    <select name="status">
                        <option value="">All Status</option>
                        <option value="confirmed" <?php echo $filter_status == 'confirmed' ? 'selected' : ''; ?>>Confirmed</option>
                        <option value="pending" <?php echo $filter_status == 'pending' ? 'selected' : ''; ?>>Pending</option>
                        <option value="cancelled" <?php echo $filter_status == 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                    </select>
                    <button type="submit" class="btn btn-outline"><i class="fas fa-filter"></i></button>
                </form>
            </div>

            <div class="table-responsive">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>User</th>
                            <th>Year</th>
                            <th>Amount</th>
                            <th>Date</th>
                            <th>Method</th>
                            <th>Status</th>
                            <th>Recorded By</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(mysqli_num_rows($payments) == 0): ?>
                        <tr><td colspan="8" class="text-center py-4 text-muted">No payments found</td></tr>
                        <?php else: ?>
                        <?php while($p = mysqli_fetch_assoc($payments)): ?>
                        <tr>
                            <td>
                                <strong><?php echo htmlspecialchars($p['full_name'] ?: $p['username']); ?></strong>
                                <br><small class="text-muted"><?php echo htmlspecialchars($p['phone']); ?></small>
                            </td>
                            <td><?php echo $p['payment_year']; ?></td>
                            <td>TZS <?php echo number_format($p['amount'], 2); ?></td>
                            <td><?php echo date('d M Y', strtotime($p['payment_date'])); ?></td>
                            <td><?php echo ucfirst(str_replace('_', ' ', $p['payment_method'])); ?></td>
                            <td>
                                <span class="badge badge-<?php echo $p['status'] == 'confirmed' ? 'success' : ($p['status'] == 'pending' ? 'warning' : 'danger'); ?>">
                                    <?php echo ucfirst($p['status']); ?>
                                </span>
                            </td>
                            <td><?php echo htmlspecialchars($p['recorded_by_name'] ?: 'System'); ?></td>
                            <td>
                                <?php if($p['status'] != 'cancelled'): ?>
                                <form method="POST" style="display:inline;" onsubmit="return confirm('Cancel this payment?')">
                                    <input type="hidden" name="action" value="cancel_payment">
                                    <input type="hidden" name="payment_id" value="<?php echo $p['id']; ?>">
                                    <button type="submit" class="btn btn-danger btn-sm"><i class="fas fa-times"></i></button>
                                </form>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <?php if($total_pages > 1): ?>
            <div class="pagination">
                <?php if($page > 1): ?>
                <a href="?page=<?php echo $page - 1; ?>&year=<?php echo $filter_year; ?>&status=<?php echo $filter_status; ?>&search=<?php echo urlencode($search); ?>"><i class="fas fa-chevron-left"></i></a>
                <?php endif; ?>
                <?php for($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                <?php if($i == $page): ?>
                <span class="active"><?php echo $i; ?></span>
                <?php else: ?>
                <a href="?page=<?php echo $i; ?>&year=<?php echo $filter_year; ?>&status=<?php echo $filter_status; ?>&search=<?php echo urlencode($search); ?>"><?php echo $i; ?></a>
                <?php endif; ?>
                <?php endfor; ?>
                <?php if($page < $total_pages): ?>
                <a href="?page=<?php echo $page + 1; ?>&year=<?php echo $filter_year; ?>&status=<?php echo $filter_status; ?>&search=<?php echo urlencode($search); ?>"><i class="fas fa-chevron-right"></i></a>
                <?php endif; ?>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Add Payment Modal -->
    <div class="modal" id="paymentModal">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="mb-0"><i class="fas fa-plus mr-2"></i>Record Payment</h5>
                <button class="btn btn-outline btn-sm" onclick="closeModal()">&times;</button>
            </div>
            <form method="POST" id="paymentForm">
                <input type="hidden" name="action" value="add_payment">
                <input type="hidden" name="user_id" id="selected_user_id" value="">
                <div class="modal-body">
                    <div class="form-group">
                        <label class="form-label">Search User (Name or Phone) *</label>
                        <div class="user-search-container">
                            <input type="text" id="userSearchInput" class="form-control" placeholder="Type name or phone number..." autocomplete="off">
                            <div id="userSearchResults" class="search-results"></div>
                        </div>
                        <div id="selectedUserDisplay" class="selected-user" style="display: none;">
                            <div class="selected-user-info">
                                <i class="fas fa-user-circle"></i>
                                <span id="selectedUserName"></span>
                            </div>
                            <button type="button" class="btn-clear" onclick="clearSelectedUser()"><i class="fas fa-times"></i></button>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-6">
                            <div class="form-group">
                                <label class="form-label">Amount (TZS) *</label>
                                <input type="number" name="amount" class="form-control" value="<?php echo $yearly_fee; ?>" required>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="form-group">
                                <label class="form-label">Payment Year *</label>
                                <select name="payment_year" class="form-control" required>
                                    <?php for($y = $current_year + 1; $y >= $current_year - 2; $y--): ?>
                                    <option value="<?php echo $y; ?>" <?php echo $y == $current_year ? 'selected' : ''; ?>><?php echo $y; ?></option>
                                    <?php endfor; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-6">
                            <div class="form-group">
                                <label class="form-label">Payment Date *</label>
                                <input type="date" name="payment_date" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="form-group">
                                <label class="form-label">Payment Method</label>
                                <select name="payment_method" class="form-control">
                                    <option value="cash">Cash</option>
                                    <option value="bank_transfer">Bank Transfer</option>
                                    <option value="mobile_money">Mobile Money</option>
                                    <option value="other">Other</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Reference Number</label>
                        <input type="text" name="reference_number" class="form-control" placeholder="Transaction ID">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Notes</label>
                        <textarea name="notes" class="form-control" rows="2"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline" onclick="closeModal()">Cancel</button>
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save mr-2"></i>Save Payment</button>
                </div>
            </form>
        </div>
    </div>

    <script src="../assets/vendor/jquery/jquery.min.js"></script>
    <script src="../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
        function openModal() {
            document.getElementById('paymentModal').classList.add('active');
            document.getElementById('userSearchInput').focus();
        }
        function closeModal() {
            document.getElementById('paymentModal').classList.remove('active');
            clearSelectedUser();
            document.getElementById('userSearchInput').value = '';
            document.getElementById('userSearchResults').classList.remove('active');
        }
        document.addEventListener('keydown', e => { if(e.key === 'Escape') closeModal(); });

        // User search functionality
        const userSearchInput = document.getElementById('userSearchInput');
        const userSearchResults = document.getElementById('userSearchResults');
        const selectedUserDisplay = document.getElementById('selectedUserDisplay');
        const selectedUserIdInput = document.getElementById('selected_user_id');
        const selectedUserName = document.getElementById('selectedUserName');
        let searchTimeout;

        userSearchInput.addEventListener('input', function() {
            clearTimeout(searchTimeout);
            const query = this.value.trim();

            if(query.length < 2) {
                userSearchResults.classList.remove('active');
                return;
            }

            searchTimeout = setTimeout(() => {
                searchUsers(query);
            }, 300);
        });

        userSearchInput.addEventListener('focus', function() {
            if(this.value.trim().length >= 2) {
                searchUsers(this.value.trim());
            }
        });

        function searchUsers(query) {
            fetch('ajax/search_users.php?q=' + encodeURIComponent(query))
                .then(response => response.json())
                .then(data => {
                    if(data.length === 0) {
                        userSearchResults.innerHTML = '<div class="search-result-item"><div class="no-results">No users found</div></div>';
                    } else {
                        userSearchResults.innerHTML = data.map(user => `
                            <div class="search-result-item" onclick="selectUser(${user.id}, '${escapeHtml(user.full_name || user.username)}', '${escapeHtml(user.phone || '')}')">
                                <i class="fas fa-user-circle"></i>
                                <div class="user-info">
                                    <div class="user-name">${escapeHtml(user.full_name || user.username)}</div>
                                    <div class="user-phone">${escapeHtml(user.phone || 'No phone')}</div>
                                </div>
                            </div>
                        `).join('');
                    }
                    userSearchResults.classList.add('active');
                })
                .catch(err => {
                    console.error('Search error:', err);
                    userSearchResults.innerHTML = '<div class="search-result-item"><div class="no-results">Error searching users</div></div>';
                    userSearchResults.classList.add('active');
                });
        }

        function selectUser(id, name, phone) {
            selectedUserIdInput.value = id;
            selectedUserName.textContent = name + (phone ? ' (' + phone + ')' : '');
            selectedUserDisplay.style.display = 'flex';
            userSearchInput.style.display = 'none';
            userSearchResults.classList.remove('active');
        }

        function clearSelectedUser() {
            selectedUserIdInput.value = '';
            selectedUserName.textContent = '';
            selectedUserDisplay.style.display = 'none';
            userSearchInput.style.display = 'block';
            userSearchInput.value = '';
            userSearchInput.focus();
        }

        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // Close search results when clicking outside
        document.addEventListener('click', function(e) {
            if(!e.target.closest('.user-search-container')) {
                userSearchResults.classList.remove('active');
            }
        });

        // Form validation
        document.getElementById('paymentForm').addEventListener('submit', function(e) {
            if(!selectedUserIdInput.value) {
                e.preventDefault();
                alert('Please select a user first');
                userSearchInput.focus();
            }
        });
    </script>
</body>
</html>
