<?php
$this->start('head'); include __DIR__ . '/_leaflet_head.php'; $this->end();
$this->start('body');
$summary   = $this->data['summary'];
$positions = $this->data['positions'];
$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-map-marked-alt me-2 text-muted"></i>GPS Dashboard</h5>
    <div class="text-muted small" id="lastRefresh">Loading&hellip;</div>
  </div>
  <div class="d-flex gap-2">
    <a href="<?= PROOT; ?>GpsDashboard/alerts" class="btn btn-sm btn-outline-secondary"><i class="fas fa-bell me-1"></i>Alerts</a>
    <button class="btn btn-sm btn-outline-primary" id="btnRefresh"><i class="fas fa-sync me-1"></i>Refresh</button>
  </div>
</div>

<!-- 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">Active devices</div>
    <div class="fs-4 fw-bold" id="kpiActive"><?= (int)$summary['active_devices']; ?></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">Active trucks</div>
    <div class="fs-4 fw-bold" id="kpiTrucks"><?= (int)$summary['active_trucks']; ?></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">Stale (&gt;15m)</div>
    <div class="fs-4 fw-bold text-warning" id="kpiStale"><?= (int)$summary['stale_devices']; ?></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">Alerts (24h)</div>
    <div class="fs-4 fw-bold text-danger" id="kpiAlerts"><?= (int)$summary['alerts_24h']; ?></div>
  </div></div></div>
</div>

<div class="row g-3">
  <div class="col-lg-3">
    <div class="card border-0 shadow-sm">
      <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">Fleet</h6>
          <span class="small text-muted" id="fleetCount"><?= count($positions); ?></span>
        </div>
        <div class="rs-live-panel" id="fleetList"></div>
      </div>
    </div>
  </div>
  <div class="col-lg-9">
    <div class="card border-0 shadow-sm">
      <div class="card-body p-2">
        <div id="rsMap" class="rs-map rs-map-full"></div>
      </div>
    </div>
  </div>
</div>

<?php
$this->end();
$this->start('section_js');
?>
<script>
// Bootstrap data from the server render — the very first paint doesn't need
// to wait for the JSON poll.
const INITIAL_POSITIONS = <?= json_encode($positions, JSON_UNESCAPED_SLASHES); ?>;
const GEOFENCES         = <?= json_encode($geofences, JSON_UNESCAPED_SLASHES); ?>;
const PROOT             = '<?= PROOT; ?>';

let map, markers = {}, fenceLayers = [];

function initMap() {
    map = L.map('rsMap').setView([-6.792354, 39.208328], 7);   // Dar es Salaam
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 19,
        attribution: '&copy; OpenStreetMap contributors'
    }).addTo(map);

    // Geofence circles — thin outline + tint to identify quickly
    GEOFENCES.forEach(g => {
        if (g.center_lat && g.center_lng && g.radius_m) {
            const c = L.circle([g.center_lat, g.center_lng], {
                radius: g.radius_m, color: g.color || '#2626F5', weight: 1.5,
                fillOpacity: 0.06,
            }).addTo(map);
            c.bindPopup(`<div><strong>${g.name}</strong><br><small>${g.kind}</small></div>`);
            fenceLayers.push(c);
        }
    });

    render(INITIAL_POSITIONS);
    if (INITIAL_POSITIONS.length > 0) fitToPositions(INITIAL_POSITIONS);
}

function markerClass(pos) {
    if (pos.stale) return 'marker-truck stale';
    if (pos.speed_kph && pos.speed_kph > 5) return 'marker-truck moving';
    return 'marker-truck';
}

function render(positions) {
    document.getElementById('fleetCount').textContent = positions.length;
    document.getElementById('fleetList').innerHTML = positions.length === 0
        ? '<div class="text-center text-muted py-4 small">No live trucks reporting.</div>'
        : positions.map(p => `
            <div class="rs-live-row ${p.stale ? 'stale' : ''}" onclick="focusTruck(${p.truck_id})">
                <div class="rs-live-reg">${p.truck_reg || p.device_code}</div>
                <div class="rs-live-meta">
                    ${p.speed_kph !== null ? Math.round(p.speed_kph) + ' km/h · ' : ''}
                    ${formatAgo(p.seconds_ago)}
                </div>
            </div>`).join('');

    // Redraw truck markers
    Object.keys(markers).forEach(id => { map.removeLayer(markers[id]); });
    markers = {};
    positions.forEach(p => {
        if (!p.truck_id) return;
        const icon = L.divIcon({
            className: '', iconAnchor: [24, 12],
            html: `<div class="${markerClass(p)}">${p.truck_reg || p.device_code}</div>`
        });
        const m = L.marker([p.lat, p.lng], { icon }).addTo(map);
        m.bindPopup(popupHtml(p));
        markers[p.truck_id] = m;
    });
}

function popupHtml(p) {
    const ago = formatAgo(p.seconds_ago);
    return `
        <div>
            <div class="lp-truck">${p.truck_reg || p.device_code}</div>
            <div>${p.make || ''} ${p.model || ''}</div>
            <hr style="margin:6px 0;">
            <div>${p.speed_kph !== null ? Math.round(p.speed_kph) + ' km/h' : 'stopped'}
                 ${p.heading_deg !== null ? ' · heading ' + Math.round(p.heading_deg) + '°' : ''}
            </div>
            <div>Last: ${ago}</div>
            ${p.truck_id ? `<a href="${PROOT}GpsDashboard/truck/${p.truck_id}">Detail →</a>` : ''}
        </div>`;
}

function formatAgo(s) {
    if (s === null || s === undefined) return '';
    if (s < 60)     return s + 's ago';
    if (s < 3600)   return Math.floor(s / 60) + 'm ago';
    if (s < 86400)  return Math.floor(s / 3600) + 'h ago';
    return Math.floor(s / 86400) + 'd ago';
}

function fitToPositions(positions) {
    const bounds = L.latLngBounds(positions.map(p => [p.lat, p.lng]));
    if (bounds.isValid()) map.fitBounds(bounds, { padding: [40, 40], maxZoom: 12 });
}

function focusTruck(truckId) {
    const m = markers[truckId];
    if (!m) return;
    map.setView(m.getLatLng(), 14);
    m.openPopup();
}

async function refresh() {
    try {
        const r = await fetch(PROOT + 'GpsDashboard/livePositions');
        const j = await r.json();
        render(j.positions);
        if (j.summary) {
            document.getElementById('kpiActive').textContent  = j.summary.active_devices;
            document.getElementById('kpiTrucks').textContent  = j.summary.active_trucks;
            document.getElementById('kpiStale').textContent   = j.summary.stale_devices;
            document.getElementById('kpiAlerts').textContent  = j.summary.alerts_24h;
        }
        document.getElementById('lastRefresh').textContent = 'Refreshed ' + new Date().toLocaleTimeString();
    } catch (e) {
        document.getElementById('lastRefresh').textContent = 'Refresh failed — will retry';
    }
}

document.getElementById('btnRefresh').addEventListener('click', refresh);

// Wait for leaflet.js to finish (defer-loaded) before initialising the map.
function whenLeafletReady(cb) {
    if (window.L) return cb();
    setTimeout(() => whenLeafletReady(cb), 50);
}
whenLeafletReady(() => {
    initMap();
    document.getElementById('lastRefresh').textContent =
        'Loaded ' + new Date().toLocaleTimeString() + ' · auto-refresh every 30s';
    setInterval(refresh, 30000);
});
</script>
<?php $this->end(); ?>
