document.addEventListener('DOMContentLoaded', function() {
    function fetchUsers() {
             fetch("/get_users.php")
                .then(response => response.json())
                .then(data => {
                    const select = document.getElementById("userSelect");
                    data.forEach(user => {
                        const option = document.createElement("option");
                        option.value = user.id;
                        option.textContent = `${user.full_name} (${user.email})`;
                        select.appendChild(option);
                    });
                })
                .catch(error => {
                    console.error("Error fetching users:", error);
                });
    }
    document.getElementById('earningsForm').addEventListener('submit', function (e) {
        e.preventDefault();

       

        const userId = document.getElementById('userSelect').value;
        const amount = document.getElementById('amount').value;
        const description = document.getElementById('desc').value;

        fetch('/credit_earnings.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `user_id=${userId}&amount=${amount}&description=${encodeURIComponent(description)}`
        })
        .then(res => res.json())
        .then(data => {
            const feedback = document.getElementById('formFeedback');
            if (data.success) {
                feedback.innerHTML = `<div class="alert alert-success">${data.message}</div>`;
                document.getElementById('earningsForm').reset();
            } else {
                feedback.innerHTML = `<div class="alert alert-danger">${data.message}</div>`;
            }
        })

    })

    fetchUsers()
})