<?php $this->start('body'); ?>
<?php $rows = $this->data['rows']; $from = $this->data['from']; $to = $this->data['to']; $preset = $this->data['preset']; ?>

<div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-2">
  <div>
    <h5 class="mb-0 fw-semibold"><i class="fas fa-building me-2 text-muted"></i>Customer Revenue
      <span class="text-muted fw-normal fs-6">· <?= count($rows); ?> customers</span>
    </h5>
    <div class="text-muted small"><?= humanDate($from); ?> → <?= humanDate($to); ?></div>
  </div>
  <?php include __DIR__ . '/_range_form.php'; ?>
</div>

<?= flashHtml(); ?>

<div class="card border-0 shadow-sm">
  <div class="table-responsive">
    <table class="table table-sm mb-0 align-middle">
      <thead class="table-light">
        <tr><th>Customer</th><th class="money">Trips</th><th class="money">Km</th><th class="money">Revenue (posted)</th><th class="money">Invoiced</th><th class="money">Paid</th><th class="money">Outstanding</th></tr>
      </thead>
      <tbody>
        <?php $totR = 0; $totI = 0; $totP = 0; $totO = 0; foreach ($rows as $r):
          $totR += (float)$r['revenue']; $totI += (float)$r['invoiced']; $totP += (float)$r['paid']; $totO += (float)$r['outstanding']; ?>
          <tr>
            <td class="small"><a href="<?= PROOT; ?>Customers/view/<?= (int)$r['customer_id']; ?>" class="fw-semibold text-decoration-none"><?= htmlspecialchars($r['customer_name']); ?></a><?php if ($r['phone']): ?><div class="text-muted small"><?= htmlspecialchars($r['phone']); ?></div><?php endif; ?></td>
            <td class="money small"><?= (int)$r['trips']; ?></td>
            <td class="money small"><?= number_format((float)$r['km'], 0); ?></td>
            <td class="money fw-semibold text-success"><?= number_format((float)$r['revenue'], 0); ?></td>
            <td class="money small"><?= number_format((float)$r['invoiced'], 0); ?></td>
            <td class="money small text-success"><?= number_format((float)$r['paid'], 0); ?></td>
            <td class="money fw-semibold <?= (float)$r['outstanding'] > 0 ? 'text-danger' : 'text-muted'; ?>"><?= number_format((float)$r['outstanding'], 0); ?></td>
          </tr>
        <?php endforeach; ?>
        <?php if (empty($rows)): ?>
          <tr><td colspan="7" class="text-center text-muted py-5">No customer activity in this range.</td></tr>
        <?php endif; ?>
      </tbody>
      <?php if (!empty($rows)): ?>
        <tfoot class="table-light">
          <tr><th>Total</th><th class="money">—</th><th class="money">—</th><th class="money text-success"><?= number_format($totR, 0); ?></th><th class="money"><?= number_format($totI, 0); ?></th><th class="money text-success"><?= number_format($totP, 0); ?></th><th class="money fw-bold text-danger"><?= number_format($totO, 0); ?></th></tr>
        </tfoot>
      <?php endif; ?>
    </table>
  </div>
</div>

<?php $this->end(); ?>
