<?php
$repeat  = $repeatRate ?? [];
$total   = (int)($repeat['total_customers']  ?? 0);
$rptCust = (int)($repeat['repeat_customers'] ?? 0);
$rptRate = $total > 0 ? round($rptCust / $total * 100, 1) : 0;
$tier    = $tierBreakdown[0] ?? [];
?>

<div class="page-header mb-3">
    <div>
        <h1><i class="bi bi-arrow-repeat me-2 text-purple"></i>Customer Retention</h1>
        <p class="text-muted">New vs. returning customers, loyalty tiers, and churn signals.</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-primary"><?= number_format($newCustomers) ?></div>
            <div class="text-muted small">New Customers</div>
            <div class="text-muted" style="font-size:.7rem;">this period</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-success"><?= $rptRate ?>%</div>
            <div class="text-muted small">Repeat Order Rate</div>
            <div class="text-muted" style="font-size:.7rem;"><?= number_format($rptCust) ?> / <?= number_format($total) ?> customers</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"><?= number_format($churned) ?></div>
            <div class="text-muted small">Churned Customers</div>
            <div class="text-muted" style="font-size:.7rem;">no order in 60 days</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">
                <?= number_format((int)($tier['platinum'] ?? 0) + (int)($tier['gold'] ?? 0)) ?>
            </div>
            <div class="text-muted small">Gold + Platinum</div>
            <div class="text-muted" style="font-size:.7rem;">high-value customers</div>
        </div>
    </div>
</div>

<div class="row g-3 mb-4">
    <!-- New vs returning stacked bar -->
    <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-people me-1 text-primary"></i>New vs. Returning Customers Daily</h6>
            <?php if (empty($newVsReturn)): ?>
            <div class="text-muted text-center py-4">No data for this period.</div>
            <?php else: ?>
            <canvas id="nvrChart" style="height:230px;"></canvas>
            <?php endif ?>
        </div>
        </div>
    </div>
    <!-- Tier 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-award me-1 text-warning"></i>Customer Tier Distribution</h6>
            <canvas id="tierChart" style="height:200px;"></canvas>
            <div class="mt-3">
                <?php
                $tierDef = [
                    ['Platinum','💎','badge-platinum','platinum'],
                    ['Gold','🥇','badge-gold','gold'],
                    ['Silver','🥈','badge-silver','silver'],
                    ['Bronze','🥉','badge-bronze','bronze'],
                    ['New','🆕','badge-new','new_customers'],
                ];
                foreach ($tierDef as [$lbl,$ico,$cls,$key]): $n = (int)($tier[$key] ?? 0); ?>
                <div class="d-flex justify-content-between align-items-center small mb-1">
                    <span><?= $ico ?> <?= $lbl ?></span>
                    <span class="fw-semibold"><?= number_format($n) ?></span>
                </div>
                <?php endforeach ?>
            </div>
        </div>
        </div>
    </div>
</div>

<!-- Tier revenue table -->
<?php if (!empty($tierRevenue)): ?>
<div class="card border-0 shadow-sm mb-4">
<div class="card-header bg-transparent border-0 py-2 px-3">
    <h6 class="fw-bold mb-0"><i class="bi bi-currency-dollar me-1 text-success"></i>Revenue by Tier (All Time)</h6>
</div>
<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">Tier</th>
            <th class="text-end">Customers</th>
            <th class="text-end">Total Revenue</th>
            <th class="text-end">Avg per Customer</th>
        </tr>
    </thead>
    <tbody>
    <?php foreach ($tierRevenue as $row):
        $avg = (int)$row['customers'] > 0 ? (float)$row['total_revenue'] / (int)$row['customers'] : 0;
    ?>
    <tr>
        <td class="px-3 fw-semibold"><?= e($row['tier']) ?></td>
        <td class="text-end"><?= number_format((int)$row['customers']) ?></td>
        <td class="text-end"><?= money((float)$row['total_revenue']) ?></td>
        <td class="text-end"><?= money($avg) ?></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($newVsReturn)): ?>
new Chart(document.getElementById('nvrChart'), {
    type:'bar',
    data:{
        labels: <?= json_encode(array_column($newVsReturn,'d')) ?>,
        datasets:[
            { label:'New',       data: <?= json_encode(array_map(fn($r)=>(int)$r['new_customers'],$newVsReturn)) ?>,
              backgroundColor:'rgba(59,130,246,.75)', borderRadius:2 },
            { label:'Returning', data: <?= json_encode(array_map(fn($r)=>(int)$r['returning_customers'],$newVsReturn)) ?>,
              backgroundColor:'rgba(34,197,94,.75)', borderRadius:2 }
        ]
    },
    options:{
        responsive:true, maintainAspectRatio:false,
        plugins:{ legend:{ position:'top', labels:{ boxWidth:12 } } },
        scales:{ x:{ stacked:true, grid:{ display:false } }, y:{ stacked:true, beginAtZero:true } }
    }
});
<?php endif ?>

new Chart(document.getElementById('tierChart'), {
    type:'doughnut',
    data:{
        labels:['Platinum','Gold','Silver','Bronze','New'],
        datasets:[{ data:[
            <?= (int)($tier['platinum']??0) ?>,
            <?= (int)($tier['gold']??0) ?>,
            <?= (int)($tier['silver']??0) ?>,
            <?= (int)($tier['bronze']??0) ?>,
            <?= (int)($tier['new_customers']??0) ?>
        ],
        backgroundColor:[
            'rgba(139,92,246,.85)',
            'rgba(234,179,8,.85)',
            'rgba(156,163,175,.85)',
            'rgba(180,83,9,.75)',
            'rgba(99,102,241,.6)'
        ], borderWidth:1 }]
    },
    options:{ responsive:true, maintainAspectRatio:false, cutout:'55%',
        plugins:{ legend:{ display:false } } }
});
</script>
<?php $extraJs = ob_get_clean(); ?>
