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

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

// ── Handle POST actions ────────────────────────────────────
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') {
        $id = (int)$_POST['id'];
        db()->prepare("DELETE FROM places WHERE id=?")->execute([$id]);
        $msg = 'تم حذف المكان.';
    }

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

// ── Fetch all places ─────────────────────────────────────
$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";
$places = db()->prepare($sql);
$places->execute($params);
$places = $places->fetchAll();

$cats = ['nature'=>'🌿 طبيعة','heritage'=>'🏛️ تراث','oasis'=>'🌴 واحة','desert'=>'🏜️ صحراء','lake'=>'💧 شط','monument'=>'🗿 معلم','other'=>'📍 أخرى'];

include 'header.php';
?>

<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; ?>

<!-- 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>

<!-- Map overview -->
<div class="table-wrap" style="margin-bottom:20px;padding:16px">
  <div style="font-size:.88rem;font-weight:700;margin-bottom:10px;color:var(--dark)">🗺️ خريطة الأماكن</div>
  <div id="overviewMap" style="width:100%;height:320px;border-radius:var(--r)"></div>
</div>

<!-- Places 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"><?= ['nature'=>'🌿','heritage'=>'🏛️','oasis'=>'🌴','desert'=>'🏜️','lake'=>'💧','monument'=>'🗿','other'=>'📍'][$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 style="font-size:.78rem;color:var(--muted)"><?= number_format($pl['lat'],4) ?>, <?= number_format($pl['lng'],4) ?></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)) ?>)">✏️ تعديل</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">
    <div class="modal-header">
      <div class="modal-title">➕ إضافة مكان جديد</div>
      <button class="modal-close">✕</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>
        <div style="margin-top:12px">
          <label class="flabel">📍 تحديد الموقع على الخريطة *</label>
          <div id="addMap" style="width:100%;height:220px;border-radius:var(--r);border:1.5px solid var(--border);margin-bottom:6px"></div>
          <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px">
            <div><label class="flabel">خط العرض</label><input type="number" name="lat" id="addLat" step="0.0000001" placeholder="33.9536"></div>
            <div><label class="flabel">خط الطول</label><input type="number" name="lng" id="addLng" step="0.0000001" placeholder="5.9256"></div>
          </div>
          <p style="font-size:.72rem;color:var(--muted);margin-top:4px">انقر على الخريطة لتحديد الموقع تلقائياً</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 modal-close">إلغاء</button>
        <button type="submit" class="btn btn-primary">حفظ المكان</button>
      </div>
    </form>
  </div>
</div>

<!-- EDIT MODAL -->
<div class="modal-overlay" id="editModal">
  <div class="modal">
    <div class="modal-header">
      <div class="modal-title">✏️ تعديل المكان</div>
      <button class="modal-close">✕</button>
    </div>
    <form method="POST" enctype="multipart/form-data" id="editForm">
      <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:12px">
          <label class="flabel">📍 الموقع</label>
          <div id="editMap" style="width:100%;height:200px;border-radius:var(--r);border:1.5px solid var(--border);margin-bottom:6px"></div>
          <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px">
            <div><label class="flabel">خط العرض</label><input type="number" name="lat" id="editLat" step="0.0000001"></div>
            <div><label class="flabel">خط الطول</label><input type="number" name="lng" id="editLng" step="0.0000001"></div>
          </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 modal-close">إلغاء</button>
        <button type="submit" class="btn btn-primary">حفظ التعديلات</button>
      </div>
    </form>
  </div>
</div>

<script>
var addMap, addMarker, editMap, editMarker, overviewMap;

// Overview map
document.addEventListener('DOMContentLoaded', function() {
  overviewMap = L.map('overviewMap').setView([33.95, 5.92], 9);
  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {attribution:'© OpenStreetMap',maxZoom:19}).addTo(overviewMap);

  var places = <?= json_encode(array_map(fn($p)=>['lat'=>(float)$p['lat'],'lng'=>(float)$p['lng'],'name'=>$p['name_ar'],'active'=>(bool)$p['is_active']], $places)) ?>;
  places.forEach(function(p) {
    var icon = L.divIcon({className:'',html:'<div style="background:'+(p.active?'#2D6A4F':'#aaa')+';;width:12px;height:12px;border-radius:50%;border:2px solid #fff;box-shadow:0 1px 4px rgba(0,0,0,.3)"></div>',iconSize:[12,12]});
    L.marker([p.lat,p.lng],{icon}).addTo(overviewMap).bindPopup('<strong>'+p.name+'</strong>');
  });
});

// Add modal map
document.getElementById('addModal').addEventListener('click', function(e) {
  if (e.target === this) return;
});

function initAddMap() {
  if (addMap) return;
  setTimeout(function() {
    addMap = L.map('addMap').setView([33.9536, 5.9256], 12);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {attribution:'© OpenStreetMap'}).addTo(addMap);
    addMarker = L.marker([33.9536, 5.9256], {draggable:true}).addTo(addMap);
    document.getElementById('addLat').value = '33.9536000';
    document.getElementById('addLng').value = '5.9256000';

    function updateAdd(ll) {
      document.getElementById('addLat').value = ll.lat.toFixed(7);
      document.getElementById('addLng').value = ll.lng.toFixed(7);
    }
    addMarker.on('dragend', e => updateAdd(e.target.getLatLng()));
    addMap.on('click', function(e) { addMarker.setLatLng(e.latlng); updateAdd(e.latlng); });

    // sync manual inputs
    ['addLat','addLng'].forEach(id => {
      document.getElementById(id).addEventListener('change', function() {
        var lat = parseFloat(document.getElementById('addLat').value);
        var lng = parseFloat(document.getElementById('addLng').value);
        if (!isNaN(lat) && !isNaN(lng)) { addMarker.setLatLng([lat,lng]); addMap.setView([lat,lng],13); }
      });
    });
    addMap.invalidateSize();
  }, 100);
}

document.querySelector('[onclick*="addModal"]').addEventListener('click', initAddMap);

// Edit modal
function openEdit(place) {
  document.getElementById('editId').value      = place.id;
  document.getElementById('editNameAr').value  = place.name_ar;
  document.getElementById('editNameEn').value  = place.name_en || '';
  document.getElementById('editNameFr').value  = place.name_fr || '';
  document.getElementById('editDescAr').value  = place.desc_ar || '';
  document.getElementById('editCat').value     = place.category;
  document.getElementById('editLat').value     = place.lat;
  document.getElementById('editLng').value     = place.lng;
  document.getElementById('editActive').checked = place.is_active == 1;

  document.getElementById('editModal').classList.add('open');

  setTimeout(function() {
    var lat = parseFloat(place.lat), lng = parseFloat(place.lng);
    if (!editMap) {
      editMap = L.map('editMap').setView([lat,lng], 13);
      L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {attribution:'© OpenStreetMap'}).addTo(editMap);
      editMarker = L.marker([lat,lng], {draggable:true}).addTo(editMap);
      function updateEdit(ll) {
        document.getElementById('editLat').value = ll.lat.toFixed(7);
        document.getElementById('editLng').value = ll.lng.toFixed(7);
      }
      editMarker.on('dragend', e => updateEdit(e.target.getLatLng()));
      editMap.on('click', function(e) { editMarker.setLatLng(e.latlng); updateEdit(e.latlng); });
    } else {
      editMap.setView([lat,lng], 13);
      editMarker.setLatLng([lat,lng]);
    }
    editMap.invalidateSize();
  }, 150);
}
</script>

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