<?php
$totalRev = array_sum(array_map(fn($r) => (float)$r['revenue'], $cats ?? []));

// Group topItems by category
$itemsByCat = [];
foreach ($topItems ?? [] as $item) {
    $itemsByCat[$item['category']][] = $item;
}
?>

<div class="page-header mb-3">
    <div>
        <h1><i class="bi bi-grid-fill me-2 text-warning"></i>Category Performance</h1>
        <p class="text-muted">Sales breakdown per food category and top-selling items.</p>
    </div>
</div>

<?php include __DIR__ . '/_bi_nav.php'; ?>

<div class="row g-3 mb-4">
    <!-- Horizontal bar chart -->
    <div class="col-lg-6">
        <div class="card border-0 shadow-sm h-100">
        <div class="card-body">
            <h6 class="fw-bold mb-3"><i class="bi bi-bar-chart-horizontal me-1 text-warning"></i>Revenue by Category</h6>
            <canvas id="catChart" style="height:<?= max(180, count($cats ?? []) * 36) ?>px;"></canvas>
        </div>
        </div>
    </div>
    <!-- Category table -->
    <div class="col-lg-6">
        <div class="card border-0 shadow-sm h-100">
        <div class="card-body p-0">
            <table class="table table-hover align-middle mb-0 small">
            <thead class="table-light">
                <tr>
                    <th class="px-3">Category</th>
                    <th class="text-end">Revenue</th>
                    <th class="text-end">Share</th>
                    <th class="text-end">Orders</th>
                    <th class="text-end">Qty Sold</th>
                </tr>
            </thead>
            <tbody>
            <?php if (empty($cats)): ?>
                <tr><td colspan="5" class="text-center text-muted py-4">No data for this period.</td></tr>
            <?php else: ?>
            <?php foreach ($cats as $i => $cat):
                $share = $totalRev > 0 ? round((float)$cat['revenue'] / $totalRev * 100, 1) : 0;
                $colors = ['text-warning','text-success','text-info','text-primary','text-danger','text-secondary'];
                $cls = $colors[$i % count($colors)];
            ?>
            <tr>
                <td class="px-3 fw-semibold <?= $cls ?>"><?= e($cat['category'] ?? 'Uncategorised') ?></td>
                <td class="text-end"><?= money((float)$cat['revenue']) ?></td>
                <td class="text-end">
                    <div class="d-flex align-items-center justify-content-end gap-1">
                        <div class="progress flex-grow-1" style="height:6px;min-width:50px;">
                            <div class="progress-bar bg-warning" style="width:<?= $share ?>%"></div>
                        </div>
                        <span><?= $share ?>%</span>
                    </div>
                </td>
                <td class="text-end"><?= number_format((int)$cat['orders']) ?></td>
                <td class="text-end"><?= number_format((int)$cat['qty_sold']) ?></td>
            </tr>
            <?php endforeach ?>
            <?php endif ?>
            </tbody>
            </table>
        </div>
        </div>
    </div>
</div>

<!-- Top items per category -->
<?php foreach ($itemsByCat as $catName => $items): ?>
<div class="card border-0 shadow-sm mb-3">
<div class="card-header bg-transparent border-0 py-2 px-3">
    <h6 class="fw-bold mb-0"><i class="bi bi-tag me-1 text-secondary"></i><?= e($catName ?? 'Uncategorised') ?></h6>
</div>
<div class="card-body p-0">
    <table class="table table-sm align-middle mb-0 small">
    <thead class="table-light">
        <tr>
            <th class="px-3">#</th>
            <th>Item</th>
            <th class="text-end">Qty</th>
            <th class="text-end">Revenue</th>
        </tr>
    </thead>
    <tbody>
    <?php foreach (array_slice($items, 0, 5) as $rank => $itm): ?>
    <tr>
        <td class="px-3 text-muted"><?= $rank + 1 ?></td>
        <td><?= e($itm['item_name']) ?></td>
        <td class="text-end"><?= number_format((int)$itm['qty']) ?></td>
        <td class="text-end fw-semibold"><?= money((float)$itm['revenue']) ?></td>
    </tr>
    <?php endforeach ?>
    </tbody>
    </table>
</div>
</div>
<?php endforeach ?>

<?php if (empty($cats)): ?>
<div class="text-center text-muted py-5"><i class="bi bi-inbox fs-1 d-block mb-2"></i>No category data for selected period.</div>
<?php endif ?>

<?php ob_start(); ?>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
<?php if (!empty($cats)): ?>
new Chart(document.getElementById('catChart'), {
    type: 'bar',
    data: {
        labels: <?= json_encode(array_map(fn($r) => $r['category'] ?? 'Uncategorised', $cats)) ?>,
        datasets: [{
            label: 'Revenue',
            data: <?= json_encode(array_map(fn($r) => (float)$r['revenue'], $cats)) ?>,
            backgroundColor: [
                'rgba(249,115,22,.8)','rgba(34,197,94,.8)','rgba(59,130,246,.8)',
                'rgba(139,92,246,.8)','rgba(239,68,68,.8)','rgba(20,184,166,.8)',
                'rgba(234,179,8,.8)', 'rgba(99,102,241,.8)'
            ],
            borderRadius: 4
        }]
    },
    options: {
        indexAxis: 'y',
        responsive: true,
        maintainAspectRatio: false,
        plugins: { legend: { display: false } },
        scales: {
            x: { beginAtZero: true, ticks: { callback: v => 'Rs.'+v.toLocaleString() } },
            y: { grid: { display: false } }
        }
    }
});
<?php endif ?>
</script>
<?php $extraJs = ob_get_clean(); ?>
