<?php
$selectedMonth = $selected_month;
$selectedYear  = $selected_year;

$daysInMonth = cal_days_in_month(CAL_GREGORIAN, $selectedMonth, $selectedYear);

// Fill daily totals
$this_expense = array_fill(1, $daysInMonth, 0);
foreach ($daily_expense as $row) {
    $day = (int)date('j', strtotime($row->date));
    $this_expense[$day] += (float)$row->amount;
}
?>

<div class="card">
    <div class="card-body">
        <canvas id="dailyExpenseChart" width="1000"  height="350"></canvas>
    </div>
</div>

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById("dailyExpenseChart").getContext("2d");
new Chart(ctx, {
    type: 'line',
    data: {
        labels: <?= json_encode(range(1, $daysInMonth)); ?>,
        datasets: [{
            label: 'Daily Expenses',
            data: <?= json_encode(array_values($this_expense)); ?>,
            borderColor: '#e91e63',
            backgroundColor: 'rgba(233, 30, 99, 0.15)',
            fill: true,
            tension: 0.3,
            pointRadius: 4,
            pointHoverRadius: 6
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: { display: false },
            tooltip: {
                callbacks: {
                    label: function(context) {
                        return 'Rs. ' + context.parsed.y.toLocaleString();
                    }
                }
            }
        },
        scales: {
            y: {
                beginAtZero: true,
                ticks: {
                    callback: function(value) {
                        return 'Rs. ' + value.toLocaleString();
                    }
                }
            },
            x: {
                title: {
                    display: false,
                    text: 'Day of Month'
                }
            }
        }
    }
});
</script>
