<?php
$filter_year = $bar_year;
$monthly_data = $monthly_expense;

// Labels for months
$month_labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
$expense_totals = array_values($monthly_data);
?>

<div class="card">
    <div class="card-body">
        <div class="row">
            <div class="col-lg-12">
                <h4 class="card-title">Monthly Expenses (<?= $filter_year ?>)</h4>
            </div>
<!--             <div class="col-lg-12 text-right">
                <form method="get" class="form-inline justify-content-end">
                    <input type="hidden" name="month" value="<?= $selected_month ?>">
                    <input type="hidden" name="year" value="<?= $selected_year ?>">

                    <label class="mr-2">Select Year</label>
                    <select name="bar_year" class="form-control mr-2">
                        <?php for ($y = date('Y'); $y >= 2020; $y--): ?>
                            <option value="<?= $y ?>" <?= ($y == $filter_year ? 'selected' : '') ?>><?= $y ?></option>
                        <?php endfor; ?>
                    </select>

                    <button type="submit" class="btn btn-success">Filter</button>
                </form>
            </div> -->
        </div>

        <canvas id="monthlyExpenseChart" width="1000" height="1000"></canvas>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctxMonthly = document.getElementById("monthlyExpenseChart").getContext("2d");
new Chart(ctxMonthly, {
    type: 'bar',
    data: {
        labels: <?= json_encode($month_labels); ?>,
        datasets: [{
            label: 'Total',
            data: <?= json_encode($expense_totals); ?>,
            backgroundColor: '#03a9f3',
            borderColor: '#039be5',
            borderWidth: 1
        }]
    },
    options: {
        indexAxis: 'y', // <<< horizontal chart
        responsive: true,
        plugins: {
            legend: { display: false },
            tooltip: {
                callbacks: {
                    label: function(context) {
                        return 'Rs. ' + context.parsed.x.toLocaleString(); // changed from `y` to `x`
                    }
                }
            }
        },
        scales: {
            x: {
                beginAtZero: true,
                ticks: {
                    callback: function(value) {
                        return 'Rs. ' + value.toLocaleString();
                    }
                }
            }
        }
    }
});
</script>

