<?php
$total      = (int)($summary['total_orders']     ?? 0);
$cancelled  = (int)($summary['cancelled_orders'] ?? 0);
$rate       = $total > 0 ? round($cancelled / $total * 100, 1) : 0;
$valueLost  = array_sum(array_map(fn($r) => (float)$r['value_lost'], $byDay ?? []));
$gvr        = $guestVsReg[0] ?? [];
$regCanc    = (int)($gvr['registered'] ?? 0);
$guestCanc  = (int)($gvr['guest']      ?? 0);
?>

<div class="page-header mb-3">
    <div>
        <h1><i class="bi bi-x-circle-fill me-2 text-danger"></i>Cancellation Analysis</h1>
        <p class="text-muted">When cancellations happen, how much is lost, and who cancels most.</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-3 text-danger"><?= $cancelled ?></div>
            <div class="text-muted small">Cancelled Orders</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-3 <?= $rate > 15 ? 'text-danger' : ($rate > 8 ? 'text-warning' : 'text-success') ?>"><?= $rate ?>%</div>
            <div class="text-muted small">Cancellation Rate</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-3 text-danger"><?= money($valueLost) ?></div>
            <div class="text-muted small">Revenue Lost</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-3"><?= $total > 0 ? number_format($total - $cancelled) : '0' ?></div>
            <div class="text-muted small">Completed / Active</div>
        </div>
    </div>
</div>

<div class="row g-3 mb-4">
    <!-- Cancellations by hour -->
    <div class="col-lg-7">
        <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-danger"></i>Cancellations by Hour</h6>
            <canvas id="hourChart" style="height:210px;"></canvas>
        </div>
        </div>
    </div>
    <!-- Guest vs Registered donut -->
    <div class="col-lg-5">
        <div class="card border-0 shadow-sm h-100">
        <div class="card-body d-flex flex-column justify-content-center">
            <h6 class="fw-bold mb-3"><i class="bi bi-person-badge me-1 text-warning"></i>Guest vs. Registered</h6>
            <canvas id="gvrChart" style="height:180px;"></canvas>
            <div class="mt-3 text-center small">
                <span class="me-3"><span class="badge bg-warning text-dark me-1">Guest</span><?= $guestCanc ?></span>
                <span><span class="badge bg-primary me-1">Registered</span><?= $regCanc ?></span>
            </div>
        </div>
        </div>
    </div>
</div>

<!-- Daily cancellation value lost -->
<?php if (!empty($byDay)): ?>
<div class="card border-0 shadow-sm mb-4">
<div class="card-body">
    <h6 class="fw-bold mb-3"><i class="bi bi-graph-down me-1 text-danger"></i>Daily Value Lost to Cancellations</h6>
    <canvas id="dayChart" style="height:180px;"></canvas>
</div>
</div>
<?php endif ?>

<!-- Cancellation by day table -->
<?php if (!empty($byDay)): ?>
<div class="card border-0 shadow-sm mb-4">
<div class="card-body p-0">
    <table class="table table-hover table-sm align-middle mb-0 small">
    <thead class="table-light">
        <tr>
            <th class="px-3">Date</th>
            <th class="text-end">Cancelled</th>
            <th class="text-end">Value Lost</th>
        </tr>
    </thead>
    <tbody>
    <?php foreach ($byDay as $row): ?>
    <tr>
        <td class="px-3"><?= $row['d'] ?></td>
        <td class="text-end text-danger fw-semibold"><?= number_format((int)$row['cancelled']) ?></td>
        <td class="text-end"><?= money((float)$row['value_lost']) ?></td>
    </tr>
    <?php endforeach ?>
    </tbody>
    </table>
</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>
<?php if (!empty($byHour)): ?>
const hrCanc = new Array(24).fill(0);
<?php foreach ($byHour as $r): ?> hrCanc[<?= (int)$r['hr'] ?>] = <?= (int)$r['cancelled'] ?>; <?php endforeach ?>
new Chart(document.getElementById('hourChart'), {
    type:'bar',
    data:{ labels: Array.from({length:24},(_,i)=>i+':00'),
        datasets:[{ label:'Cancellations', data:hrCanc, backgroundColor:'rgba(239,68,68,.7)', borderRadius:3 }] },
    options:{ responsive:true, maintainAspectRatio:false,
        plugins:{ legend:{ display:false } },
        scales:{ y:{ beginAtZero:true, ticks:{ stepSize:1 } }, x:{ grid:{ display:false } } }
    }
});
<?php endif ?>

new Chart(document.getElementById('gvrChart'), {
    type:'doughnut',
    data:{
        labels:['Guest','Registered'],
        datasets:[{ data:[<?= $guestCanc ?>,<?= $regCanc ?>],
            backgroundColor:['rgba(234,179,8,.8)','rgba(59,130,246,.8)'], borderWidth:1 }]
    },
    options:{ responsive:true, maintainAspectRatio:false, cutout:'60%',
        plugins:{ legend:{ position:'bottom', labels:{ boxWidth:12 } } } }
});

<?php if (!empty($byDay)): ?>
new Chart(document.getElementById('dayChart'), {
    data:{
        labels: <?= json_encode(array_column($byDay,'d')) ?>,
        datasets:[
            { type:'bar',  label:'Value Lost', data: <?= json_encode(array_map(fn($r)=>(float)$r['value_lost'],$byDay)) ?>,
              backgroundColor:'rgba(239,68,68,.6)', borderRadius:3, yAxisID:'y' },
            { type:'line', label:'Count',      data: <?= json_encode(array_map(fn($r)=>(int)$r['cancelled'],$byDay)) ?>,
              borderColor:'rgba(249,115,22,.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 }, ticks:{ stepSize:1 } }
        }
    }
});
<?php endif ?>
</script>
<?php $extraJs = ob_get_clean(); ?>
