<?php
$db = Database::getInstance();
$dist = $db->fetchAll(
    "SELECT mt.name_en, mt.color_hex, COUNT(m.id) AS cnt
     FROM membership_types mt LEFT JOIN members m ON m.membership_type_id = mt.id AND m.status = 'active' AND m.is_deleted = 0
     WHERE mt.is_active = 1 GROUP BY mt.id ORDER BY cnt DESC"
);
$labels = array_column($dist, 'name_en');
$values = array_column($dist, 'cnt');
$colors = array_map(fn($d) => $d['color_hex'] ?: '#' . substr(md5($d['name_en']), 0, 6), $dist);
?>
<div class="card h-100">
    <div class="card-body">
        <h6 class="text-muted mb-3"><?= lang('members.distribution') ?></h6>
        <canvas id="chart-distribution" height="200"></canvas>
    </div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
    new Chart(document.getElementById('chart-distribution'), {
        type: 'doughnut',
        data: {
            labels: <?= json_encode($labels) ?>,
            datasets: [{ data: <?= json_encode(array_map('intval', $values)) ?>, backgroundColor: <?= json_encode($colors) ?> }]
        },
        options: { responsive: true, plugins: { legend: { position: 'bottom', labels: { boxWidth: 12, font: { size: 11 } } } } }
    });
});
</script>