document.addEventListener('DOMContentLoaded', function () {
    const withdrawForm = document.querySelector('#withdrawForm');
    const creditForm = document.querySelector('#creditForm');
    const editUserForm = document.querySelector('#editUserForm');

    function showAlert(message, type = 'success') {
        const alertPlaceholder = document.getElementById('alertContainer');

        // Clear previous alerts
        alertPlaceholder.innerHTML = '';

        const alert = document.createElement('div');
        alert.className = `alert alert-${type} alert-dismissible fade show`;
        alert.setAttribute('role', 'alert');
        alert.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        `;

        alertPlaceholder.appendChild(alert);

        // Auto-dismiss after 3 seconds
        setTimeout(() => {
            const bsAlert = bootstrap.Alert.getOrCreateInstance(alert);
            bsAlert.close();
        }, 3000);
    }


    function fetchUsers() {
        fetch('/fetchUsers.php')
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    const tableBody = document.querySelector('#usersTable');
                    tableBody.innerHTML = '';

                    data.users.forEach(user => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>#${user.id}</td>
                            <td>${user.full_name}</td>
                            <td>${user.email}</td>
                            <td>$${parseFloat(user.account_balance).toFixed(2)}</td>
                            <td>
                                <span class="badge ${user.account_status === 'active' ? 'bg-success' : 'bg-danger'}">
                                    ${user.account_status}
                                </span>
                            </td>
                            <td>
                                <button class="btn btn-sm btn-danger" onclick='openEditModal(${JSON.stringify(user)})'>Edit</button>
                                <button class="btn btn-sm btn-warning" onclick="openWithdrawModal(${user.id}, '${user.full_name}')">Withdraw</button>
                                <button class="btn btn-sm btn-success" onclick="openCreditModal(${user.id}, '${user.full_name}')">Credit</button>
                                <button class="btn btn-sm btn-danger" onclick="deleteUser(${user.id})"><i class="bi bi-trash"></i></button>
                            </td>
                        `;
                        tableBody.appendChild(row);
                    });
                } else {
                    showAlert('Failed to fetch users.', 'danger');
                }
            })
            .catch(error => console.error('Error fetching users:', error));
    }

    fetchUsers();

    // Modal openers
    window.openWithdrawModal = function (userId, userName) {
        document.querySelector('#withdrawUserId').value = userId;
        document.querySelector('#withdrawUserName').textContent = userName;
        const modal = new bootstrap.Modal(document.getElementById('withdrawModal'));
        modal.show();
    };

    window.openCreditModal = function (userId, userName) {
        document.querySelector('#creditUserId').value = userId;
        document.querySelector('#creditUserName').textContent = userName;
        const modal = new bootstrap.Modal(document.getElementById('creditModal'));
        modal.show();
    };

    window.openEditModal = function (user) {
        document.querySelector('#editUserId').value = user.id;
        document.querySelector('#editFullName').value = user.full_name;
        document.querySelector('#editEmail').value = user.email;
        document.querySelector('#editAccountStatus').value = user.account_status;
        const modal = new bootstrap.Modal(document.getElementById('editModal'));
        modal.show();
    };
    
        window.deleteUser = function (userId) {
        if (!confirm('Are you sure you want to delete this user?')) return;

        fetch('/deleteUser.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ id: userId })
        })
        .then(res => res.json())
        .then(data => {
            showAlert(data.message, data.success ? 'success' : 'danger');
            if (data.success) {
                fetchUsers();
            }
        })
        .catch(err => {
            console.error('Delete user error:', err);
            showAlert('Something went wrong while deleting user.', 'danger');
        });
    }

    // Withdraw submission
    withdrawForm.addEventListener('submit', function (e) {
        e.preventDefault();
        const formData = new FormData(withdrawForm);
        fetch('/withdraw.php', {
            method: 'POST',
            body: formData
        })
        .then(res => res.json())
        .then(data => {
            showAlert(data.message, 'success');
            if (data.success) {
                bootstrap.Modal.getInstance(document.getElementById('withdrawModal')).hide();
                fetchUsers();
            }
        })
        .catch(err => console.error('Withdraw error:', err));
    });

    // Credit submission
    creditForm.addEventListener('submit', function (e) {
        e.preventDefault();
        const formData = new FormData(creditForm);
        fetch('/credit.php', {
            method: 'POST',
            body: formData
        })
        .then(res => res.json())
        .then(data => {
            showAlert(data.message, 'success');
            if (data.success) {
                bootstrap.Modal.getInstance(document.getElementById('creditModal')).hide();
                fetchUsers();
            }
        })
        .catch(err => console.error('Credit error:', err));
    });

    // Edit user submission
    editUserForm.addEventListener('submit', function (e) {
        e.preventDefault();
        const formData = new FormData(editUserForm);
        fetch('/editUser.php', {
            method: 'POST',
            body: formData
        })
        .then(res => res.json())
        .then(data => {
            showAlert(data.message, 'success');
            if (data.success) {
                bootstrap.Modal.getInstance(document.getElementById('editModal')).hide();
                fetchUsers();
            }
        })
        .catch(err => console.error('Edit user error:', err));
    });
});
