<?php
require __DIR__ . '/_common.php';
require_perm('view_dashboard');

$centerLat = 24.2075; // Al Ain default
$centerLng = 55.7447;
$zoom = 12;

// Fetch data (supports both lat/lng and latitude/longitude column names)
if (!function_exists('table_has_col')) {
  function table_has_col(string $table, string $col): bool {
    $r = db_one("SELECT COUNT(*) AS c FROM INFORMATION_SCHEMA.COLUMNS
                 WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?",
                [$table, $col]);
    return $r && intval($r['c'] ?? 0) > 0;
  }
}
if (!function_exists('geo_col')) {
  function geo_col(string $table, array $candidates): ?string {
    foreach ($candidates as $c) {
      if (table_has_col($table, $c)) return $c;
    }
    return null;
  }
}

$oLatCol = geo_col('oases', ['lat','latitude','Latitude']);
$oLngCol = geo_col('oases', ['lng','longitude','Longitude']);
$fLatCol = geo_col('farms', ['lat','latitude','Latitude']);
$fLngCol = geo_col('farms', ['lng','longitude','Longitude']);
$aLatCol = geo_col('assets', ['lat','latitude','Latitude']);
$aLngCol = geo_col('assets', ['lng','longitude','Longitude']);

$oases = [];
$farms = [];
$assets = [];

if ($oLatCol && $oLngCol) {
  $oases = db_all("SELECT id, code, name, {$oLatCol} AS lat, {$oLngCol} AS lng, status, palm_trees_count, falaj_outlets_count
                   FROM oases WHERE {$oLatCol} IS NOT NULL AND {$oLngCol} IS NOT NULL");
}

if ($fLatCol && $fLngCol) {
  $farms = db_all("SELECT f.id, f.code, f.oasis_id, f.owner_name, f.status, f.{$fLatCol} AS lat, f.{$fLngCol} AS lng, o.name AS oasis_name
                   FROM farms f JOIN oases o ON o.id=f.oasis_id
                   WHERE f.{$fLatCol} IS NOT NULL AND f.{$fLngCol} IS NOT NULL");
}

if ($aLatCol && $aLngCol) {
  $assets = db_all("SELECT id, owner_type, owner_id, category, tag, status, {$aLatCol} AS lat, {$aLngCol} AS lng
                    FROM assets WHERE {$aLatCol} IS NOT NULL AND {$aLngCol} IS NOT NULL");
}

$aflaj = db_all("SELECT id, oasis_id, code, name FROM aflaj");
// Build lookups
$oasisName = [];
foreach ($oases as $o) { $oasisName[intval($o['id'])] = $o['name']; }

$farmOasis = [];
$farmCode = [];
foreach ($farms as $f) {
  $farmOasis[intval($f['id'])] = intval($f['oasis_id']);
  $farmCode[intval($f['id'])] = $f['code'];
}

$falajOasis = [];
$falajName = [];
foreach ($aflaj as $a) {
  $falajOasis[intval($a['id'])] = intval($a['oasis_id']);
  $falajName[intval($a['id'])] = $a['name'] ?: $a['code'];
}

// Normalize markers
$markers = [];

// Oases markers
foreach ($oases as $o) {
  $markers[] = [
    'type' => 'oasis',
    'id' => intval($o['id']),
    'oasis_id' => intval($o['id']),
    'title' => $o['name'],
    'subtitle' => 'كود: ' . $o['code'],
    'status' => $o['status'],
    'lat' => floatval($o['lat']),
    'lng' => floatval($o['lng']),
    'url' => url('/index.php?page=oases&action=view&id=' . intval($o['id'])),
    'meta' => 'نخيل: ' . intval($o['palm_trees_count']) . ' • مخارج فلج: ' . intval($o['falaj_outlets_count']),
  ];
}

// Farms markers
foreach ($farms as $f) {
  $markers[] = [
    'type' => 'farm',
    'id' => intval($f['id']),
    'oasis_id' => intval($f['oasis_id']),
    'title' => 'مزرعة ' . $f['code'],
    'subtitle' => 'واحة: ' . ($f['oasis_name'] ?? '-'),
    'status' => $f['status'],
    'lat' => floatval($f['lat']),
    'lng' => floatval($f['lng']),
    'url' => url('/index.php?page=farms&action=edit&id=' . intval($f['id'])),
    'meta' => $f['owner_name'] ? ('المالك: ' . $f['owner_name']) : '',
  ];
}

// Assets markers
foreach ($assets as $a) {
  $ot = (string)$a['owner_type'];
  $oid = intval($a['owner_id']);
  $oasisId = 0;
  $ownerLabel = '';

  if ($ot === 'oasis') {
    $oasisId = $oid;
    $ownerLabel = 'واحة: ' . ($oasisName[$oid] ?? ('#' . $oid));
  } elseif ($ot === 'farm') {
    $oasisId = intval($farmOasis[$oid] ?? 0);
    $ownerLabel = 'مزرعة: ' . ($farmCode[$oid] ?? ('#' . $oid));
  } elseif ($ot === 'falaj') {
    $oasisId = intval($falajOasis[$oid] ?? 0);
    $ownerLabel = 'فلج: ' . ($falajName[$oid] ?? ('#' . $oid));
  }

  $markers[] = [
    'type' => 'asset',
    'id' => intval($a['id']),
    'oasis_id' => $oasisId,
    'title' => 'أصل: ' . $a['tag'],
    'subtitle' => 'تصنيف: ' . $a['category'],
    'status' => $a['status'],
    'lat' => floatval($a['lat']),
    'lng' => floatval($a['lng']),
    'url' => url('/index.php?page=assets&action=edit&id=' . intval($a['id'])),
    'meta' => $ownerLabel,
  ];
}

// Compute center if possible (use first oasis)
if (!empty($oases)) {
  $centerLat = floatval($oases[0]['lat']);
  $centerLng = floatval($oases[0]['lng']);
  $zoom = 13;
}

$mapData = [
  'markers' => $markers,
  'oases' => array_map(function($o){ return ['id'=>intval($o['id']),'name'=>$o['name'],'code'=>$o['code']]; }, $oases),
];

$DATA_JSON = json_encode($mapData, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
$centerLatJs = json_encode($centerLat);
$centerLngJs = json_encode($centerLng);
$zoomJs = intval($zoom);

$extra_head = <<<HTML
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin=""/>
<style>
#mapWrap{display:grid;grid-template-columns:340px 1fr;gap:12px;align-items:stretch}
@media (max-width: 980px){#mapWrap{grid-template-columns:1fr}}
#map{height:72vh;min-height:520px;border-radius:14px;overflow:hidden;border:1px solid rgba(255,255,255,.12)}
.panel .row{display:flex;gap:10px;flex-wrap:wrap;align-items:center}
.panel label{display:flex;gap:8px;align-items:center}
.micon{width:18px;height:18px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;color:#fff;font-size:12px;font-weight:700;border:1px solid rgba(0,0,0,.25)}
.micon.oasis{background:#2e7d32}
.micon.farm{background:#1565c0}
.micon.asset{background:#ef6c00}
.leaflet-popup-content{font-family:inherit}
.smallhint{opacity:.8}
</style>
HTML;

$extra_js = <<<HTML
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
<script>
(function(){
  const DATA = $DATA_JSON;

  const map = L.map("map", {scrollWheelZoom:true}).setView([$centerLatJs, $centerLngJs], $zoomJs);
  L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
    maxZoom: 19,
    attribution: "&copy; OpenStreetMap"
  }).addTo(map);

  const groups = {
    oasis: L.layerGroup().addTo(map),
    farm:  L.layerGroup().addTo(map),
    asset: L.layerGroup().addTo(map),
  };

  const makeIcon = (t) => L.divIcon({
    className: "",
    html: `<span class="micon \${t}">\${t==="oasis"?"و":(t==="farm"?"م":"أ")}</span>`,
    iconSize: [18,18],
    iconAnchor: [9,9]
  });

  const state = {
    show: {oasis:true,farm:true,asset:true},
    oasisId: "all",
    q: ""
  };

  const elShowO = document.getElementById("shOasis");
  const elShowF = document.getElementById("shFarms");
  const elShowA = document.getElementById("shAssets");
  const elOasisSel = document.getElementById("oasisFilter");
  const elQ = document.getElementById("q");
  const elFit = document.getElementById("fitAll");

  function clearAll(){ Object.values(groups).forEach(g=>g.clearLayers()); }

  function matches(m){
    if (!state.show[m.type]) return false;
    if (state.oasisId !== "all" && String(m.oasis_id) !== state.oasisId) return false;
    if (state.q){
      const s = (m.title + " " + m.subtitle + " " + (m.meta||"")).toLowerCase();
      if (!s.includes(state.q)) return false;
    }
    return true;
  }

  function escapeHtml(str){
    return String(str||"").replace(/[&<>"']/g, (s) => ({
      "&":"&amp;","<":"&lt;",">":"&gt;","\"":"&quot;","'":"&#39;"
    }[s]));
  }

  function popupHtml(m){
    const meta = m.meta ? `<div class="smallhint" style="margin-top:6px">\${escapeHtml(m.meta)}</div>` : "";
    const st = m.status ? `<div class="smallhint">الحالة: \${escapeHtml(m.status)}</div>` : "";
    return `
      <div style="min-width:240px">
        <div style="font-weight:800;margin-bottom:6px">\${escapeHtml(m.title)}</div>
        <div class="small">\${escapeHtml(m.subtitle)}</div>
        \${st}
        \${meta}
        <div style="margin-top:10px;display:flex;gap:8px;flex-wrap:wrap">
          <a class="btn" href="\${m.url}">فتح التفاصيل</a>
          <a class="btn" target="_blank" rel="noopener" href="https://www.google.com/maps?q=\${m.lat},\${m.lng}">Google Maps</a>
        </div>
      </div>
    `;
  }

  function render(){
    clearAll();
    const bounds = [];
    DATA.markers.forEach(m=>{
      if (!matches(m)) return;
      const marker = L.marker([m.lat, m.lng], {icon: makeIcon(m.type)});
      marker.bindPopup(popupHtml(m));
      groups[m.type].addLayer(marker);
      bounds.push([m.lat, m.lng]);
    });

    document.getElementById("cntO").textContent = DATA.markers.filter(x=>x.type==="oasis").length;
    document.getElementById("cntF").textContent = DATA.markers.filter(x=>x.type==="farm").length;
    document.getElementById("cntA").textContent = DATA.markers.filter(x=>x.type==="asset").length;
  }

  function fitAll(){
    const bounds = [];
    DATA.markers.forEach(m=>{ if (matches(m)) bounds.push([m.lat,m.lng]); });
    if (!bounds.length) return;
    map.fitBounds(bounds, {padding:[20,20]});
  }

  elShowO.addEventListener("change", ()=>{ state.show.oasis = elShowO.checked; render(); fitAll(); });
  elShowF.addEventListener("change", ()=>{ state.show.farm  = elShowF.checked; render(); fitAll(); });
  elShowA.addEventListener("change", ()=>{ state.show.asset = elShowA.checked; render(); fitAll(); });
  elOasisSel.addEventListener("change", ()=>{ state.oasisId = elOasisSel.value; render(); fitAll(); });
  elQ.addEventListener("input", ()=>{ state.q = (elQ.value||"").trim().toLowerCase(); render(); });

  elFit.addEventListener("click", (e)=>{ e.preventDefault(); fitAll(); });

  render();
  setTimeout(fitAll, 250);
})();
</script>
HTML;


?>
<div class="grid">
  <div class="card">
    <h1 style="margin:0 0 8px 0">الخريطة</h1>
    <div class="small">عرض الواحات والمزارع والأصول على خريطة Leaflet (OpenStreetMap).</div>
  </div>

  <div id="mapWrap">
    <div class="card panel">
      <div class="row" style="justify-content:space-between">
        <div>
          <div class="small">طبقات</div>
          <div style="margin-top:8px;display:grid;gap:8px">
            <label><input type="checkbox" id="shOasis" checked> <span class="micon oasis">و</span> الواحات <span class="smallhint">(<span id="cntO">0</span>)</span></label>
            <label><input type="checkbox" id="shFarms" checked> <span class="micon farm">م</span> المزارع <span class="smallhint">(<span id="cntF">0</span>)</span></label>
            <label><input type="checkbox" id="shAssets" checked> <span class="micon asset">أ</span> الأصول <span class="smallhint">(<span id="cntA">0</span>)</span></label>
          </div>
        </div>
        <div style="text-align:left">
          <a class="btn" id="fitAll" href="#">ملاءمة الخريطة</a>
        </div>
      </div>

      <hr>

      <div class="row" style="gap:8px">
        <div style="flex:1;min-width:220px">
          <div class="small">فلترة حسب الواحة</div>
          <select class="input" id="oasisFilter" style="width:100%;margin-top:6px">
            <option value="all">كل الواحات</option>
            <?php foreach ($mapData['oases'] as $o): ?>
              <option value="<?= e($o['id']) ?>"><?= e($o['name']) ?> (<?= e($o['code']) ?>)</option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>

      <div style="margin-top:12px">
        <div class="small">بحث</div>
        <input class="input" id="q" placeholder="اسم/كود/وسم/تصنيف/مالك..." style="width:100%;margin-top:6px">
      </div>

      <div class="small" style="margin-top:12px;opacity:.85">
        ملاحظة: يظهر فقط العناصر التي تحتوي على إحداثيات (Lat/Lng).
      </div>
    </div>

    <div class="card" style="padding:0">
      <div id="map"></div>
    </div>
  </div>
</div>