<?php
// Build heatmap matrix [dow][hr] => orders
$matrix = [];
$maxOrders = 1;
foreach ($heatmap ?? [] as $row) {
    $d = (int)$row['dow']; // 1=Sun .. 7=Sat
    $h = (int)$row['hr'];
    $n = (int)$row['orders'];
    $matrix[$d][$h] = $n;
    if ($n > $maxOrders) $maxOrders = $n;
}
$dayNames = [1=>'Sun',2=>'Mon',3=>'Tue',4=>'Wed',5=>'Thu',6=>'Fri',7=>'Sat'];
?>

<div class="page-header mb-3">
    <div>
        <h1><i class="bi bi-clock-history me-2 text-info"></i>Peak Hours</h1>
        <p class="text-muted">Order heatmap by hour and day — find your busiest windows.</p>
    </div>
</div>

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

<!-- Stat cards -->
<div class="row g-3 mb-4">
    <div class="col-md-6">
        <div class="card border-0 shadow-sm text-center py-4">
            <div class="display-6 fw-bold text-info"><?= $busiestHour['hr'] ?? '—' ?>:00</div>
            <div class="text-muted">Busiest Hour</div>
            <?php if (!empty($busiestHour)): ?>
            <div class="small text-secondary"><?= number_format((int)$busiestHour['orders']) ?> orders on average</div>
            <?php endif ?>
        </div>
    </div>
    <div class="col-md-6">
        <div class="card border-0 shadow-sm text-center py-4">
            <div class="display-6 fw-bold text-warning"><?= e($busiestDay['day_name'] ?? '—') ?></div>
            <div class="text-muted">Busiest Day</div>
            <?php if (!empty($busiestDay)): ?>
            <div class="small text-secondary"><?= number_format((int)$busiestDay['orders']) ?> orders this period</div>
            <?php endif ?>
        </div>
    </div>
</div>

<!-- Heatmap -->
<div class="card border-0 shadow-sm mb-4">
<div class="card-body">
    <h6 class="fw-bold mb-3"><i class="bi bi-grid me-1 text-primary"></i>Order Heatmap (Hour × Day)</h6>
    <div class="table-responsive">
    <table class="table table-bordered table-sm text-center mb-0" style="font-size:.75rem;">
    <thead>
        <tr>
            <th class="table-secondary" style="min-width:42px;">Hr</th>
            <?php for ($d=1;$d<=7;$d++): ?>
            <th class="table-secondary" style="min-width:46px;"><?= $dayNames[$d] ?></th>
            <?php endfor ?>
        </tr>
    </thead>
    <tbody>
    <?php for ($h = 0; $h < 24; $h++): ?>
    <tr>
        <td class="fw-semibold table-light text-muted"><?= $h ?>:00</td>
        <?php for ($d=1;$d<=7;$d++):
            $n = $matrix[$d][$h] ?? 0;
            $intensity = $maxOrders > 0 ? $n / $maxOrders : 0;
            $alpha = round($intensity * 0.85 + ($n > 0 ? 0.1 : 0), 2);
            $textColor = $intensity > 0.5 ? '#fff' : 'inherit';
        ?>
        <td style="background:rgba(249,115,22,<?= $alpha ?>);color:<?= $textColor ?>;font-weight:<?= $n > 0 ? '600' : '400' ?>;">
            <?= $n > 0 ? $n : '' ?>
        </td>
        <?php endfor ?>
    </tr>
    <?php endfor ?>
    </tbody>
    </table>
    </div>
    <div class="d-flex align-items-center gap-2 mt-2" style="font-size:.72rem;">
        <span class="text-muted">Low</span>
        <div style="height:10px;width:120px;background:linear-gradient(to right,rgba(249,115,22,.1),rgba(249,115,22,.9));border-radius:4px;"></div>
        <span class="text-muted">High</span>
    </div>
</div>
</div>

<div class="row g-3 mb-4">
    <!-- Orders by hour bar -->
    <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-clock me-1 text-info"></i>Orders by Hour</h6>
            <canvas id="hourChart" style="height:200px;"></canvas>
        </div>
        </div>
    </div>
    <!-- Orders by day -->
    <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-calendar3 me-1 text-warning"></i>Orders by Day of Week</h6>
            <canvas id="dowChart" style="height:200px;"></canvas>
        </div>
        </div>
    </div>
</div>

<?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($byHour)): ?>
const hrData = new Array(24).fill(0);
<?php foreach ($byHour as $r): ?> hrData[<?= (int)$r['hr'] ?>] = <?= (int)$r['orders'] ?>; <?php endforeach ?>
new Chart(document.getElementById('hourChart'), {
    type:'bar',
    data:{ labels: Array.from({length:24},(_,i)=>i+':00'), datasets:[{ label:'Orders', data:hrData,
        backgroundColor:'rgba(6,182,212,.75)', borderRadius:3 }] },
    options:{ responsive:true, maintainAspectRatio:false,
        plugins:{ legend:{ display:false } },
        scales:{ y:{ beginAtZero:true, ticks:{ stepSize:1 } }, x:{ grid:{ display:false } } }
    }
});
<?php endif ?>

<?php if (!empty($byDow)): ?>
new Chart(document.getElementById('dowChart'), {
    type:'bar',
    data:{ labels: <?= json_encode(array_map(fn($r)=>$r['day_name'],$byDow)) ?>,
        datasets:[{ label:'Orders', data: <?= json_encode(array_map(fn($r)=>(int)$r['orders'],$byDow)) ?>,
        backgroundColor:'rgba(249,115,22,.75)', borderRadius:3 }] },
    options:{ responsive:true, maintainAspectRatio:false,
        plugins:{ legend:{ display:false } },
        scales:{ y:{ beginAtZero:true, ticks:{ stepSize:1 } }, x:{ grid:{ display:false } } }
    }
});
<?php endif ?>
</script>
<?php $extraJs = ob_get_clean(); ?>
