<?php
$type_labels = [];
$type_totals = [];

foreach ($type_wise_expense as $type) {
    $type_labels[] = $type->expense_type;
    $type_totals[] = (float)$type->total;
}
?>

<div class="card">
    <div class="card-body">
        <canvas id="expenseTypePieChart" width="1000"  height="350"></canvas>
    </div>
</div>
<!-- Load jQuery first -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<!-- Load Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
const pieCtx = document.getElementById("expenseTypePieChart").getContext("2d");

new Chart(pieCtx, {
    type: 'pie',
    data: {
        labels: <?= json_encode($type_labels) ?>,
        datasets: [{
            data: <?= json_encode($type_totals) ?>,
            backgroundColor: [
                '#03a9f3', '#f44336', '#8bc34a', '#ff9800',
                '#9c27b0', '#00bcd4', '#ffc107', '#e91e63',
                '#4caf50', '#607d8b', '#ff5722', '#673ab7'
            ]
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: {
                position: 'bottom',
            },
            tooltip: {
                callbacks: {
                    label: function(context) {
                        let label = context.label || '';
                        let value = context.parsed;
                        return label + ': Rs. ' + value.toLocaleString();
                    }
                }
            }
        }
    }
});
</script>
