<?php
$totalDelivered = array_sum(array_map(fn($r) => (int)$r['delivered'], $riders ?? []));
$totalRevenue   = array_sum(array_map(fn($r) => (float)$r['revenue_handled'], $riders ?? []));
?>

<div class="page-header mb-3">
    <div>
        <h1><i class="bi bi-bicycle me-2 text-primary"></i>Rider Performance</h1>
        <p class="text-muted">Delivery stats ranked by completed deliveries.</p>
    </div>
    <a href="?from=<?= $from ?>&to=<?= $to ?>&export=csv" class="btn btn-sm btn-outline-secondary">
        <i class="bi bi-download me-1"></i>Export CSV
    </a>
</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"><?= count($riders ?? []) ?></div>
            <div class="text-muted small">Active Riders</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"><?= number_format($totalDelivered) ?></div>
            <div class="text-muted small">Total Delivered</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"><?= money($totalRevenue) ?></div>
            <div class="text-muted small">Revenue Handled</div>
        </div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card border-0 shadow-sm text-center py-3">
            <?php
            $totalAssigned = array_sum(array_map(fn($r) => (int)$r['total_assigned'], $riders ?? []));
            $overallRate   = $totalAssigned > 0 ? round($totalDelivered / $totalAssigned * 100, 1) : 0;
            ?>
            <div class="fw-bold fs-3 <?= $overallRate >= 80 ? 'text-success' : 'text-warning' ?>"><?= $overallRate ?>%</div>
            <div class="text-muted small">Overall Delivery Rate</div>
        </div>
    </div>
</div>

<!-- Performance bar chart -->
<?php if (!empty($riders)): ?>
<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-horizontal me-1 text-primary"></i>Deliveries by Rider</h6>
    <canvas id="riderChart" style="height:<?= max(180, count($riders) * 36) ?>px;"></canvas>
</div>
</div>
<?php endif ?>

<!-- Rider table -->
<div class="card border-0 shadow-sm">
<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">#</th>
            <th>Rider</th>
            <th>Phone</th>
            <th class="text-end">Assigned</th>
            <th class="text-end">Delivered</th>
            <th class="text-end">Cancelled</th>
            <th class="text-end">Delivery Rate</th>
            <th class="text-end">Revenue Handled</th>
        </tr>
    </thead>
    <tbody>
    <?php if (empty($riders)): ?>
    <tr><td colspan="8" class="text-center text-muted py-5">No rider data for selected period.</td></tr>
    <?php else: ?>
    <?php foreach ($riders as $i => $r):
        $assigned = (int)$r['total_assigned'];
        $delivered = (int)$r['delivered'];
        $rate = $assigned > 0 ? round($delivered / $assigned * 100, 1) : 0;
        $rateClass = $rate >= 85 ? 'text-success' : ($rate >= 65 ? 'text-warning' : 'text-danger');
    ?>
    <tr>
        <td class="px-3 text-muted"><?= $i + 1 ?></td>
        <td class="fw-semibold"><i class="bi bi-person-circle me-1 text-secondary"></i><?= e($r['rider_name']) ?></td>
        <td><?= e($r['phone'] ?? '—') ?></td>
        <td class="text-end"><?= number_format($assigned) ?></td>
        <td class="text-end text-success fw-semibold"><?= number_format($delivered) ?></td>
        <td class="text-end text-danger"><?= number_format((int)$r['cancelled']) ?></td>
        <td class="text-end">
            <div class="d-flex align-items-center justify-content-end gap-1">
                <div class="progress flex-grow-1" style="height:6px;min-width:50px;">
                    <div class="progress-bar <?= $rate >= 85 ? 'bg-success' : ($rate >= 65 ? 'bg-warning' : 'bg-danger') ?>" style="width:<?= $rate ?>%"></div>
                </div>
                <span class="<?= $rateClass ?> fw-semibold"><?= $rate ?>%</span>
            </div>
        </td>
        <td class="text-end"><?= money((float)$r['revenue_handled']) ?></td>
    </tr>
    <?php endforeach ?>
    <?php endif ?>
    </tbody>
    </table>
</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($riders)): ?>
new Chart(document.getElementById('riderChart'), {
    type: 'bar',
    data: {
        labels: <?= json_encode(array_map(fn($r) => $r['rider_name'], $riders)) ?>,
        datasets: [
            { label:'Delivered', data: <?= json_encode(array_map(fn($r)=>(int)$r['delivered'],$riders)) ?>,
              backgroundColor:'rgba(34,197,94,.8)', borderRadius:3 },
            { label:'Cancelled', data: <?= json_encode(array_map(fn($r)=>(int)$r['cancelled'],$riders)) ?>,
              backgroundColor:'rgba(239,68,68,.6)', borderRadius:3 }
        ]
    },
    options: {
        indexAxis: 'y',
        responsive: true, maintainAspectRatio: false,
        plugins: { legend: { position:'top', labels:{ boxWidth:12 } } },
        scales: { x: { beginAtZero: true, stacked: false }, y: { grid:{ display:false } } }
    }
});
<?php endif ?>
</script>
<?php $extraJs = ob_get_clean(); ?>
