<?php
include '../config/koneksi.php';
include '../helpers/functions.php';

if (!isLogin() || !isAdmin()) redirect('../auth/login.php');

$data = mysqli_query($conn, "
    SELECT DATE(created_at) as tanggal, SUM(nominal) as total
    FROM transactions
    WHERE status='confirmed'
    GROUP BY DATE(created_at)
    ORDER BY DATE(created_at) ASC
");

$labels = [];
$totals = [];

while ($row = mysqli_fetch_assoc($data)) {
    $labels[] = $row['tanggal'];
    $totals[] = $row['total'];
}

$title = "Grafik";
include '../layouts/header.php';
?>

<div class="container-fluid">
    <div id="overlay" class="overlay"></div>

    <div class="row">
        <div class="col-lg-2 p-0">
            <?php include '../layouts/sidebar.php'; ?>
        </div>

        <div class="col-lg-10 p-0">
            <?php include '../layouts/navbar.php'; ?>

            <div class="content-wrap">
                <div class="card p-4">
                    <h4 class="section-title">Grafik Setoran Confirmed</h4>
                    <canvas id="grafikTabungan" height="100"></canvas>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
const ctx = document.getElementById('grafikTabungan');
new Chart(ctx, {
    type: 'bar',
    data: {
        labels: <?= json_encode($labels); ?>,
        datasets: [{
            label: 'Total Setoran',
            data: <?= json_encode($totals); ?>,
            borderWidth: 1
        }]
    },
    options: {
        responsive: true,
        scales: {
            y: { beginAtZero: true }
        }
    }
});
</script>

<?php include '../layouts/footer.php'; ?>