async function loadDashboard() {
    const response = await fetch('../api/admin_stats.php');
    const data = await response.json();

    renderStats(data.totals);
    renderWorkersChart(data.workersByStatus);
    renderMessagesChart(data.messagesPerDay);
    renderUsersChart(data.newUsersPerMonth);
}

function renderWorkersChart(rows) {
    new Chart(document.getElementById('workersChart'), {
        type: 'doughnut',
        data: {
            labels: rows.map(r => r.status),
            datasets: [{
                data: rows.map(r => r.total),
                borderWidth: 2
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });
}

function renderMessagesChart(rows) {
    new Chart(document.getElementById('messagesChart'), {
        type: 'line',
        data: {
            labels: rows.map(r => r.day),
            datasets: [{
                label: 'Messages',
                data: rows.map(r => r.total),
                tension: 0.35,
                fill: true
            }]
        },
        options: {
            responsive: true,
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
}

function renderUsersChart(rows) {
    new Chart(document.getElementById('usersChart'), {
        type: 'bar',
        data: {
            labels: rows.map(r => r.month),
            datasets: [{
                label: 'New Users',
                data: rows.map(r => r.total)
            }]
        },
        options: {
            responsive: true,
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
}

loadDashboard();