<?php
$rev     = (float)($summary['total_revenue']  ?? 0);
$prevRev = (float)($prevSummary['total_revenue'] ?? 0);
$revGrowth = $prevRev > 0 ? round(($rev - $prevRev) / $prevRev * 100, 1) : 0;

$orders     = (int)($summary['total_orders']     ?? 0);
$prevOrders = (int)($prevSummary['total_orders'] ?? 0);
$ordGrowth  = $prevOrders > 0 ? round(($orders - $prevOrders) / $prevOrders * 100, 1) : 0;

function growth_badge(float $pct): string {
    if ($pct > 0) return '<span class="badge bg-success ms-1">▲ '.$pct.'%</span>';
    if ($pct < 0) return '<span class="badge bg-danger ms-1">▼ '.abs($pct).'%</span>';
    return '<span class="badge bg-secondary ms-1">—</span>';
}
?>

<div class="page-header mb-3">
    <div>
        <h1><i class="bi bi-speedometer2 me-2 text-primary"></i>Business Intelligence</h1>
        <p class="text-muted">Executive overview — revenue, orders, customers at a glance.</p>
    </div>
</div>

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

<!-- KPI Cards -->
<div class="row g-3 mb-4">
    <div class="col-6 col-lg-3">
        <div class="card border-0 shadow-sm h-100">
        <div class="card-body">
            <div class="text-muted small mb-1"><i class="bi bi-currency-dollar me-1"></i>Total Revenue</div>
            <div class="fw-bold fs-4"><?= money($rev) ?></div>
            <?= growth_badge($revGrowth) ?>
            <div class="text-muted" style="font-size:.72rem;margin-top:2px;">vs previous period</div>
        </div>
        </div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card border-0 shadow-sm h-100">
        <div class="card-body">
            <div class="text-muted small mb-1"><i class="bi bi-bag-fill me-1"></i>Total Orders</div>
            <div class="fw-bold fs-4"><?= number_format($orders) ?></div>
            <?= growth_badge($ordGrowth) ?>
            <div class="text-muted" style="font-size:.72rem;margin-top:2px;">vs previous period</div>
        </div>
        </div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card border-0 shadow-sm h-100">
        <div class="card-body">
            <div class="text-muted small mb-1"><i class="bi bi-receipt me-1"></i>Avg Order Value</div>
            <div class="fw-bold fs-4"><?= money((float)($summary['avg_order_value'] ?? 0)) ?></div>
            <div class="text-muted" style="font-size:.72rem;margin-top:6px;">delivered orders only</div>
        </div>
        </div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card border-0 shadow-sm h-100">
        <div class="card-body">
            <div class="text-muted small mb-1"><i class="bi bi-people me-1"></i>New Customers</div>
            <div class="fw-bold fs-4"><?= number_format($newCustomers) ?></div>
            <div class="text-muted" style="font-size:.72rem;margin-top:6px;"><?= number_format((int)($summary['unique_customers'] ?? 0)) ?> ordered this period</div>
        </div>
        </div>
    </div>
</div>

<!-- Order status breakdown -->
<div class="row g-3 mb-4">
    <div class="col-md-4">
        <div class="card border-0 shadow-sm text-center py-3">
            <div class="text-success fw-bold fs-3"><?= number_format((int)($summary['delivered_orders'] ?? 0)) ?></div>
            <div class="text-muted small">Delivered</div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card border-0 shadow-sm text-center py-3">
            <div class="text-warning fw-bold fs-3"><?= number_format((int)($summary['active_orders'] ?? 0)) ?></div>
            <div class="text-muted small">In Progress</div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card border-0 shadow-sm text-center py-3">
            <div class="text-danger fw-bold fs-3"><?= number_format((int)($summary['cancelled_orders'] ?? 0)) ?></div>
            <div class="text-muted small">Cancelled</div>
        </div>
    </div>
</div>

<div class="row g-3 mb-4">
    <!-- Daily Revenue + Orders chart -->
    <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-graph-up me-1 text-primary"></i>Daily Revenue & Orders</h6>
            <canvas id="dailyChart" style="height:220px;"></canvas>
        </div>
        </div>
    </div>

    <!-- Payment + Type donuts -->
    <div class="col-lg-4">
        <div class="card border-0 shadow-sm mb-3">
        <div class="card-body pb-2">
            <h6 class="fw-bold mb-2" style="font-size:.85rem;"><i class="bi bi-credit-card me-1 text-success"></i>Payment Method</h6>
            <canvas id="paymentChart" style="height:130px;"></canvas>
        </div>
        </div>
        <div class="card border-0 shadow-sm">
        <div class="card-body pb-2">
            <h6 class="fw-bold mb-2" style="font-size:.85rem;"><i class="bi bi-box2 me-1 text-warning"></i>Order Type</h6>
            <canvas id="typeChart" style="height:130px;"></canvas>
        </div>
        </div>
    </div>
</div>

<!-- 6-month trend -->
<?php if (!empty($monthly)): ?>
<div class="card border-0 shadow-sm mb-4">
<div class="card-body">
    <h6 class="fw-bold mb-3"><i class="bi bi-bar-chart me-1 text-info"></i>Monthly Revenue — Last 6 Months</h6>
    <canvas id="monthlyChart" style="height:200px;"></canvas>
</div>
</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>
const ACCENT = 'rgba(249,115,22,.8)';
const BLUE   = 'rgba(59,130,246,.8)';
const GREEN  = 'rgba(34,197,94,.8)';
const RED    = 'rgba(239,68,68,.8)';

<?php if (!empty($daily)): ?>
new Chart(document.getElementById('dailyChart'), {
    data: {
        labels: <?= json_encode(array_column($daily, 'd')) ?>,
        datasets: [
            { type:'bar',  label:'Revenue', data: <?= json_encode(array_map(fn($r)=>(float)$r['revenue'], $daily)) ?>,
              backgroundColor: ACCENT, yAxisID:'y', borderRadius:3 },
            { type:'line', label:'Orders',  data: <?= json_encode(array_map(fn($r)=>(int)$r['orders'], $daily)) ?>,
              borderColor: BLUE, backgroundColor:'transparent', yAxisID:'y2', tension:.4, pointRadius:3 }
        ]
    },
    options: { responsive:true, maintainAspectRatio:false,
        plugins:{ legend:{ position:'top', labels:{ boxWidth:12 } } },
        scales:{
            y:  { beginAtZero:true, position:'left',  ticks:{ callback: v => 'Rs.'+v.toLocaleString() } },
            y2: { beginAtZero:true, position:'right', grid:{ drawOnChartArea:false }, ticks:{ stepSize:1 } }
        }
    }
});
<?php endif ?>

<?php if (!empty($paymentSplit)): ?>
new Chart(document.getElementById('paymentChart'), {
    type:'doughnut',
    data:{
        labels: <?= json_encode(array_map(fn($r)=>ucfirst($r['payment_method']), $paymentSplit)) ?>,
        datasets:[{ data: <?= json_encode(array_map(fn($r)=>(int)$r['cnt'], $paymentSplit)) ?>,
            backgroundColor:['rgba(34,197,94,.8)','rgba(59,130,246,.8)','rgba(249,115,22,.8)'],
            borderWidth:1 }]
    },
    options:{ responsive:true, maintainAspectRatio:false, cutout:'65%',
        plugins:{ legend:{ position:'right', labels:{ boxWidth:10, font:{size:11} } } } }
});
<?php endif ?>

<?php if (!empty($typeSplit)): ?>
new Chart(document.getElementById('typeChart'), {
    type:'doughnut',
    data:{
        labels: <?= json_encode(array_map(fn($r)=>ucfirst($r['order_type']), $typeSplit)) ?>,
        datasets:[{ data: <?= json_encode(array_map(fn($r)=>(int)$r['cnt'], $typeSplit)) ?>,
            backgroundColor:['rgba(249,115,22,.8)','rgba(139,92,246,.8)','rgba(20,184,166,.8)'],
            borderWidth:1 }]
    },
    options:{ responsive:true, maintainAspectRatio:false, cutout:'65%',
        plugins:{ legend:{ position:'right', labels:{ boxWidth:10, font:{size:11} } } } }
});
<?php endif ?>

<?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: ACCENT, 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(); ?>
