<?php $this->start('body');
    $d = $this->data['d'];
    $t = $d['truck']; $monthly = $d['monthly']; $fuel = $d['fuel'];
    $trips = $d['trips']; $wos = $d['work_orders']; $incidents = $d['incidents'];
    $from = $this->data['from']; $to = $this->data['to']; $preset = $this->data['preset'];

    // Aggregates for the KPI strip
    $totRev = $totCost = $totFuelL = $totFuelSpend = $totKm = 0;
    foreach ($monthly as $m) { $totRev += (float)$m['rev']; $totCost += (float)$m['cost']; }
    foreach ($fuel as $f)    { $totFuelL += (float)$f['liters']; $totFuelSpend += (float)$f['spend']; }
    foreach ($trips as $tr)  { $totKm += (float)$tr['actual_km']; }
    $margin = $totRev - $totCost;
?>

<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-truck me-2 text-muted"></i>
      <span class="font-monospace"><?= htmlspecialchars($t['reg_no']); ?></span>
      <span class="badge bg-primary ms-2" style="font-size:.6em;vertical-align:middle;text-transform:capitalize;"><?= htmlspecialchars(str_replace('_',' ',$t['status'])); ?></span>
    </h5>
    <div class="text-muted small">
      <?= htmlspecialchars(trim(($t['make'] ?? '') . ' ' . ($t['model'] ?? '') . ' ' . ($t['year'] ?? ''))); ?>
      <?php if ($t['chassis_no']): ?> &middot; chassis <?= htmlspecialchars($t['chassis_no']); ?><?php endif; ?>
      &middot; <?= humanDate($from); ?> &rarr; <?= humanDate($to); ?>
    </div>
  </div>
  <div class="d-flex gap-2">
    <a href="<?= PROOT; ?>FleetAnalytics/matrix?preset=<?= htmlspecialchars($preset); ?>&from=<?= $from; ?>&to=<?= $to; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Matrix</a>
    <a href="<?= PROOT; ?>Trucks/view/<?= (int)$t['c0d']; ?>" class="btn btn-sm btn-outline-primary"><i class="fas fa-info-circle me-1"></i>Truck info</a>
    <a href="<?= PROOT; ?>GpsDashboard/truck/<?= (int)$t['c0d']; ?>" class="btn btn-sm btn-outline-primary"><i class="fas fa-map-marked-alt me-1"></i>Live GPS</a>
  </div>
</div>

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

<!-- KPI strip -->
<div class="row g-2 mb-3">
  <div class="col-6 col-lg-3"><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-4 fw-bold text-success">TZS <?= number_format($totRev, 0); ?></div>
  </div></div></div>
  <div class="col-6 col-lg-3"><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-4 fw-bold text-danger">TZS <?= number_format($totCost, 0); ?></div>
    <div class="small text-muted">excl. fuel</div>
  </div></div></div>
  <div class="col-6 col-lg-3"><div class="card border-0 shadow-sm h-100"><div class="card-body py-2">
    <div class="text-uppercase text-muted small">Fuel spend</div>
    <div class="fs-4 fw-bold text-warning">TZS <?= number_format($totFuelSpend, 0); ?></div>
    <div class="small text-muted"><?= number_format($totFuelL, 0); ?> L</div>
  </div></div></div>
  <div class="col-6 col-lg-3"><div class="card border-0 shadow-sm h-100 border-primary"><div class="card-body py-2">
    <div class="text-uppercase text-muted small">Gross margin</div>
    <div class="fs-4 fw-bold <?= ($margin - $totFuelSpend) >= 0 ? 'text-success' : 'text-danger'; ?>">TZS <?= number_format($margin - $totFuelSpend, 0); ?></div>
    <div class="small text-muted">Rev &minus; (cost + fuel)</div>
  </div></div></div>
</div>

<!-- Charts row -->
<div class="row g-3">
  <div class="col-lg-8"><div class="card border-0 shadow-sm h-100"><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 &middot; monthly</h6>
    </div>
    <div id="c-monthly" style="min-height: 260px;"></div>
  </div></div></div>
  <div class="col-lg-4"><div class="card border-0 shadow-sm h-100"><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">Incident breakdown</h6>
    </div>
    <div id="c-incidents" style="min-height: 260px;"></div>
  </div></div></div>
</div>

<div class="row g-3 mt-1">
  <div class="col-lg-12"><div class="card border-0 shadow-sm"><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">Fuel litres per month</h6>
    </div>
    <div id="c-fuel" style="min-height: 220px;"></div>
  </div></div></div>
</div>

<!-- Trips + Work orders side by side -->
<div class="row g-3 mt-1">
  <div class="col-lg-7">
    <div class="card border-0 shadow-sm h-100"><div class="card-body p-0">
      <div class="p-3 pb-2 d-flex justify-content-between align-items-center">
        <h6 class="text-uppercase text-muted small mb-0">Closed trips &middot; last 10</h6>
        <a href="<?= PROOT; ?>Trips?truck_id=<?= (int)$t['c0d']; ?>" class="small text-decoration-none">All &rarr;</a>
      </div>
      <?php if (empty($trips)): ?>
        <div class="text-center text-muted small py-4">No closed trips in this range.</div>
      <?php else: ?>
        <div class="table-responsive">
          <table class="table table-sm mb-0">
            <thead class="table-light">
              <tr><th>Trip</th><th>Customer</th><th>Driver</th><th class="money">Km</th><th>On-time</th></tr>
            </thead>
            <tbody>
              <?php foreach ($trips as $tr):
                $ot = $tr['planned_delivery'] && $tr['actual_end'] && strtotime($tr['actual_end']) <= strtotime($tr['planned_delivery']);
              ?>
                <tr>
                  <td class="font-monospace small">
                    <a href="<?= PROOT; ?>Trips/view/<?= (int)$tr['c0d']; ?>" class="text-decoration-none"><?= htmlspecialchars($tr['trip_no']); ?></a>
                    <div class="text-muted small"><?= humanDate($tr['actual_end']); ?></div>
                  </td>
                  <td class="small"><?= htmlspecialchars($tr['customer_name'] ?? '—'); ?></td>
                  <td class="small"><?= htmlspecialchars($tr['driver_name'] ?? '—'); ?></td>
                  <td class="money font-monospace small"><?= number_format((float)$tr['actual_km'], 0); ?></td>
                  <td>
                    <?php if ($tr['planned_delivery']): ?>
                      <span class="badge bg-<?= $ot ? 'success' : 'danger'; ?>"><?= $ot ? 'on time' : 'late'; ?></span>
                    <?php else: ?>
                      <span class="badge bg-light text-muted">—</span>
                    <?php endif; ?>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>
    </div></div>
  </div>
  <div class="col-lg-5">
    <div class="card border-0 shadow-sm h-100"><div class="card-body p-0">
      <div class="p-3 pb-2 d-flex justify-content-between align-items-center">
        <h6 class="text-uppercase text-muted small mb-0">Work orders</h6>
        <a href="<?= PROOT; ?>WorkOrders?truck_id=<?= (int)$t['c0d']; ?>" class="small text-decoration-none">All &rarr;</a>
      </div>
      <?php if (empty($wos)): ?>
        <div class="text-center text-muted small py-4">No work orders.</div>
      <?php else: ?>
        <table class="table table-sm mb-0">
          <tbody>
            <?php foreach ($wos as $w): $bg = ['open'=>'warning text-dark','in_progress'=>'primary','completed'=>'success','cancelled'=>'dark'][$w['status']] ?? 'light'; ?>
              <tr>
                <td>
                  <a href="<?= PROOT; ?>WorkOrders/view/<?= (int)$w['c0d']; ?>" class="text-decoration-none">
                    <div class="font-monospace small"><?= htmlspecialchars($w['wo_no']); ?></div>
                    <div class="text-muted small"><?= htmlspecialchars($w['shop'] ?? '—'); ?></div>
                  </a>
                </td>
                <td class="text-end">
                  <div class="fw-bold font-monospace small">TZS <?= number_format((float)$w['total_cost'], 0); ?></div>
                  <span class="badge bg-<?= $bg; ?> small"><?= htmlspecialchars($w['status']); ?></span>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      <?php endif; ?>
    </div></div>
  </div>
</div>

<?php $this->end(); $this->start('section_js'); ?>
<script>
document.addEventListener('DOMContentLoaded', function () {
  // Monthly rev vs cost
  const monthly = <?= json_encode($monthly, JSON_UNESCAPED_SLASHES); ?>;
  new PacificChart('#c-monthly', 'bar', {
    categories: monthly.map(m => m.ym.slice(5)),
    tzs: true, colors: ['#0E9F6E','#DC2626'],
    series: [
      { name: 'Revenue', data: monthly.map(m => Number(m.rev  || 0)) },
      { name: 'Cost',    data: monthly.map(m => Number(m.cost || 0)) },
    ],
  });

  // Incidents donut
  const inc = <?= json_encode($incidents, JSON_UNESCAPED_SLASHES); ?>;
  if (inc.length === 0) {
    document.querySelector('#c-incidents').innerHTML =
      '<div class="text-center text-muted py-5"><i class="fas fa-shield-halved fa-2x"></i><div class="mt-2">No incidents</div></div>';
  } else {
    new PacificChart('#c-incidents', 'donut', {
      labels: inc.map(i => i.kind.replace(/_/g,' ')),
      series: inc.map(i => Number(i.n)),
      colors: 'quad',
    });
  }

  // Fuel litres per month
  const fuel = <?= json_encode($fuel, JSON_UNESCAPED_SLASHES); ?>;
  new PacificChart('#c-fuel', 'area', {
    categories: fuel.map(f => f.ym.slice(5)),
    series: [{ name: 'Litres', data: fuel.map(f => Number(f.liters || 0)) }],
    colors: ['#F59E0B'],
  });
});
</script>
<?php $this->end(); ?>
