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

    // Fleet totals for the header strip
    $tot = ['revenue' => 0.0, 'cost' => 0.0, 'fuel_l' => 0.0, 'km' => 0.0, 'trips' => 0, 'ontime' => 0];
    foreach ($rows as $r) {
        $tot['revenue'] += (float)$r['revenue'];
        $tot['cost']    += (float)$r['cost_direct'] + (float)$r['fuel_cost'];
        $tot['fuel_l']  += (float)$r['fuel_l'];
        $tot['km']      += (float)$r['km'];
        $tot['trips']   += (int)$r['trips_closed'];
        $tot['ontime']  += (int)$r['ontime_count'];
    }
    $tot['margin']         = round($tot['revenue'] - $tot['cost'], 2);
    $tot['cost_per_km']    = $tot['km'] > 0 ? round($tot['cost'] / $tot['km'], 2) : null;
    $tot['revenue_per_km'] = $tot['km'] > 0 ? round($tot['revenue'] / $tot['km'], 2) : null;
    $tot['l_per_100km']    = $tot['km'] > 0 ? round($tot['fuel_l'] * 100 / $tot['km'], 2) : null;
    $tot['on_time_pct']    = $tot['trips'] > 0 ? round(($tot['ontime'] / $tot['trips']) * 100, 1) : null;
?>

<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-th me-2 text-muted"></i>Truck Matrix</h5>
    <div class="text-muted small"><?= humanDate($from); ?> &rarr; <?= humanDate($to); ?> &middot; every truck × every metric</div>
  </div>
  <div class="d-flex gap-2">
    <a href="<?= PROOT; ?>FleetAnalytics" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Analytics</a>
    <button class="btn btn-sm btn-outline-primary" onclick="window.print()"><i class="fas fa-print me-1"></i>Print</button>
  </div>
</div>

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

<!-- Fleet totals strip -->
<div class="row g-2 mb-3">
  <div class="col-6 col-lg"><div class="card border-0 shadow-sm h-100"><div class="card-body py-2">
    <div class="text-uppercase text-muted small">Revenue</div>
    <div class="fs-5 fw-bold text-success">TZS <?= number_format($tot['revenue'], 0); ?></div>
  </div></div></div>
  <div class="col-6 col-lg"><div class="card border-0 shadow-sm h-100"><div class="card-body py-2">
    <div class="text-uppercase text-muted small">Direct cost</div>
    <div class="fs-5 fw-bold text-danger">TZS <?= number_format($tot['cost'], 0); ?></div>
  </div></div></div>
  <div class="col-6 col-lg"><div class="card border-0 shadow-sm h-100"><div class="card-body py-2">
    <div class="text-uppercase text-muted small">Gross margin</div>
    <div class="fs-5 fw-bold <?= $tot['margin'] >= 0 ? 'text-success' : 'text-danger'; ?>">TZS <?= number_format($tot['margin'], 0); ?></div>
  </div></div></div>
  <div class="col-6 col-lg"><div class="card border-0 shadow-sm h-100"><div class="card-body py-2">
    <div class="text-uppercase text-muted small">Km driven</div>
    <div class="fs-5 fw-bold"><?= number_format($tot['km'], 0); ?></div>
  </div></div></div>
  <div class="col-6 col-lg"><div class="card border-0 shadow-sm h-100"><div class="card-body py-2">
    <div class="text-uppercase text-muted small">L / 100km</div>
    <div class="fs-5 fw-bold"><?= $tot['l_per_100km'] !== null ? number_format($tot['l_per_100km'], 1) : '—'; ?></div>
  </div></div></div>
  <div class="col-6 col-lg"><div class="card border-0 shadow-sm h-100"><div class="card-body py-2">
    <div class="text-uppercase text-muted small">On-time %</div>
    <div class="fs-5 fw-bold"><?= $tot['on_time_pct'] !== null ? number_format($tot['on_time_pct'], 1) . '%' : '—'; ?></div>
  </div></div></div>
</div>

<!-- Fleet chart -->
<div class="card border-0 shadow-sm mb-3"><div class="card-body">
  <div class="d-flex justify-content-between align-items-baseline mb-2">
    <h6 class="text-uppercase text-muted small mb-0">Revenue vs cost per truck</h6>
    <span class="small text-muted">click a bar to open detail</span>
  </div>
  <div id="chart-rev-cost" style="min-height: 260px;"></div>
</div></div>

<!-- The matrix -->
<div class="card border-0 shadow-sm">
  <div class="table-responsive">
    <table class="table table-sm mb-0 align-middle" id="matrixTable">
      <thead class="table-light">
        <tr>
          <th>Truck</th>
          <th class="text-center">Trips</th>
          <th class="money">Km</th>
          <th class="money">Revenue</th>
          <th class="money">Fuel L</th>
          <th class="money">Fuel TZS</th>
          <th class="money">Direct cost</th>
          <th class="money fw-bold">Margin</th>
          <th class="money">Cost / km</th>
          <th class="money">Rev / km</th>
          <th class="money">L / 100km</th>
          <th class="text-center">On-time</th>
          <th class="text-center">Down d</th>
          <th class="text-end"></th>
        </tr>
      </thead>
      <tbody>
        <?php if (empty($rows)): ?>
          <tr><td colspan="14" class="text-center text-muted py-5">No trucks match this range.</td></tr>
        <?php else: foreach ($rows as $r):
          $margin  = (float)$r['gross_margin'];
          $mCls    = $margin >= 0 ? 'text-success' : 'text-danger';
          $lp100   = $r['l_per_100km'];
          $lp100Cls= $lp100 === null ? 'text-muted' : ($lp100 > 40 ? 'text-danger' : ($lp100 > 30 ? 'text-warning' : 'text-success'));
          $ot      = $r['on_time_pct'];
          $otCls   = $ot === null ? '' : ($ot >= 90 ? 'bg-success' : ($ot >= 70 ? 'bg-warning text-dark' : 'bg-danger'));
        ?>
          <tr>
            <td>
              <a href="<?= PROOT; ?>FleetAnalytics/truck/<?= (int)$r['truck_id']; ?>?preset=<?= htmlspecialchars($preset); ?>&from=<?= $from; ?>&to=<?= $to; ?>" class="text-decoration-none">
                <div class="font-monospace fw-semibold"><?= htmlspecialchars($r['reg_no']); ?></div>
                <div class="text-muted small"><?= htmlspecialchars(trim(($r['make'] ?? '') . ' ' . ($r['model'] ?? ''))); ?></div>
              </a>
            </td>
            <td class="text-center small"><?= (int)$r['trips_closed']; ?></td>
            <td class="money font-monospace small"><?= number_format((float)$r['km'], 0); ?></td>
            <td class="money font-monospace small text-success"><?= number_format((float)$r['revenue'], 0); ?></td>
            <td class="money font-monospace small"><?= number_format((float)$r['fuel_l'], 0); ?></td>
            <td class="money font-monospace small"><?= number_format((float)$r['fuel_cost'], 0); ?></td>
            <td class="money font-monospace small text-danger"><?= number_format((float)$r['cost_direct'] + (float)$r['fuel_cost'], 0); ?></td>
            <td class="money font-monospace fw-bold <?= $mCls; ?>"><?= number_format($margin, 0); ?></td>
            <td class="money font-monospace small"><?= $r['cost_per_km']    !== null ? number_format($r['cost_per_km'],    0) : '—'; ?></td>
            <td class="money font-monospace small"><?= $r['revenue_per_km'] !== null ? number_format($r['revenue_per_km'], 0) : '—'; ?></td>
            <td class="money font-monospace small <?= $lp100Cls; ?>"><?= $lp100 !== null ? number_format($lp100, 1) : '—'; ?></td>
            <td class="text-center">
              <?php if ($ot !== null): ?>
                <span class="badge <?= $otCls; ?>"><?= number_format($ot, 0); ?>%</span>
              <?php else: ?>—<?php endif; ?>
            </td>
            <td class="text-center small"><?= (int)$r['downtime_days']; ?></td>
            <td class="text-end">
              <a href="<?= PROOT; ?>FleetAnalytics/truck/<?= (int)$r['truck_id']; ?>?preset=<?= htmlspecialchars($preset); ?>&from=<?= $from; ?>&to=<?= $to; ?>" class="btn btn-sm btn-outline-primary"><i class="fas fa-arrow-right"></i></a>
            </td>
          </tr>
        <?php endforeach; endif; ?>
      </tbody>
    </table>
  </div>
</div>

<?php $this->end(); $this->start('section_js'); ?>
<script>
document.addEventListener('DOMContentLoaded', function () {
  const rows = <?= json_encode(array_map(fn($r) => [
      'reg' => $r['reg_no'], 'id' => (int)$r['truck_id'],
      'revenue' => round((float)$r['revenue'], 2),
      'cost'    => round((float)$r['cost_direct'] + (float)$r['fuel_cost'], 2),
  ], $rows), JSON_UNESCAPED_SLASHES); ?>;

  const cats = rows.map(r => r.reg);
  new PacificChart('#chart-rev-cost', 'bar', {
    categories: cats, tzs: true, colors: ['#0E9F6E', '#DC2626'],
    series: [
      { name: 'Revenue',     data: rows.map(r => r.revenue) },
      { name: 'Direct cost', data: rows.map(r => r.cost) },
    ],
  });
});
</script>
<?php $this->end(); ?>
