<?php
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/../config/db.php';

// Action label helper
function actionLabel(string $a): string {
    return match($a) {
        'map_open'      => '📍 Opened map',
        'parcel_tap'    => '👆 Tapped parcel',
        'survey_start'  => '📝 Started survey',
        'survey_save'   => '💾 Saved survey',
        'sync_start'    => '🔄 Sync started',
        'sync_complete' => '✅ Synced',
        'zone_selected' => '🗺 Changed zone',
        'app_open'      => '📱 App opened',
        'login'         => '🔑 Logged in',
        default         => ucfirst(str_replace('_', ' ', $a)),
    };
}
?>

<!-- Leaflet CSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"/>

<style>
  #live-map { height: calc(100vh - 120px); min-height: 500px; border-radius: 12px; }
  .pulse-green { animation: pulse 2s infinite; }
  @keyframes pulse { 0%,100%{ box-shadow: 0 0 0 0 #10b98166 } 50%{ box-shadow: 0 0 0 8px #10b98100 } }
  .user-dot { width:14px;height:14px;border-radius:50%;border:2.5px solid #fff;display:inline-block; }
</style>

<div class="flex gap-4 h-full" x-data="liveMap()" x-init="init()">

  <!-- ── Sidebar ── -->
  <div class="w-72 flex-shrink-0 flex flex-col gap-3">

    <!-- Header card -->
    <div class="bg-white rounded-xl border border-gray-200 p-4">
      <div class="flex items-center justify-between mb-1">
        <h2 class="font-bold text-slate-800">Live Tracker</h2>
        <span class="text-xs text-slate-400" x-text="'Refresh: ' + countdown + 's'"></span>
      </div>
      <div class="flex items-center gap-3 text-sm">
        <span class="text-green-600 font-semibold" x-text="activeCount + ' active'"></span>
        <span class="text-slate-300">|</span>
        <span class="text-slate-500" x-text="users.length + ' total'"></span>
        <span class="ml-auto">
          <span x-show="loading" class="inline-block w-3 h-3 border-2 border-blue-500 border-t-transparent rounded-full animate-spin"></span>
        </span>
      </div>
    </div>

    <!-- User cards -->
    <div class="flex-1 overflow-y-auto space-y-2">
      <template x-for="u in users" :key="u.user_id">
        <div class="bg-white rounded-xl border border-gray-200 p-3 cursor-pointer hover:border-blue-300 transition-colors"
             @click="focusUser(u)">
          <div class="flex items-center gap-2 mb-1">
            <span class="user-dot flex-shrink-0"
                  :style="{ background: u.is_active ? '#10b981' : u.is_recent ? '#f59e0b' : '#9ca3af' }"
                  :class="u.is_active ? 'pulse-green' : ''"></span>
            <span class="font-semibold text-slate-800 text-sm truncate" x-text="u.name"></span>
            <span class="ml-auto text-xs text-slate-400 flex-shrink-0" x-text="u.last_seen"></span>
          </div>
          <div class="text-xs text-slate-500 truncate pl-4" x-text="actionLabel(u.last_action)"></div>
          <template x-if="u.last_action_details">
            <div class="text-xs text-slate-400 truncate pl-4" x-text="u.last_action_details"></div>
          </template>
          <div class="flex items-center gap-3 mt-1.5 pl-4 text-xs text-slate-400">
            <template x-if="u.battery >= 0">
              <span x-text="'🔋 ' + u.battery + '%'"
                    :class="u.battery < 20 ? 'text-red-500 font-semibold' : ''"></span>
            </template>
            <template x-if="u.accuracy > 0">
              <span x-text="'± ' + u.accuracy + 'm'"></span>
            </template>
          </div>
        </div>
      </template>

      <template x-if="users.length === 0 && !loading">
        <div class="text-center text-slate-400 text-sm py-8">No active users in last 24h</div>
      </template>
    </div>

    <!-- Legend -->
    <div class="bg-white rounded-xl border border-gray-200 p-3 text-xs text-slate-500 space-y-1">
      <div class="flex items-center gap-2"><span class="user-dot" style="background:#10b981"></span> Active (&lt;5 min)</div>
      <div class="flex items-center gap-2"><span class="user-dot" style="background:#f59e0b"></span> Recent (&lt;30 min)</div>
      <div class="flex items-center gap-2"><span class="user-dot" style="background:#9ca3af"></span> Inactive</div>
    </div>

  </div>

  <!-- ── Map ── -->
  <div class="flex-1 min-w-0">
    <div id="live-map" class="w-full shadow-sm border border-gray-200"></div>
  </div>

</div>

<!-- Leaflet JS -->
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
function liveMap() {
  return {
    users:       [],
    loading:     false,
    countdown:   15,
    _map:        null,
    _markers:    {},
    _timer:      null,
    _cdTimer:    null,

    activeCount() {
      return this.users.filter(u => u.is_active).length;
    },

    get activeCount() {
      return this.users.filter(u => u.is_active).length;
    },

    actionLabel(a) {
      const map = {
        map_open:      '📍 Opened map',
        parcel_tap:    '👆 Tapped parcel',
        survey_start:  '📝 Started survey',
        survey_save:   '💾 Saved survey',
        sync_start:    '🔄 Sync started',
        sync_complete: '✅ Synced',
        zone_selected: '🗺 Changed zone',
        app_open:      '📱 App opened',
        login:         '🔑 Logged in',
      };
      return map[a] || (a ? a.replace(/_/g,' ') : 'No activity');
    },

    init() {
      this._map = L.map('live-map').setView([27.7762, 85.2283], 15);
      L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors',
        maxZoom: 19
      }).addTo(this._map);

      // Landfill center marker
      L.circleMarker([27.7762, 85.2283], {
        radius: 8, color: '#ef4444', fillColor: '#ef4444', fillOpacity: 0.3, weight: 2
      }).addTo(this._map).bindPopup('<b>🏭 Bancharedanda Landfill</b>');

      this.fetch();
      this._timer   = setInterval(() => { this.fetch(); this.countdown = 15; }, 15000);
      this._cdTimer = setInterval(() => { if (this.countdown > 0) this.countdown--; }, 1000);
    },

    async fetch() {
      this.loading = true;
      try {
        const res  = await fetch('live_locations_ajax.php');
        const data = await res.json();
        this.users = data.users || [];
        this.updateMarkers();
      } catch(e) {}
      this.loading = false;
    },

    updateMarkers() {
      // Remove stale markers
      const currentIds = new Set(this.users.map(u => u.user_id));
      for (const [id, m] of Object.entries(this._markers)) {
        if (!currentIds.has(parseInt(id))) { m.remove(); delete this._markers[id]; }
      }

      this.users.forEach(u => {
        const color = u.is_active ? '#10b981' : u.is_recent ? '#f59e0b' : '#9ca3af';
        const iconHtml = `<div style="width:16px;height:16px;background:${color};border:2.5px solid #fff;
                          border-radius:50%;box-shadow:0 0 0 4px ${color}33;
                          ${u.is_active ? 'animation:pulse 2s infinite' : ''}"></div>`;
        const icon = L.divIcon({ html: iconHtml, className:'', iconSize:[16,16], iconAnchor:[8,8] });

        const popup = `
          <div style="min-width:180px;font-family:sans-serif">
            <div style="font-weight:700;font-size:14px;margin-bottom:4px">${u.name}</div>
            <div style="font-size:12px;color:#64748b">${u.email}</div>
            <hr style="margin:6px 0">
            <div style="font-size:12px">🕐 <b>${u.last_seen}</b></div>
            ${u.battery >= 0 ? `<div style="font-size:12px">🔋 ${u.battery}%${u.battery < 20 ? ' ⚠️' : ''}</div>` : ''}
            ${u.accuracy > 0 ? `<div style="font-size:12px">📡 ±${u.accuracy}m accuracy</div>` : ''}
            <div style="font-size:12px;margin-top:4px">${this.actionLabel(u.last_action)}</div>
            ${u.last_action_details ? `<div style="font-size:11px;color:#94a3b8">${u.last_action_details}</div>` : ''}
            <div style="margin-top:8px">
              <a href="activity_log.php?user_id=${u.user_id}"
                 style="font-size:11px;color:#2563eb;text-decoration:none">View activity log →</a>
            </div>
          </div>`;

        if (this._markers[u.user_id]) {
          this._markers[u.user_id].setLatLng([u.lat, u.lng]).setIcon(icon).getPopup().setContent(popup);
        } else {
          this._markers[u.user_id] = L.marker([u.lat, u.lng], {icon})
            .addTo(this._map).bindPopup(popup);
        }
      });
    },

    focusUser(u) {
      this._map.flyTo([u.lat, u.lng], 17, { duration: 1 });
      if (this._markers[u.user_id]) this._markers[u.user_id].openPopup();
    },
  };
}
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
