<?php
$this->start('head'); include __DIR__ . '/_leaflet_head.php'; $this->end();
$this->start('body');
$truck = $this->data['truck']; $track = $this->data['track']; $geofences = $this->data['geofences'];
?>

<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($truck['truck_reg']); ?></span>
      <span class="badge bg-primary ms-2" style="font-size:.6em;vertical-align:middle;text-transform:capitalize;"><?= htmlspecialchars(str_replace('_',' ',$truck['status'])); ?></span>
    </h5>
    <div class="text-muted small">
      <?= htmlspecialchars(trim(($truck['make'] ?? '') . ' ' . ($truck['model'] ?? ''))); ?>
      <?php if ($truck['device_code']): ?> · <span class="font-monospace"><?= htmlspecialchars($truck['device_code']); ?></span><?php endif; ?>
      <?php if ($truck['last_seen_at']): ?> · last seen <?= humanDateTime($truck['last_seen_at']); ?><?php endif; ?>
    </div>
  </div>
  <div class="d-flex gap-2">
    <a href="<?= PROOT; ?>GpsDashboard" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Live map</a>
    <a href="<?= PROOT; ?>Trucks/view/<?= (int)$truck['c0d']; ?>" class="btn btn-sm btn-outline-primary"><i class="fas fa-info-circle me-1"></i>Truck</a>
  </div>
</div>

<!-- Window KPI strip -->
<div class="row g-2 mb-3">
  <div class="col-6 col-md-3"><div class="card border-0 shadow-sm h-100"><div class="card-body py-2">
    <div class="text-uppercase text-muted small">Distance (24h)</div>
    <div class="fs-4 fw-bold"><?= number_format((float)$track['distance_km'], 1); ?> km</div>
  </div></div></div>
  <div class="col-6 col-md-3"><div class="card border-0 shadow-sm h-100"><div class="card-body py-2">
    <div class="text-uppercase text-muted small">Top speed</div>
    <div class="fs-4 fw-bold"><?= number_format((float)$track['top_speed_kph'], 0); ?> km/h</div>
  </div></div></div>
  <div class="col-6 col-md-3"><div class="card border-0 shadow-sm h-100"><div class="card-body py-2">
    <div class="text-uppercase text-muted small">Avg (moving)</div>
    <div class="fs-4 fw-bold"><?= $track['avg_speed_kph'] !== null ? number_format((float)$track['avg_speed_kph'], 0) . ' km/h' : '—'; ?></div>
  </div></div></div>
  <div class="col-6 col-md-3"><div class="card border-0 shadow-sm h-100"><div class="card-body py-2">
    <div class="text-uppercase text-muted small">Points / events</div>
    <div class="fs-5 fw-bold"><?= (int)$track['total_points']; ?> / <?= count($track['events']); ?></div>
    <div class="small text-muted">showing <?= (int)$track['returned_points']; ?></div>
  </div></div></div>
</div>

<div class="row g-3">
  <div class="col-lg-8">
    <div class="card border-0 shadow-sm">
      <div class="card-body p-2">
        <div id="rsMap" class="rs-map"></div>
      </div>
    </div>
  </div>
  <div class="col-lg-4">
    <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">Recent events</h6>
          <span class="small text-muted"><?= count($track['events']); ?></span>
        </div>
        <div style="max-height:60vh; overflow-y:auto;">
          <?php if (empty($track['events'])): ?>
            <div class="text-center text-muted small py-4">No events in the last 24 hours.</div>
          <?php else: ?>
            <?php foreach ($track['events'] as $e): ?>
              <div class="d-flex align-items-start gap-2 p-2 border-bottom small">
                <span class="marker-event <?= htmlspecialchars($e['severity']); ?>" style="margin-top:4px;"></span>
                <div class="flex-grow-1">
                  <div class="fw-semibold"><?= htmlspecialchars(str_replace('_', ' ', $e['kind'])); ?></div>
                  <div class="text-muted"><?= humanDateTime($e['ts']); ?><?php if ($e['speed_kph'] !== null): ?> · <?= number_format((float)$e['speed_kph'], 0); ?> km/h<?php endif; ?></div>
                </div>
              </div>
            <?php endforeach; ?>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>
</div>

<?php $this->end(); $this->start('section_js'); ?>
<script>
const TRACK     = <?= json_encode($track, JSON_UNESCAPED_SLASHES); ?>;
const GEOFENCES = <?= json_encode($geofences, JSON_UNESCAPED_SLASHES); ?>;

function whenLeafletReady(cb) { if (window.L) return cb(); setTimeout(() => whenLeafletReady(cb), 50); }

whenLeafletReady(() => {
    const map = L.map('rsMap');
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 19, attribution: '&copy; OpenStreetMap contributors'
    }).addTo(map);

    GEOFENCES.forEach(g => {
        if (g.center_lat && g.center_lng && g.radius_m) {
            L.circle([g.center_lat, g.center_lng], {
                radius: g.radius_m, color: g.color || '#2626F5', weight: 1.5, fillOpacity: 0.06,
            }).addTo(map).bindPopup(`<strong>${g.name}</strong><br><small>${g.kind}</small>`);
        }
    });

    if (TRACK.points.length === 0) {
        map.setView([-6.792354, 39.208328], 7);
        return;
    }

    // Coloured polyline: green for movement, grey for idle
    const line = TRACK.points.map(p => [p.lat, p.lng]);
    L.polyline(line, { color: '#2626F5', weight: 3, opacity: 0.85 }).addTo(map);

    // Start / end / events
    const start = TRACK.points[0];
    L.marker([start.lat, start.lng]).addTo(map).bindPopup('Start · ' + start.ts);
    const end = TRACK.points[TRACK.points.length - 1];
    L.marker([end.lat, end.lng]).addTo(map).bindPopup('Latest · ' + end.ts);

    TRACK.events.forEach(e => {
        if (e.lat && e.lng) {
            L.circleMarker([e.lat, e.lng], {
                radius: 6,
                color: e.severity === 'crit' || e.severity === 'critical' ? '#DC2626'
                     : e.severity === 'warn' ? '#F59E0B' : '#2626F5',
                fillOpacity: 0.85, weight: 2
            }).addTo(map).bindPopup(`<strong>${e.kind.replace(/_/g, ' ')}</strong><br>${e.ts}`);
        }
    });

    map.fitBounds(L.latLngBounds(line), { padding: [30, 30] });
});
</script>
<?php $this->end(); ?>
