<?php
$this->start('head'); include __DIR__ . '/_leaflet_head.php'; $this->end();
$this->start('body');
$d = $this->data['data']; $trip = $d['trip']; $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-route me-2 text-muted"></i>
      <span class="font-monospace"><?= htmlspecialchars($trip['trip_no']); ?></span>
      <span class="badge bg-primary ms-2" style="font-size:.6em;vertical-align:middle;text-transform:capitalize;"><?= htmlspecialchars($trip['status']); ?></span>
    </h5>
    <div class="text-muted small">
      <?= htmlspecialchars($trip['origin'] ?? '—'); ?> &rarr; <?= htmlspecialchars($trip['destination'] ?? '—'); ?>
      <?php if ($trip['truck_reg']): ?> · <?= htmlspecialchars($trip['truck_reg']); ?><?php endif; ?>
      <?php if ($trip['driver_name']): ?> · <?= htmlspecialchars($trip['driver_name']); ?><?php endif; ?>
    </div>
  </div>
  <a href="<?= PROOT; ?>Trips/view/<?= (int)$trip['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Trip</a>
</div>

<div class="row g-2 mb-3">
  <div class="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</div>
    <div class="fs-4 fw-bold"><?= number_format((float)$d['distance_km'], 1); ?> km</div>
  </div></div></div>
  <div class="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</div>
    <div class="fs-4 fw-bold"><?= count($d['points']); ?></div>
  </div></div></div>
  <div class="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">Events</div>
    <div class="fs-4 fw-bold"><?= count($d['events']); ?></div>
  </div></div></div>
  <div class="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">Duration</div>
    <div class="fs-5 fw-bold">
      <?php
      if ($trip['started_at'] && $trip['ended_at']) {
          $s = strtotime($trip['ended_at']) - strtotime($trip['started_at']);
          echo sprintf('%dh %dm', intdiv($s, 3600), intdiv($s % 3600, 60));
      } elseif ($trip['started_at']) {
          echo 'in progress';
      } else {
          echo '—';
      }
      ?>
    </div>
  </div></div></div>
</div>

<div class="card border-0 shadow-sm">
  <div class="card-body p-2">
    <div id="rsMap" class="rs-map rs-map-full"></div>
    <div class="d-flex align-items-center gap-2 mt-2 flex-wrap">
      <button class="btn btn-sm btn-primary" id="btnPlay"><i class="fas fa-play me-1"></i>Play</button>
      <button class="btn btn-sm btn-outline-secondary" id="btnReset"><i class="fas fa-undo"></i></button>
      <input type="range" min="0" max="1" step="1" value="0" id="scrub" class="form-range" style="flex:1;">
      <span class="small text-muted font-monospace" id="tsLabel">&mdash;</span>
      <span class="small text-muted ms-3">Speed</span>
      <select id="playSpeed" class="form-select form-select-sm" style="width:auto;">
        <option value="30">30x</option><option value="60" selected>60x</option>
        <option value="120">120x</option><option value="300">300x</option>
      </select>
    </div>
  </div>
</div>

<?php $this->end(); $this->start('section_js'); ?>
<script>
const DATA      = <?= json_encode($d, 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);
        }
    });

    if (DATA.points.length === 0) {
        map.setView([-6.792354, 39.208328], 7);
        document.getElementById('btnPlay').disabled = true;
        return;
    }

    const line = DATA.points.map(p => [p.lat, p.lng]);
    L.polyline(line, { color: '#2626F5', weight: 3, opacity: 0.7 }).addTo(map);
    L.marker(line[0]).addTo(map).bindPopup('Start');
    L.marker(line[line.length - 1]).addTo(map).bindPopup('End');

    DATA.events.forEach(e => {
        if (e.lat && e.lng) {
            L.circleMarker([e.lat, e.lng], {
                radius: 5,
                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}`);
        }
    });

    const playhead = L.circleMarker(line[0], {
        radius: 10, color: '#DC2626', fillColor: '#fff', fillOpacity: 1, weight: 3
    }).addTo(map);

    const scrub    = document.getElementById('scrub');
    const tsLabel  = document.getElementById('tsLabel');
    scrub.max = DATA.points.length - 1;

    function setIndex(i) {
        i = Math.max(0, Math.min(i, DATA.points.length - 1));
        const p = DATA.points[i];
        playhead.setLatLng([p.lat, p.lng]);
        tsLabel.textContent = p.ts + (p.speed_kph !== null ? ` · ${Math.round(p.speed_kph)} km/h` : '');
        scrub.value = i;
    }
    setIndex(0);

    map.fitBounds(L.latLngBounds(line), { padding: [30, 30] });

    scrub.addEventListener('input', () => setIndex(parseInt(scrub.value, 10)));

    // Playback loops through indices at speed × factor. Each tick advances by
    // (factor / 10) hop indices — cheap way to make the playback speed knob
    // meaningful without walking each real-time second.
    let timer = null;
    document.getElementById('btnPlay').addEventListener('click', () => {
        if (timer) {
            clearInterval(timer); timer = null;
            document.getElementById('btnPlay').innerHTML = '<i class="fas fa-play me-1"></i>Play';
            return;
        }
        document.getElementById('btnPlay').innerHTML = '<i class="fas fa-pause me-1"></i>Pause';
        const factor = parseInt(document.getElementById('playSpeed').value, 10);
        timer = setInterval(() => {
            const nxt = Math.min(DATA.points.length - 1, parseInt(scrub.value, 10) + Math.max(1, Math.floor(factor / 10)));
            setIndex(nxt);
            if (nxt >= DATA.points.length - 1) {
                clearInterval(timer); timer = null;
                document.getElementById('btnPlay').innerHTML = '<i class="fas fa-play me-1"></i>Play';
            }
        }, 200);
    });
    document.getElementById('btnReset').addEventListener('click', () => setIndex(0));
});
</script>
<?php $this->end(); ?>
