document.addEventListener('DOMContentLoaded', function() {
    function renderStatusBadge(status) {
        let color = "secondary";
        if (status === "approved") color = "success";
        else if (status === "pending") color = "warning";
        else if (status === "rejected" || status === "declined") color = "danger";
        return `<span class="badge bg-${color} status-badge">${status}</span>`;
    }

    


    function populateDeposits() {
        fetch("/get_deposits.php")
            .then(res => res.json())
            .then(deposits => {
                const tbody = document.getElementById("depositTableBody");
                tbody.innerHTML = deposits.map(dep => `
                    <tr>
                        <td>${dep.user_id}</td>
                        <td>$${dep.usd_amount}</td>
                        <td>${dep.crypto_amount}</td>
                        <td>${dep.crypto_type}</td>
                        <td>${dep.wallet_address}</td>
                        <td><a href="https://www.octaltrade.net/uploads/proofs/${dep.proof_file}" target="_blank">View</a></td>
                        <td>${renderStatusBadge(dep.status)}</td>
                        <td>
                            <button class="btn btn-sm btn-success me-1" onclick="updateStatus(${dep.id}, 'approved', 'deposit')">Approve</button>
                            <button class="btn btn-sm btn-warning me-1" onclick="updateStatus(${dep.id}, 'pending', 'deposit')">Pend</button>
                            <button class="btn btn-sm btn-danger" onclick="updateStatus(${dep.id}, 'rejected', 'deposit')">Reject</button>
                        </td>
                    </tr>
                `).join("");
            });
    }

    function populateWithdrawals() {
        fetch("/get_withdrawals.php")
            .then(res => res.json())
            .then(withdrawals => {
                const tbody = document.getElementById("withdrawalTableBody");
                tbody.innerHTML = withdrawals.map(wd => `
                    <tr>
                        <td>${wd.user_id}</td>
                        <td>$${wd.usd_amount}</td>
                        <td>${wd.crypto_amount}</td>
                        <td>${wd.crypto_type}</td>
                        <td>${wd.wallet_address}</td>
                        <td>${renderStatusBadge(wd.status)}</td>
                        <td>
                            <button class="btn btn-sm btn-success me-1" onclick="updateStatus(${wd.id}, 'approved', 'withdrawal')">Approve</button>
                            <button class="btn btn-sm btn-warning me-1" onclick="updateStatus(${wd.id}, 'pending', 'withdrawal')">Pend</button>
                            <button class="btn btn-sm btn-danger" onclick="updateStatus(${wd.id}, 'declined', 'withdrawal')">Decline</button>
                        </td>
                    </tr>
                `).join("");
            });
    }

    // Expose globally
    window.populateDeposits = populateDeposits;
    window.populateWithdrawals = populateWithdrawals;

    populateDeposits();
    populateWithdrawals();
});

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

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

        alertContainer.appendChild(alertDiv);

        // Auto-dismiss after X seconds (optional)
        if (timeout > 0) {
        setTimeout(() => {
            alertDiv.classList.remove('show');
            alertDiv.classList.add('fade');
            setTimeout(() => alertDiv.remove(), 300); // give it time to fade
        }, timeout);
        }
    }

function updateStatus(id, status, type) {
    const formData = new FormData();
    formData.append("id", id);
    formData.append("status", status);
    formData.append("type", type);

    fetch("/updateTransactionStatus.php", {
        method: "POST",
        body: formData
    })
    .then(res => res.json())
    .then(data => {
        if (data.status === "success") {
            showAlert(`${type.charAt(0).toUpperCase() + type.slice(1)} ${status} successfully!`, 'success');
            if (type === "deposit") window.populateDeposits();
            else window.populateWithdrawals();
        } else {
            showAlert(data.message, "danger");
        }
    })
    .catch(err => {
        console.error(err);
        showAlert("Something went wrong.", "danger");
    });
}


