<?php
$comp = $components ?? [];
$food     = (float)($comp['food_revenue']     ?? 0);
$delivery = (float)($comp['delivery_revenue'] ?? 0);
$tax      = (float)($comp['tax_revenue']      ?? 0);
$discount = (float)($comp['total_discount']   ?? 0);
$total    = (float)($summary['total_revenue'] ?? 0);
$days     = max(1, (int)(new \DateTime($to))->diff(new \DateTime($from))->days + 1);
?>

<div class="page-header mb-3">
    <div>
        <h1><i class="bi bi-graph-up-arrow me-2 text-success"></i>Revenue Analytics</h1>
        <p class="text-muted">Breakdown of revenue streams by time, day of week and components.</p>
    </div>
</div>

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

<!-- KPI strip -->
<div class="row g-3 mb-4">
    <div class="col-6 col-lg-3">
        <div class="card border-0 shadow-sm text-center py-3">
            <div class="fw-bold fs-4 text-success"><?= money($total) ?></div>
            <div class="text-muted small">Total Revenue</div>
        </div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card border-0 shadow-sm text-center py-3">
            <div class="fw-bold fs-4"><?= money($food) ?></div>
            <div class="text-muted small">Food Revenue</div>
        </div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card border-0 shadow-sm text-center py-3">
            <div class="fw-bold fs-4"><?= money($delivery) ?></div>
            <div class="text-muted small">Delivery Fees</div>
        </div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card border-0 shadow-sm text-center py-3">
            <div class="fw-bold fs-4 text-danger"><?= money($discount) ?></div>
            <div class="text-muted small">Discounts Given</div>
        </div>
    </div>
</div>

<div class="row g-3 mb-4">
    <!-- By hour -->
    <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>Revenue by Hour of Day</h6>
            <canvas id="hourChart" style="height:230px;"></canvas>
        </div>
        </div>
    </div>
    <!-- By day of week -->
    <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>Revenue by Day of Week</h6>
            <canvas id="dowChart" style="height:230px;"></canvas>
        </div>
        </div>
    </div>
</div>

<div class="row g-3 mb-4">
    <!-- Revenue components donut -->
    <div class="col-lg-4">
        <div class="card border-0 shadow-sm h-100">
        <div class="card-body">
            <h6 class="fw-bold mb-3"><i class="bi bi-pie-chart me-1 text-primary"></i>Revenue Components</h6>
            <canvas id="compChart" style="height:230px;"></canvas>
            <div class="mt-3">
                <?php foreach ([['Food','success',$food],['Delivery','info',$delivery],['Tax','warning',$tax]] as [$lbl,$cls,$val]): ?>
                <div class="d-flex justify-content-between small mb-1">
                    <span><span class="badge bg-<?= $cls ?> me-1"> </span><?= $lbl ?></span>
                    <span><?= money($val) ?></span>
                </div>
                <?php endforeach ?>
            </div>
        </div>
        </div>
    </div>
    <!-- Monthly trend -->
    <div class="col-lg-8">
        <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 me-1 text-success"></i>Monthly Revenue Trend</h6>
            <canvas id="monthlyChart" style="height:230px;"></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)): ?>
// Pad all 24 hours
const hrRevData = new Array(24).fill(0), hrOrdData = new Array(24).fill(0);
<?php foreach ($byHour as $r): ?> hrRevData[<?= (int)$r['hr'] ?>] = <?= (float)$r['revenue'] ?>; hrOrdData[<?= (int)$r['hr'] ?>] = <?= (int)$r['orders'] ?>; <?php endforeach ?>
new Chart(document.getElementById('hourChart'), {
    data: {
        labels: Array.from({length:24}, (_,i) => i+':00'),
        datasets: [
            { type:'bar', label:'Revenue', data: hrRevData, backgroundColor:'rgba(34,197,94,.7)', yAxisID:'y', borderRadius:3 },
            { type:'line', label:'Orders', data: hrOrdData, borderColor:'rgba(249,115,22,.9)', backgroundColor:'transparent', yAxisID:'y2', tension:.4, pointRadius:2 }
        ]
    },
    options: { responsive:true, maintainAspectRatio:false,
        plugins:{ legend:{ position:'top', labels:{ boxWidth:12 } } },
        scales: {
            y:  { beginAtZero:true, ticks:{ callback: v=>'Rs.'+v.toLocaleString() } },
            y2: { beginAtZero:true, position:'right', grid:{ drawOnChartArea:false }, ticks:{ stepSize:1 } }
        }
    }
});
<?php endif ?>

<?php if (!empty($byDow)): ?>
new Chart(document.getElementById('dowChart'), {
    data: {
        labels: <?= json_encode(array_map(fn($r)=>$r['day_name'], $byDow)) ?>,
        datasets: [
            { type:'bar', label:'Revenue', data: <?= json_encode(array_map(fn($r)=>(float)$r['revenue'], $byDow)) ?>,
              backgroundColor:'rgba(249,115,22,.7)', yAxisID:'y', borderRadius:3 },
            { type:'line', label:'Orders', data: <?= json_encode(array_map(fn($r)=>(int)$r['orders'], $byDow)) ?>,
              borderColor:'rgba(59,130,246,.9)', backgroundColor:'transparent', yAxisID:'y2', tension:.4, pointRadius:3 }
        ]
    },
    options: { responsive:true, maintainAspectRatio:false,
        plugins:{ legend:{ position:'top', labels:{ boxWidth:12 } } },
        scales: {
            y:  { beginAtZero:true, ticks:{ callback: v=>'Rs.'+v.toLocaleString() } },
            y2: { beginAtZero:true, position:'right', grid:{ drawOnChartArea:false } }
        }
    }
});
<?php endif ?>

new Chart(document.getElementById('compChart'), {
    type:'doughnut',
    data:{
        labels:['Food','Delivery','Tax'],
        datasets:[{ data:[<?= $food ?>,<?= $delivery ?>,<?= $tax ?>],
            backgroundColor:['rgba(34,197,94,.8)','rgba(59,130,246,.8)','rgba(234,179,8,.8)'],
            borderWidth:1 }]
    },
    options:{ responsive:true, maintainAspectRatio:false, cutout:'60%',
        plugins:{ legend:{ position:'bottom', labels:{ boxWidth:12 } } } }
});

<?php if (!empty($monthly)): ?>
new Chart(document.getElementById('monthlyChart'), {
    type:'bar',
    data:{
        labels: <?= json_encode(array_column($monthly,'month')) ?>,
        datasets:[{ label:'Revenue', data: <?= json_encode(array_map(fn($r)=>(float)$r['revenue'],$monthly)) ?>,
            backgroundColor:'rgba(34,197,94,.7)', borderRadius:4 }]
    },
    options:{ responsive:true, maintainAspectRatio:false,
        plugins:{ legend:{ display:false } },
        scales:{ y:{ beginAtZero:true, ticks:{ callback: v=>'Rs.'+v.toLocaleString() } }, x:{ grid:{ display:false } } }
    }
});
<?php endif ?>
</script>
<?php $extraJs = ob_get_clean(); ?>
