<?php
$this->title = "Top 10 Produk Terlaris";
?>

<div class="row">

<!-- ================= LEFT : GRID ================= -->
<div class="col-md-6">
    <div class="card shadow-sm">
        <div class="card-header bg-dark text-white">
            <strong>Top 10 Produk Bulan Ini</strong>
        </div>

        <div class="card-body p-0">
            <table class="table table-striped mb-0">
                <thead class="table-dark">
                    <tr>
                        <th>#</th>
                        <th>Produk</th>
                        <th>Qty</th>
                        <th>Omset</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $no=1; foreach($data as $d): ?>
                    <tr>
                        <td><?= $no++ ?></td>
                        <td><?= $d['nama'] ?></td>
                        <td><?= number_format($d['total_qty']) ?></td>
                        <td>Rp <?= number_format($d['total_omset']) ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- ================= RIGHT : CHART ================= -->
<div class="col-md-6">
    <div class="card shadow-sm">
        <div class="card-header bg-primary text-white">
            <strong>Grafik Penjualan</strong>
        </div>
        <div class="card-body">
            <canvas id="topProdukChart"></canvas>
        </div>
    </div>
</div>

</div>
<?php
$labels = [];
$qty = [];

foreach($data as $d){
    $labels[] = $d['nama'];
    $qty[] = (int)$d['total_qty'];
}

$labelsJson = json_encode($labels);
$qtyJson = json_encode($qty);
?>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById('topProdukChart');

new Chart(ctx, {
    type: 'bar',
    data: {
        labels: <?= $labelsJson ?>,
        datasets: [{
            label: 'Qty Terjual',
            data: <?= $qtyJson ?>,
            backgroundColor: [
                '#4e73df','#1cc88a','#36b9cc','#f6c23e',
                '#e74a3b','#858796','#5a5c69','#20c9a6',
                '#6610f2','#fd7e14'
            ]
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: { display: false }
        }
    }
});
</script>
