<?php
require_once 'auth_guard.php';
$pageTitle = 'الأماكن السياحية';

$msg = '';
$err = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'add' || $action === 'edit') {
        $name_ar  = trim($_POST['name_ar'] ?? '');
        $name_en  = trim($_POST['name_en'] ?? '');
        $name_fr  = trim($_POST['name_fr'] ?? '');
        $desc_ar  = trim($_POST['desc_ar'] ?? '');
        $desc_en  = trim($_POST['desc_en'] ?? '');
        $desc_fr  = trim($_POST['desc_fr'] ?? '');
        $category = $_POST['category'] ?? 'nature';
        $lat      = (float)($_POST['lat'] ?? 0);
        $lng      = (float)($_POST['lng'] ?? 0);
        $is_active= isset($_POST['is_active']) ? 1 : 0;

        $allowed_cats = ['nature','heritage','oasis','desert','lake','monument','other'];
        if (!in_array($category, $allowed_cats)) $category = 'nature';

        if (!$name_ar || !$lat || !$lng) {
            $err = 'يرجى ملء اسم المكان (عربي) وإدخال الإحداثيات.';
        } else {
            $image = upload_image('image', 'places');
            if ($action === 'add') {
                $stmt = db()->prepare("INSERT INTO places (name_ar,name_en,name_fr,desc_ar,desc_en,desc_fr,category,lat,lng,image,is_active) VALUES (?,?,?,?,?,?,?,?,?,?,?)");
                $stmt->execute([$name_ar,$name_en,$name_fr,$desc_ar,$desc_en,$desc_fr,$category,$lat,$lng,$image,$is_active]);
                $msg = 'تم إضافة المكان بنجاح ✅';
            } else {
                $id = (int)$_POST['id'];
                if ($image) {
                    $stmt = db()->prepare("UPDATE places SET name_ar=?,name_en=?,name_fr=?,desc_ar=?,desc_en=?,desc_fr=?,category=?,lat=?,lng=?,image=?,is_active=? WHERE id=?");
                    $stmt->execute([$name_ar,$name_en,$name_fr,$desc_ar,$desc_en,$desc_fr,$category,$lat,$lng,$image,$is_active,$id]);
                } else {
                    $stmt = db()->prepare("UPDATE places SET name_ar=?,name_en=?,name_fr=?,desc_ar=?,desc_en=?,desc_fr=?,category=?,lat=?,lng=?,is_active=? WHERE id=?");
                    $stmt->execute([$name_ar,$name_en,$name_fr,$desc_ar,$desc_en,$desc_fr,$category,$lat,$lng,$is_active,$id]);
                }
                $msg = 'تم تحديث المكان بنجاح ✅';
            }
        }
    }

    if ($action === 'delete') {
        db()->prepare("DELETE FROM places WHERE id=?")->execute([(int)$_POST['id']]);
        $msg = 'تم حذف المكان.';
    }

    if ($action === 'toggle') {
        db()->prepare("UPDATE places SET is_active = 1 - is_active WHERE id=?")->execute([(int)$_POST['id']]);
        header('Location: places.php'); exit;
    }
}

$filter = $_GET['cat'] ?? '';
$search = trim($_GET['q'] ?? '');
$where  = []; $params = [];
if ($filter) { $where[] = 'category = ?'; $params[] = $filter; }
if ($search)  { $where[] = '(name_ar LIKE ? OR name_en LIKE ?)'; $params[] = "%$search%"; $params[] = "%$search%"; }
$sql = "SELECT * FROM places" . ($where ? ' WHERE '.implode(' AND ',$where) : '') . " ORDER BY created_at DESC";
$stmt = db()->prepare($sql); $stmt->execute($params);
$places = $stmt->fetchAll();

$cats       = ['nature'=>'🌿 طبيعة','heritage'=>'🏛️ تراث','oasis'=>'🌴 واحة','desert'=>'🏜️ صحراء','lake'=>'💧 شط','monument'=>'🗿 معلم','other'=>'📍 أخرى'];
$cat_colors = ['nature'=>'#40916c','heritage'=>'#a07060','oasis'=>'#52B788','desert'=>'#C9A84C','lake'=>'#3b9fd4','monument'=>'#7c6f8f','other'=>'#888888'];
$cat_icons  = ['nature'=>'🌿','heritage'=>'🏛️','oasis'=>'🌴','desert'=>'🏜️','lake'=>'💧','monument'=>'🗿','other'=>'📍'];

$places_json = json_encode(array_map(fn($p) => [
    'id'     => $p['id'],
    'lat'    => (float)$p['lat'],
    'lng'    => (float)$p['lng'],
    'name'   => $p['name_ar'],
    'name_en'=> $p['name_en'] ?? '',
    'cat'    => $p['category'],
    'cat_label' => $cats[$p['category']] ?? $p['category'],
    'desc'   => mb_substr($p['desc_ar'] ?? '', 0, 100),
    'active' => (bool)$p['is_active'],
    'image'  => $p['image'] ?? '',
    'color'  => $cat_colors[$p['category']] ?? '#2d6a4f',
    'icon'   => $cat_icons[$p['category']] ?? '📍',
], $places));

include 'header.php';
?>

<style>
/* ── Map ── */
#overviewMap {
  width:100%; height:400px;
  border-radius:12px; overflow:hidden; position:relative;
  border:1.5px solid var(--border); background:#e8f4ec;
}
#overviewMap iframe { width:100%; height:100%; border:0; display:block; }

/* ── Pins ── */
.apin {
  position:absolute; transform:translate(-50%,-100%);
  cursor:pointer; z-index:10; display:none;
  transition:transform .2s, z-index 0s;
  pointer-events:auto;
}
.apin:hover { transform:translate(-50%,-110%) scale(1.08); z-index:20; }
.apin-bubble {
  display:flex; align-items:center; gap:5px;
  background:var(--pc,#2d6a4f); color:#fff;
  border-radius:50px; padding:5px 12px;
  font-size:.78rem; font-weight:700; font-family:Cairo,sans-serif;
  white-space:nowrap; box-shadow:0 3px 14px rgba(0,0,0,.28);
  border:2px solid #fff;
}
.apin-bubble.off { opacity:.5; filter:grayscale(.5); }
.apin-arrow {
  width:10px; height:8px; margin:0 auto;
  background:var(--pc,#2d6a4f);
  clip-path:polygon(50% 100%,0 0,100% 0);
}

/* ── Popup ── */
#pinPopup {
  position:absolute; background:#fff;
  border-radius:14px; padding:16px 18px;
  min-width:230px; max-width:270px;
  box-shadow:0 8px 32px rgba(0,0,0,.18);
  z-index:100; font-family:Cairo,sans-serif;
  direction:rtl; display:none;
  transform:translate(-50%,calc(-100% - 60px));
  pointer-events:auto;
}
#pinPopup::after {
  content:''; position:absolute;
  bottom:-9px; left:50%; transform:translateX(-50%);
  width:18px; height:9px; background:#fff;
  clip-path:polygon(0 0,100% 0,50% 100%);
}
#pinPopup.show { display:block; }
.pp-close {
  position:absolute; top:8px; left:12px;
  background:none; border:none; font-size:1rem;
  color:#aaa; cursor:pointer; line-height:1;
}
.pp-title { font-weight:800; font-size:.98rem; color:#1b4332; margin-bottom:3px; }
.pp-cat   { font-size:.72rem; color:#6b7c74; margin-bottom:6px; }
.pp-desc  { font-size:.8rem; color:#555; line-height:1.5; margin-bottom:10px; min-height:20px; }
.pp-coord { font-size:.7rem; color:#aaa; margin-bottom:10px; direction:ltr; text-align:left; }
.pp-btns  { display:flex; gap:6px; }
.pp-btn   { flex:1; text-align:center; padding:7px; border-radius:8px; font-size:.75rem; font-weight:700; cursor:pointer; border:none; font-family:Cairo,sans-serif; }
.pp-edit  { background:#e8f5e9; color:#2d6a4f; }
.pp-del   { background:#fee2e2; color:#dc2626; }
.pp-gmaps { display:block; text-align:center; font-size:.72rem; color:#4285f4; margin-top:8px; text-decoration:none; font-weight:600; }

/* ── Map preview in modal ── */
.map-preview {
  width:100%; height:220px; border-radius:10px;
  overflow:hidden; border:2px solid var(--border);
  background:#e8f4ec; display:flex; align-items:center;
  justify-content:center; flex-direction:column;
  gap:8px; color:#2d6a4f; font-family:Cairo,sans-serif;
  font-weight:600; font-size:.88rem;
}
.map-preview iframe { width:100%; height:100%; border:0; display:block; }
</style>

<div class="page-header" style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px">
  <div>
    <div class="page-title">🗺️ الأماكن السياحية</div>
    <div class="page-sub"><?= count($places) ?> مكان في قاعدة البيانات</div>
  </div>
  <button class="btn btn-primary" onclick="document.getElementById('addModal').classList.add('open')">＋ إضافة مكان</button>
</div>

<?php if ($msg): ?><div class="ok-box">✅ <?= htmlspecialchars($msg) ?></div><?php endif; ?>
<?php if ($err): ?><div class="err-box">⚠️ <?= htmlspecialchars($err) ?></div><?php endif; ?>

<!-- ══ OVERVIEW MAP ══ -->
<div class="table-wrap" style="margin-bottom:20px;padding:16px">
  <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:10px">
    <div style="font-weight:800;color:var(--dark)">🗺️ خريطة جميع الأماكن</div>
    <div style="font-size:.75rem;color:var(--muted)">اضغط على أي مؤشر 📍 لعرض التفاصيل</div>
  </div>
  <div style="position:relative">
    <div id="overviewMap">
      <iframe id="ovFrame" src="https://maps.google.com/maps?q=33.95,5.92&z=10&output=embed&hl=ar"
              allowfullscreen loading="lazy" referrerpolicy="no-referrer-when-downgrade"></iframe>

      <!-- Pins overlay -->
      <div id="pinsLayer" style="position:absolute;inset:0;pointer-events:none;z-index:10">
        <?php foreach($places as $pl):
          $color = $cat_colors[$pl['category']] ?? '#2d6a4f';
          $icon  = $cat_icons[$pl['category']] ?? '📍';
        ?>
        <div class="apin"
             data-id="<?= $pl['id'] ?>"
             data-lat="<?= $pl['lat'] ?>"
             data-lng="<?= $pl['lng'] ?>"
             data-name="<?= htmlspecialchars($pl['name_ar']) ?>"
             data-cat="<?= htmlspecialchars($cats[$pl['category']] ?? '') ?>"
             data-desc="<?= htmlspecialchars(mb_substr($pl['desc_ar'] ?? '', 0, 90)) ?>"
             data-active="<?= $pl['is_active'] ?>"
             style="--pc:<?= $color ?>;pointer-events:auto"
             onclick="showPopup(this,event)">
          <div class="apin-bubble <?= $pl['is_active'] ? '' : 'off' ?>">
            <span><?= $icon ?></span><span><?= htmlspecialchars($pl['name_ar']) ?></span>
          </div>
          <div class="apin-arrow"></div>
        </div>
        <?php endforeach; ?>

        <!-- Shared popup -->
        <div id="pinPopup">
          <button class="pp-close" onclick="closePopup(event)">✕</button>
          <div class="pp-title" id="ppName"></div>
          <div class="pp-cat"   id="ppCat"></div>
          <div class="pp-desc"  id="ppDesc"></div>
          <div class="pp-coord" id="ppCoord"></div>
          <div class="pp-btns">
            <button class="pp-btn pp-edit" onclick="editFromPopup()">✏️ تعديل</button>
            <button class="pp-btn pp-del"  onclick="deleteFromPopup()">🗑️ حذف</button>
          </div>
          <a class="pp-gmaps" id="ppGmaps" href="#" target="_blank">🌐 فتح في Google Maps</a>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Filters -->
<div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:16px;align-items:center">
  <form method="GET" style="display:flex;gap:8px;flex:1;min-width:200px">
    <input type="text" name="q" value="<?= htmlspecialchars($search) ?>" placeholder="🔍 بحث..." style="flex:1">
    <?php if ($filter): ?><input type="hidden" name="cat" value="<?= htmlspecialchars($filter) ?>"><?php endif; ?>
    <button type="submit" class="btn btn-primary btn-sm">بحث</button>
  </form>
  <div style="display:flex;gap:6px;flex-wrap:wrap">
    <a href="places.php" class="btn btn-sm <?= !$filter ? 'btn-primary' : 'btn-ghost' ?>">الكل</a>
    <?php foreach ($cats as $k => $v): ?>
      <a href="?cat=<?= $k ?><?= $search ? '&q='.urlencode($search) : '' ?>"
         class="btn btn-sm <?= $filter===$k ? 'btn-primary' : 'btn-ghost' ?>"><?= $v ?></a>
    <?php endforeach; ?>
  </div>
</div>

<!-- Table -->
<div class="table-wrap">
  <div class="table-head"><span class="table-head-title">قائمة الأماكن</span></div>
  <div class="tbl-scroll">
    <table class="tbl">
      <thead><tr>
        <th>الصورة</th><th>الاسم</th><th>التصنيف</th><th>الإحداثيات</th><th>الحالة</th><th>إجراءات</th>
      </tr></thead>
      <tbody>
      <?php foreach ($places as $pl): ?>
      <tr>
        <td>
          <?php if ($pl['image']): ?>
            <img src="../<?= htmlspecialchars($pl['image']) ?>" style="width:52px;height:44px;object-fit:cover;border-radius:8px">
          <?php else: ?>
            <div class="thumb" style="font-size:1.4rem;display:flex;align-items:center;justify-content:center;width:52px;height:44px;background:var(--bg-2);border-radius:8px">
              <?= $cat_icons[$pl['category']] ?? '📍' ?>
            </div>
          <?php endif; ?>
        </td>
        <td>
          <div style="font-weight:700"><?= htmlspecialchars($pl['name_ar']) ?></div>
          <div style="font-size:.75rem;color:var(--muted)"><?= htmlspecialchars($pl['name_en'] ?? '') ?></div>
        </td>
        <td><span class="badge badge-green"><?= $cats[$pl['category']] ?? $pl['category'] ?></span></td>
        <td>
          <a href="https://www.google.com/maps?q=<?= $pl['lat'] ?>,<?= $pl['lng'] ?>" target="_blank"
             style="font-size:.78rem;color:#4285f4;font-weight:600;text-decoration:none;">
            📍 <?= number_format((float)$pl['lat'],4) ?>, <?= number_format((float)$pl['lng'],4) ?>
          </a>
        </td>
        <td>
          <form method="POST" style="display:inline">
            <input type="hidden" name="action" value="toggle">
            <input type="hidden" name="id" value="<?= $pl['id'] ?>">
            <button type="submit" class="badge <?= $pl['is_active'] ? 'badge-green' : 'badge-red' ?>" style="cursor:pointer;border:none;font-family:inherit">
              <?= $pl['is_active'] ? '✅ مفعّل' : '❌ مخفي' ?>
            </button>
          </form>
        </td>
        <td>
          <div style="display:flex;gap:6px">
            <button class="btn btn-ghost btn-sm"
              onclick='openEdit(<?= htmlspecialchars(json_encode($pl), ENT_QUOTES) ?>)'>✏️ تعديل</button>
            <form method="POST" onsubmit="return confirm('حذف هذا المكان نهائياً؟')">
              <input type="hidden" name="action" value="delete">
              <input type="hidden" name="id" value="<?= $pl['id'] ?>">
              <button type="submit" class="btn btn-danger btn-sm">🗑️</button>
            </form>
          </div>
        </td>
      </tr>
      <?php endforeach; ?>
      <?php if (!$places): ?>
        <tr><td colspan="6" style="text-align:center;color:var(--muted);padding:32px">لا توجد أماكن. أضف أول مكان!</td></tr>
      <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- ══ ADD MODAL ══ -->
<div class="modal-overlay" id="addModal">
  <div class="modal" style="max-width:580px">
    <div class="modal-header">
      <div class="modal-title">➕ إضافة مكان جديد</div>
      <button class="modal-close" onclick="document.getElementById('addModal').classList.remove('open')">✕</button>
    </div>
    <form method="POST" enctype="multipart/form-data">
      <input type="hidden" name="action" value="add">
      <div class="modal-body">
        <div class="form-grid form-grid-2" style="gap:12px">
          <div><label class="flabel">الاسم (عربي) *</label><input type="text" name="name_ar" required></div>
          <div><label class="flabel">Name (English)</label><input type="text" name="name_en"></div>
          <div><label class="flabel">Nom (Français)</label><input type="text" name="name_fr"></div>
          <div>
            <label class="flabel">التصنيف</label>
            <select name="category">
              <?php foreach($cats as $k=>$v): ?><option value="<?=$k?>"><?=$v?></option><?php endforeach; ?>
            </select>
          </div>
        </div>
        <div style="margin-top:12px"><label class="flabel">وصف (عربي)</label><textarea name="desc_ar" rows="2"></textarea></div>

        <!-- Location -->
        <div style="margin-top:14px">
          <label class="flabel">📍 الموقع الجغرافي *</label>
          <div style="display:grid;grid-template-columns:1fr 1fr auto;gap:8px;margin-bottom:8px;align-items:flex-end">
            <div>
              <label class="flabel" style="font-size:.72rem">خط العرض (Lat)</label>
              <input type="number" name="lat" id="addLat" step="0.0000001" placeholder="33.9536" required oninput="previewAdd()">
            </div>
            <div>
              <label class="flabel" style="font-size:.72rem">خط الطول (Lng)</label>
              <input type="number" name="lng" id="addLng" step="0.0000001" placeholder="5.9256" required oninput="previewAdd()">
            </div>
            <button type="button" class="btn btn-ghost btn-sm" onclick="setDefault('add')" style="white-space:nowrap;margin-bottom:1px">📍 المغير</button>
          </div>
          <div class="map-preview" id="addPreview">
            <span style="font-size:2rem">🗺️</span>
            أدخل الإحداثيات لمعاينة الموقع
          </div>
          <p style="font-size:.72rem;color:var(--muted);margin-top:6px">
            💡 للحصول على إحداثيات: افتح
            <a href="https://maps.google.com" target="_blank" style="color:#4285f4">Google Maps</a>
            → انقر على المكان بالزر الأيمن → انسخ الأرقام
          </p>
        </div>

        <div style="margin-top:12px"><label class="flabel">صورة المكان</label><input type="file" name="image" accept="image/*" style="padding:8px"></div>
        <div style="margin-top:12px"><label class="form-check"><input type="checkbox" name="is_active" checked> إظهار على الموقع</label></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-ghost" onclick="document.getElementById('addModal').classList.remove('open')">إلغاء</button>
        <button type="submit" class="btn btn-primary">💾 حفظ المكان</button>
      </div>
    </form>
  </div>
</div>

<!-- ══ EDIT MODAL ══ -->
<div class="modal-overlay" id="editModal">
  <div class="modal" style="max-width:580px">
    <div class="modal-header">
      <div class="modal-title">✏️ تعديل المكان</div>
      <button class="modal-close" onclick="document.getElementById('editModal').classList.remove('open')">✕</button>
    </div>
    <form method="POST" enctype="multipart/form-data">
      <input type="hidden" name="action" value="edit">
      <input type="hidden" name="id" id="editId">
      <div class="modal-body">
        <div class="form-grid form-grid-2" style="gap:12px">
          <div><label class="flabel">الاسم (عربي) *</label><input type="text" name="name_ar" id="editNameAr" required></div>
          <div><label class="flabel">Name (English)</label><input type="text" name="name_en" id="editNameEn"></div>
          <div><label class="flabel">Nom (Français)</label><input type="text" name="name_fr" id="editNameFr"></div>
          <div>
            <label class="flabel">التصنيف</label>
            <select name="category" id="editCat">
              <?php foreach($cats as $k=>$v): ?><option value="<?=$k?>"><?=$v?></option><?php endforeach; ?>
            </select>
          </div>
        </div>
        <div style="margin-top:12px"><label class="flabel">وصف (عربي)</label><textarea name="desc_ar" id="editDescAr" rows="2"></textarea></div>
        <div style="margin-top:14px">
          <label class="flabel">📍 الموقع</label>
          <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:8px">
            <div><label class="flabel" style="font-size:.72rem">خط العرض</label><input type="number" name="lat" id="editLat" step="0.0000001" required oninput="previewEdit()"></div>
            <div><label class="flabel" style="font-size:.72rem">خط الطول</label><input type="number" name="lng" id="editLng" step="0.0000001" required oninput="previewEdit()"></div>
          </div>
          <div class="map-preview" id="editPreview">
            <iframe id="editMapIframe" src="" width="100%" height="100%" style="border:0;display:block;"></iframe>
          </div>
        </div>
        <div style="margin-top:12px"><label class="flabel">صورة جديدة (اختياري)</label><input type="file" name="image" accept="image/*" style="padding:8px"></div>
        <div style="margin-top:12px"><label class="form-check"><input type="checkbox" name="is_active" id="editActive"> إظهار على الموقع</label></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-ghost" onclick="document.getElementById('editModal').classList.remove('open')">إلغاء</button>
        <button type="submit" class="btn btn-primary">💾 حفظ التعديلات</button>
      </div>
    </form>
  </div>
</div>

<script>
var placesData = <?= $places_json ?>;
var activePopupId = null;
var addTimer = null, editTimer = null;

/* ══ MAP PINS POSITIONING ══ */
var MAP = { lat:33.95, lng:5.92, zoom:10 };

function toPixel(lat, lng, cLat, cLng, zoom, w, h) {
  var s = Math.pow(2, zoom);
  function ly(la){ var sin=Math.sin(la*Math.PI/180); return (0.5-Math.log((1+sin)/(1-sin))/(4*Math.PI))*256*s; }
  function lx(lo){ return (lo+180)/360*256*s; }
  return { x: w/2+(lx(lng)-lx(cLng)), y: h/2+(ly(lat)-ly(cLat)) };
}

function positionPins(cLat, cLng, zoom) {
  cLat = cLat || MAP.lat; cLng = cLng || MAP.lng; zoom = zoom || MAP.zoom;
  var map = document.getElementById('overviewMap');
  if (!map) return;
  var w = map.offsetWidth, h = map.offsetHeight;
  document.querySelectorAll('.apin').forEach(function(pin) {
    var p = toPixel(+pin.dataset.lat, +pin.dataset.lng, cLat, cLng, zoom, w, h);
    if (p.x > 20 && p.x < w-20 && p.y > 20 && p.y < h-20) {
      pin.style.left = p.x+'px'; pin.style.top = p.y+'px'; pin.style.display = 'block';
    } else { pin.style.display = 'none'; }
  });
}

/* ══ POPUP ══ */
function showPopup(pin, e) {
  e.stopPropagation();
  var popup = document.getElementById('pinPopup');
  if (activePopupId === pin.dataset.id && popup.classList.contains('show')) {
    closePopup(e); return;
  }
  activePopupId = pin.dataset.id;

  document.getElementById('ppName').textContent  = pin.dataset.name;
  document.getElementById('ppCat').textContent   = pin.dataset.cat;
  document.getElementById('ppDesc').textContent  = pin.dataset.desc || 'لا يوجد وصف';
  document.getElementById('ppCoord').textContent = pin.dataset.lat + ', ' + pin.dataset.lng;
  document.getElementById('ppGmaps').href = 'https://www.google.com/maps?q='+pin.dataset.lat+','+pin.dataset.lng;
  popup.dataset.id = pin.dataset.id;

  // Position popup above pin
  popup.style.left = pin.style.left;
  popup.style.top  = pin.style.top;
  popup.classList.add('show');

  // Focus map on place
  document.getElementById('ovFrame').src =
    'https://maps.google.com/maps?q='+pin.dataset.lat+','+pin.dataset.lng+'&z=13&output=embed&hl=ar';
  setTimeout(function(){
    positionPins(+pin.dataset.lat, +pin.dataset.lng, 13);
  }, 800);
}

function closePopup(e) {
  if (e) e.stopPropagation();
  document.getElementById('pinPopup').classList.remove('show');
  activePopupId = null;
}

function editFromPopup() {
  var id = parseInt(document.getElementById('pinPopup').dataset.id);
  var pl = placesData.find(function(p){ return p.id === id; });
  if (pl) { closePopup(); openEdit(pl); }
}

function deleteFromPopup() {
  var id = document.getElementById('pinPopup').dataset.id;
  if (!confirm('حذف هذا المكان نهائياً؟')) return;
  var f = document.createElement('form');
  f.method = 'POST';
  f.innerHTML = '<input name="action" value="delete"><input name="id" value="'+id+'">';
  document.body.appendChild(f); f.submit();
}

document.addEventListener('click', function(e) {
  if (!e.target.closest('.apin') && !e.target.closest('#pinPopup')) {
    document.getElementById('pinPopup').classList.remove('show');
    activePopupId = null;
    document.getElementById('ovFrame').src = 'https://maps.google.com/maps?q=33.95,5.92&z=10&output=embed&hl=ar';
    setTimeout(function(){ positionPins(); }, 800);
  }
});

/* ══ ADD MODAL ══ */
function previewAdd() {
  var lat = parseFloat(document.getElementById('addLat').value);
  var lng = parseFloat(document.getElementById('addLng').value);
  if (isNaN(lat)||isNaN(lng)||!lat||!lng) return;
  clearTimeout(addTimer);
  addTimer = setTimeout(function() {
    document.getElementById('addPreview').innerHTML =
      '<iframe src="https://maps.google.com/maps?q='+lat+','+lng+'&z=15&output=embed&hl=ar" width="100%" height="100%" style="border:0;display:block;" allowfullscreen loading="lazy"></iframe>';
  }, 700);
}

function setDefault(mode) {
  var lat = '33.9536000', lng = '5.9256000';
  document.getElementById(mode+'Lat').value = lat;
  document.getElementById(mode+'Lng').value = lng;
  if (mode === 'add') previewAdd(); else previewEdit();
}

/* ══ EDIT MODAL ══ */
function openEdit(pl) {
  document.getElementById('editId').value      = pl.id;
  document.getElementById('editNameAr').value  = pl.name_ar || pl.name || '';
  document.getElementById('editNameEn').value  = pl.name_en || '';
  document.getElementById('editNameFr').value  = pl.name_fr || '';
  document.getElementById('editDescAr').value  = pl.desc_ar || pl.desc || '';
  document.getElementById('editCat').value     = pl.category || pl.cat || 'nature';
  document.getElementById('editLat').value     = pl.lat;
  document.getElementById('editLng').value     = pl.lng;
  document.getElementById('editActive').checked = pl.is_active == 1 || pl.active === true;
  document.getElementById('editMapIframe').src =
    'https://maps.google.com/maps?q='+pl.lat+','+pl.lng+'&z=14&output=embed&hl=ar';
  document.getElementById('editModal').classList.add('open');
}

function previewEdit() {
  var lat = parseFloat(document.getElementById('editLat').value);
  var lng = parseFloat(document.getElementById('editLng').value);
  if (isNaN(lat)||isNaN(lng)||!lat||!lng) return;
  clearTimeout(editTimer);
  editTimer = setTimeout(function() {
    document.getElementById('editMapIframe').src =
      'https://maps.google.com/maps?q='+lat+','+lng+'&z=15&output=embed&hl=ar';
  }, 700);
}

/* ══ INIT ══ */
document.addEventListener('DOMContentLoaded', function() {
  setTimeout(positionPins, 600);
  window.addEventListener('resize', function(){ positionPins(); });

  document.querySelectorAll('.modal-overlay').forEach(function(o) {
    o.addEventListener('click', function(e){ if(e.target===this) this.classList.remove('open'); });
  });
  document.querySelectorAll('.modal-close').forEach(function(b) {
    b.addEventListener('click', function(){ this.closest('.modal-overlay').classList.remove('open'); });
  });
});
</script>

<?php include 'footer.php'; ?>
