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

// Load all parcels with centroid + status
$parcels = $pdo->query("
    SELECT id, kml_id, zone, sheet_number, parcel_no,
           centroid_lat, centroid_lng, survey_status,
           ROUND(shape_area_sqm,1) AS shape_area_sqm
    FROM parcels
    WHERE centroid_lat != 0 AND centroid_lng != 0
    ORDER BY zone
")->fetchAll();

// Also load polygon coords for drawing
$polygons = $pdo->query("
    SELECT id, polygon_coords, survey_status, zone
    FROM parcels
    WHERE polygon_coords IS NOT NULL AND polygon_coords != '' AND centroid_lat != 0
")->fetchAll();

$stats = $pdo->query("
    SELECT survey_status, COUNT(*) as cnt FROM parcels GROUP BY survey_status
")->fetchAll(PDO::FETCH_KEY_PAIR);

$total = array_sum($stats);
$done  = (int)($stats['completed']   ?? 0);
$prog  = (int)($stats['in_progress'] ?? 0);
$pend  = (int)($stats['pending']     ?? 0);

// Encode for JS
$parcelsJson  = json_encode($parcels);
$polygonsJson = json_encode($polygons);
?>

<!-- Override main padding for full-height map -->
<style>
  main { padding: 0 !important; display: flex; flex-direction: column; overflow: hidden; }
  main { height: calc(100vh - 49px); } /* 49px = sticky top bar height */
</style>

<!-- Top bar -->
<div class="flex items-center justify-between px-5 py-3 bg-white border-b border-slate-200 flex-shrink-0 flex-wrap gap-3">
  <div>
    <h1 class="text-lg font-bold text-slate-800">Parcel Map</h1>
    <p class="text-xs text-slate-500">1,498 parcels · Bancharedanda affected area</p>
  </div>
  <div class="flex items-center gap-4 flex-wrap">
    <!-- Parcel search -->
    <div class="relative">
      <input id="parcelSearch" type="text" placeholder="🔍 Parcel no…" autocomplete="off"
             class="text-xs border border-slate-300 rounded-lg pl-3 pr-7 py-1.5 w-36 focus:outline-none focus:ring-2 focus:ring-blue-500">
      <button id="parcelSearchClear" type="button"
              class="hidden absolute right-1.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-700 text-xs">✕</button>
      <div id="parcelSearchResults"
           class="hidden absolute z-[60] mt-1 w-56 max-h-64 overflow-y-auto bg-white border border-slate-200 rounded-lg shadow-lg text-xs"></div>
    </div>
    <!-- Zone legend -->
    <div class="flex items-center gap-3 text-xs font-semibold border-r border-slate-200 pr-4">
      <span class="flex items-center gap-1.5"><span class="w-3.5 h-3.5 rounded-sm inline-block" style="background:#ef4444"></span>0–300m (<?= $pdo->query("SELECT COUNT(*) FROM parcels WHERE zone='0-300m'")->fetchColumn() ?>)</span>
      <span class="flex items-center gap-1.5"><span class="w-3.5 h-3.5 rounded-sm inline-block" style="background:#f97316"></span>300–400m (<?= $pdo->query("SELECT COUNT(*) FROM parcels WHERE zone='300-400m'")->fetchColumn() ?>)</span>
      <span class="flex items-center gap-1.5"><span class="w-3.5 h-3.5 rounded-sm inline-block" style="background:#3b82f6"></span>400–900m (<?= $pdo->query("SELECT COUNT(*) FROM parcels WHERE zone='400-900m'")->fetchColumn() ?>)</span>
    </div>
    <!-- Status opacity legend -->
    <div class="flex items-center gap-3 text-xs font-medium border-r border-slate-200 pr-4">
      <span class="flex items-center gap-1.5"><span class="w-3 h-3 rounded-full bg-slate-800 inline-block opacity-90"></span>Completed (<?= $done ?>)</span>
      <span class="flex items-center gap-1.5"><span class="w-3 h-3 rounded-full bg-slate-800 inline-block opacity-50"></span>In Progress (<?= $prog ?>)</span>
      <span class="flex items-center gap-1.5"><span class="w-3 h-3 rounded-full bg-slate-800 inline-block opacity-20"></span>Pending (<?= $pend ?>)</span>
    </div>
    <!-- Live surveyor badge -->
    <span id="liveBadge" class="text-xs font-semibold text-slate-400 bg-slate-100 px-2 py-0.5 rounded-full">
      ⚫ 0 online
    </span>

    <!-- Zone filter -->
    <select id="zoneFilter" class="text-xs border border-slate-300 rounded-lg px-3 py-1.5 focus:outline-none focus:ring-2 focus:ring-blue-500">
      <option value="">All Zones</option>
      <option value="0-300m">Zone 0–300m</option>
      <option value="300-400m">Zone 300–400m</option>
      <option value="400-900m">Zone 400–900m</option>
    </select>
    <!-- Status filter -->
    <select id="statusFilter" class="text-xs border border-slate-300 rounded-lg px-3 py-1.5 focus:outline-none focus:ring-2 focus:ring-blue-500">
      <option value="">All Status</option>
      <option value="pending">Pending</option>
      <option value="in_progress">In Progress</option>
      <option value="completed">Completed</option>
    </select>
  </div>
</div>

<!-- Progress bar -->
<div class="flex-shrink-0 bg-white border-b border-slate-100">
  <div class="flex h-2">
    <div class="bg-green-500 transition-all" style="width:<?= $total ? round($done/$total*100,1) : 0 ?>%" title="Completed"></div>
    <div class="bg-amber-400 transition-all" style="width:<?= $total ? round($prog/$total*100,1) : 0 ?>%" title="In Progress"></div>
    <div class="bg-red-400 transition-all" style="width:<?= $total ? round($pend/$total*100,1) : 0 ?>%" title="Pending"></div>
  </div>
</div>

<!-- Map container -->
<div id="map" class="flex-1" style="z-index:0"></div>

<!-- Parcel detail panel (slides in on click) -->
<div id="detailPanel" class="hidden absolute top-0 right-0 h-full w-72 bg-white shadow-2xl border-l border-slate-200 z-50 flex flex-col" style="position:absolute;right:0;top:0">
  <div class="flex items-center justify-between px-4 py-3 border-b border-slate-200">
    <h3 class="font-semibold text-slate-800 text-sm">Parcel Detail</h3>
    <button onclick="closePanel()" class="text-slate-400 hover:text-slate-700">
      <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
    </button>
  </div>
  <div id="detailContent" class="p-4 flex-1 overflow-y-auto text-sm"></div>
</div>

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"/>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>

<script>
const PARCELS  = <?= $parcelsJson ?>;
const POLYGONS = <?= $polygonsJson ?>;

// Zone = fill color (3 distinct colors)
const ZONE_COLOR = {
  '0-300m':   '#ef4444',  // red   — critical
  '300-400m': '#f97316',  // orange — high
  '400-900m': '#3b82f6',  // blue   — standard
};

// Status = opacity (how "solid" the parcel looks)
const STATUS_OPACITY = {
  completed:   { fill: 0.80, stroke: 0.95 },
  in_progress: { fill: 0.45, stroke: 0.70 },
  pending:     { fill: 0.15, stroke: 0.40 },
};

// Init map
const map = L.map('map', { center: [27.7762, 85.2283], zoom: 14, zoomControl: true });
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '© OpenStreetMap contributors', maxZoom: 19
}).addTo(map);

function kmlToLatLng(raw) {
  return (raw || '').trim().split(/\s+/).reduce((acc, token) => {
    const p = token.split(',');
    if (p.length >= 2) {
      const lat = parseFloat(p[1]), lng = parseFloat(p[0]);
      if (!isNaN(lat) && !isNaN(lng)) acc.push([lat, lng]);
    }
    return acc;
  }, []);
}

function parcelStyle(zone, status) {
  const fill    = ZONE_COLOR[zone]    || '#94a3b8';
  const opacity = STATUS_OPACITY[status] || STATUS_OPACITY.pending;
  return { fillColor: fill, fillOpacity: opacity.fill, color: fill, weight: 1.2, opacity: opacity.stroke };
}

// Draw polygons — colored by zone, opacity by status
const polyLayers = [];
POLYGONS.forEach(p => {
  const pts = kmlToLatLng(p.polygon_coords);
  if (pts.length < 3) return;
  const style = parcelStyle(p.zone, p.survey_status);
  const poly  = L.polygon(pts, style);
  poly._parcelId = p.id;
  poly._zone     = p.zone;
  poly._status   = p.survey_status;
  poly.on('click', () => showParcelDetail(p.id));
  poly.on('mouseover', function() { this.setStyle({ weight: 2.5, fillOpacity: Math.min(style.fillOpacity + 0.2, 1) }); });
  poly.on('mouseout',  function() { this.setStyle(style); });
  poly.addTo(map);
  polyLayers.push(poly);
});

// Circle markers at centroids — same zone color + status opacity
const markerMap = {};
PARCELS.forEach(p => {
  if (!p.centroid_lat || !p.centroid_lng) return;
  const fill    = ZONE_COLOR[p.zone] || '#94a3b8';
  const opacity = STATUS_OPACITY[p.survey_status] || STATUS_OPACITY.pending;
  const marker  = L.circleMarker([p.centroid_lat, p.centroid_lng], {
    radius: 5, fillColor: fill, fillOpacity: opacity.fill + 0.15,
    color: '#fff', weight: 1.5,
  });
  marker._parcelId = p.id;
  marker._zone     = p.zone;
  marker._status   = p.survey_status;
  const statusLabel = p.survey_status.replace('_',' ');
  marker.bindTooltip(`<b>${p.parcel_no}</b><br>${p.zone} · <i>${statusLabel}</i>`, { sticky: true });
  marker.on('click', () => showParcelDetail(p.id));
  marker.addTo(map);
  markerMap[p.id] = { marker, data: p };
});

// Parcel detail panel
function showParcelDetail(id) {
  const p = markerMap[id]?.data;
  if (!p) return;
  const statusClass = {
    completed: 'bg-green-100 text-green-700',
    in_progress: 'bg-amber-100 text-amber-700',
    pending: 'bg-red-100 text-red-700',
  }[p.survey_status] || 'bg-slate-100 text-slate-700';
  const statusLabel = p.survey_status.replace('_', ' ').replace(/\b\w/g, c => c.toUpperCase());

  document.getElementById('detailContent').innerHTML = `
    <div class="space-y-3">
      <div class="flex items-center justify-between">
        <span class="px-2.5 py-0.5 rounded-full text-xs font-semibold ${statusClass}">${statusLabel}</span>
        <span class="text-xs text-slate-400">#${p.id}</span>
      </div>
      <div class="bg-slate-50 rounded-xl p-3 space-y-2">
        <div class="flex justify-between"><span class="text-slate-500">Parcel No</span><span class="font-semibold">${p.parcel_no || '—'}</span></div>
        <div class="flex justify-between"><span class="text-slate-500">Zone</span><span class="font-semibold">${p.zone}</span></div>
        <div class="flex justify-between"><span class="text-slate-500">Sheet</span><span class="font-semibold">${p.sheet_number || '—'}</span></div>
        <div class="flex justify-between"><span class="text-slate-500">Area</span><span class="font-semibold">${p.shape_area_sqm} m²</span></div>
        <div class="flex justify-between"><span class="text-slate-500">KML ID</span><span class="font-mono text-xs">${p.kml_id}</span></div>
      </div>
      <a href="surveys.php?parcel_id=${p.id}" class="block w-full text-center py-2 px-4 bg-blue-600 hover:bg-blue-700 text-white text-xs font-semibold rounded-lg transition">
        View Survey →
      </a>
    </div>
  `;
  document.getElementById('detailPanel').classList.remove('hidden');
}

function closePanel() {
  document.getElementById('detailPanel').classList.add('hidden');
}

// Zone / status filter
function applyFilters() {
  const zone   = document.getElementById('zoneFilter').value;
  const status = document.getElementById('statusFilter').value;
  Object.values(markerMap).forEach(({ marker }) => {
    const match =
      (!zone   || marker._zone   === zone)   &&
      (!status || marker._status === status);
    if (match) map.addLayer(marker);
    else map.removeLayer(marker);
  });
  polyLayers.forEach(poly => {
    const match =
      (!zone   || poly._zone   === zone)   &&
      (!status || poly._status === status);
    if (match) map.addLayer(poly);
    else map.removeLayer(poly);
  });
}

document.getElementById('zoneFilter').addEventListener('change', applyFilters);
document.getElementById('statusFilter').addEventListener('change', applyFilters);

// ── Parcel number search ────────────────────────────────────────────────────
const searchInput   = document.getElementById('parcelSearch');
const searchResults = document.getElementById('parcelSearchResults');
const searchClear   = document.getElementById('parcelSearchClear');

function focusParcel(p) {
  if (p.centroid_lat && p.centroid_lng) {
    map.setView([p.centroid_lat, p.centroid_lng], 19, { animate: true });
  }
  showParcelDetail(p.id);
  const mk = markerMap[p.id]?.marker;
  if (mk && mk.openTooltip) { try { mk.openTooltip(); } catch (e) {} }
  searchResults.classList.add('hidden');
}

function renderResults(matches) {
  if (!matches.length) {
    searchResults.innerHTML = '<div class="px-3 py-2 text-slate-400">No parcel found</div>';
    searchResults.classList.remove('hidden');
    return;
  }
  searchResults.innerHTML = matches.slice(0, 30).map(p => `
    <button type="button" data-id="${p.id}"
       class="block w-full text-left px-3 py-2 hover:bg-blue-50 border-b border-slate-50 last:border-0">
      <span class="font-semibold">${(p.parcel_no ?? '—')}</span>
      <span class="text-slate-400"> · ${p.zone} · sheet ${p.sheet_number || '—'}</span>
    </button>`).join('');
  searchResults.classList.remove('hidden');
  searchResults.querySelectorAll('button[data-id]').forEach(btn => {
    btn.addEventListener('click', () => {
      const p = markerMap[btn.dataset.id]?.data;
      if (p) focusParcel(p);
    });
  });
}

function runSearch() {
  const q = searchInput.value.trim().toLowerCase();
  searchClear.classList.toggle('hidden', q === '');
  if (!q) { searchResults.classList.add('hidden'); return; }
  const matches = PARCELS.filter(p =>
    String(p.parcel_no ?? '').toLowerCase().includes(q) ||
    String(p.sheet_number ?? '').toLowerCase().includes(q)
  );
  renderResults(matches);
}

searchInput.addEventListener('input', runSearch);
searchInput.addEventListener('keydown', e => {
  if (e.key === 'Enter') {
    e.preventDefault();
    const q = searchInput.value.trim().toLowerCase();
    const exact = PARCELS.find(p => String(p.parcel_no ?? '').toLowerCase() === q);
    const first = exact || PARCELS.find(p =>
      String(p.parcel_no ?? '').toLowerCase().includes(q) ||
      String(p.sheet_number ?? '').toLowerCase().includes(q));
    if (first) focusParcel(first);
  } else if (e.key === 'Escape') {
    searchResults.classList.add('hidden');
  }
});
searchClear.addEventListener('click', () => {
  searchInput.value = '';
  searchClear.classList.add('hidden');
  searchResults.classList.add('hidden');
  searchInput.focus();
});
document.addEventListener('click', e => {
  if (!e.target.closest('#parcelSearch') && !e.target.closest('#parcelSearchResults'))
    searchResults.classList.add('hidden');
});

// ── Live Surveyor Locations ────────────────────────────────────────────────────
// Polls every 15s; overlaid on top of parcels as distinct person markers.

const surveyorMarkers = {};   // keyed by user_id

function actionLabel(a) {
  const m = {
    map_open: '📍 Map open', parcel_tap: '👆 Tapped parcel',
    survey_start: '📝 Started survey', survey_save: '💾 Saved survey',
    sync_start: '🔄 Sync started', sync_complete: '✅ Synced',
    zone_selected: '🗺 Zone changed', app_open: '📱 App opened',
  };
  return m[a] || (a ? a.replace(/_/g, ' ') : '—');
}

function surveyorIcon(isActive, isRecent) {
  const color = isActive ? '#10b981' : isRecent ? '#f59e0b' : '#9ca3af';
  const pulse = isActive
    ? `animation:pulse 2s infinite;`
    : '';
  return L.divIcon({
    className: '',
    iconSize: [26, 26],
    iconAnchor: [13, 13],
    html: `
      <div style="
        width:26px;height:26px;border-radius:50%;
        background:${color};border:3px solid #fff;
        box-shadow:0 2px 6px rgba(0,0,0,.35),0 0 0 4px ${color}44;
        display:flex;align-items:center;justify-content:center;
        font-size:12px;line-height:1;${pulse}
      ">👤</div>`,
  });
}

async function fetchSurveyors() {
  try {
    const res  = await fetch('live_locations_ajax.php');
    const data = await res.json();
    const users = data.users || [];

    // Remove markers for users no longer in list
    const ids = new Set(users.map(u => u.user_id));
    for (const [id, m] of Object.entries(surveyorMarkers)) {
      if (!ids.has(+id)) { m.remove(); delete surveyorMarkers[id]; }
    }

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

      const icon = surveyorIcon(u.is_active, u.is_recent);
      if (surveyorMarkers[u.user_id]) {
        surveyorMarkers[u.user_id]
          .setLatLng([u.lat, u.lng])
          .setIcon(icon)
          .getPopup().setContent(popup);
      } else {
        surveyorMarkers[u.user_id] = L.marker([u.lat, u.lng], { icon, zIndexOffset: 1000 })
          .bindPopup(popup)
          .addTo(map);
      }
    });

    // Update counter badge
    const active = users.filter(u => u.is_active).length;
    const badge  = document.getElementById('liveBadge');
    if (badge) {
      badge.textContent = active > 0 ? `🟢 ${active} online` : `⚫ 0 online`;
      badge.className   = active > 0
        ? 'text-xs font-semibold text-green-600 bg-green-50 px-2 py-0.5 rounded-full'
        : 'text-xs font-semibold text-slate-400 bg-slate-100 px-2 py-0.5 rounded-full';
    }
  } catch (_) {}
}

// Kick off polling
fetchSurveyors();
setInterval(fetchSurveyors, 15000);

// Keyframe for pulse animation
const style = document.createElement('style');
style.textContent = `@keyframes pulse{0%,100%{box-shadow:0 2px 6px rgba(0,0,0,.35),0 0 0 4px transparent}50%{box-shadow:0 2px 6px rgba(0,0,0,.35),0 0 0 8px rgba(16,185,129,.2)}}`;
document.head.appendChild(style);
</script>

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