<?php
require_once __DIR__ . '/includes/lang.php';
require_once __DIR__ . '/config/db.php';
session_start();

$dir      = t('dir');
$code     = t('lang_code');
$name_col = "name_{$code}";
$desc_col = "desc_{$code}";

// Fetch places & providers — محمية من أخطاء DB
$places    = [];
$providers = [];
try {
    $places    = db()->query("SELECT * FROM places WHERE is_active=1 ORDER BY id LIMIT 6")->fetchAll();
    $providers = db()->query("
        SELECT p.*,
               COALESCE(AVG(r.rating),0) AS avg_rating,
               COUNT(r.id) AS rating_count
        FROM providers p
        LEFT JOIN provider_ratings r ON r.provider_id = p.id
        WHERE p.status='approved'
        GROUP BY p.id
        ORDER BY RAND() LIMIT 8
    ")->fetchAll();
} catch (Exception $e) {
    // DB connected but tables missing — show empty state gracefully
}

$cat_icons = ['nature'=>'🌿','heritage'=>'🏛️','oasis'=>'🌴','desert'=>'🏜️','lake'=>'💧','monument'=>'🗿','other'=>'📍'];
$act_icons = ['restaurant'=>'🍽️','hotel'=>'🏨','guide'=>'🗺️','craft'=>'🛍️','agency'=>'✈️','transport'=>'🚲'];
?>
<!DOCTYPE html>
<html lang="<?= htmlspecialchars($code) ?>" dir="<?= htmlspecialchars($dir) ?>">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="<?= htmlspecialchars(t('meta_desc')) ?>">
  <title><?= htmlspecialchars(t('site_name')) ?> — <?= htmlspecialchars(t('tagline')) ?></title>
  <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🌴</text></svg>">
  <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="css/style.css">
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">

<style>
/* ── Custom Leaflet Markers ── */
.custom-marker { display:flex; flex-direction:column; align-items:center; }
.cm-bubble {
  display:flex; align-items:center; gap:5px;
  background:var(--mc,#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;
  transition:transform .2s, box-shadow .2s;
}
.cm-bubble:hover { transform:scale(1.06); box-shadow:0 6px 20px rgba(0,0,0,.35); }
.cm-icon { font-size:.95rem; }
.cm-name { max-width:120px; overflow:hidden; text-overflow:ellipsis; }
.cm-arrow {
  width:10px; height:8px; margin:0 auto;
  background:var(--mc,#2d6a4f);
  clip-path:polygon(50% 100%,0 0,100% 0);
}

/* ── Leaflet popup custom style ── */
.custom-leaflet-popup .leaflet-popup-content-wrapper {
  border-radius:14px !important;
  box-shadow:0 8px 32px rgba(0,0,0,.18) !important;
  padding:0 !important;
  overflow:hidden;
}
.custom-leaflet-popup .leaflet-popup-content {
  margin:0 !important; width:240px !important;
}
.custom-leaflet-popup .leaflet-popup-tip-container { margin-top:-1px; }
.lf-popup { padding:14px 16px; font-family:Cairo,sans-serif; direction:rtl; }
.lf-popup-cat   { font-size:.72rem; font-weight:700; margin-bottom:4px; }
.lf-popup-title { font-size:1rem; font-weight:900; color:#1b4332; margin-bottom:6px; }
.lf-popup-desc  { font-size:.8rem; color:#666; line-height:1.55; margin-bottom:10px; }
.lf-popup-btn {
  display:block; text-align:center;
  color:#fff; padding:8px; border-radius:8px;
  font-size:.8rem; font-weight:700;
  text-decoration:none; font-family:Cairo,sans-serif;
  transition:.2s;
}
.lf-popup-btn:hover { opacity:.85; }
</style>
</head>
<body>

<!-- ── NAVIGATION ── -->
<nav class="nav" id="mainNav">
  <div class="nav-inner">
    <a href="index.php<?= $code!=='ar'?'?lang='.$code:'' ?>" class="nav-logo">
      تحويسة<span>.</span>
    </a>
    <div class="nav-links">
      <a href="#places"><?= htmlspecialchars(t('nav_places')) ?></a>
      <a href="#activities"><?= htmlspecialchars(t('nav_activities')) ?></a>
      <a href="#contact"><?= htmlspecialchars(t('nav_contact')) ?></a>
    </div>
    <div class="nav-right">
      <div class="lang-sw">
        <a href="<?= lang_url('ar') ?>" class="<?= $code==='ar'?'active':'' ?>">ع</a>
        <a href="<?= lang_url('en') ?>" class="<?= $code==='en'?'active':'' ?>">EN</a>
        <a href="<?= lang_url('fr') ?>" class="<?= $code==='fr'?'active':'' ?>">FR</a>
      </div>
      <?php if (isset($_SESSION['user_id'])): ?>
        <a href="dashboard.php" class="nav-auth-link">👤 <?= htmlspecialchars($_SESSION['username']) ?></a>
        <button class="nav-settings-btn" id="navSettingsBtn" aria-label="الإعدادات" title="الإعدادات">⚙️</button>
      <?php else: ?>
        <a href="auth/login.php<?= $code!=='ar'?'?lang='.$code:'' ?>" class="nav-auth-link"><?= htmlspecialchars(t('login')) ?></a>
      <?php endif; ?>
      <button class="hamburger" id="hamburger" aria-label="القائمة" aria-expanded="false">
        <span></span><span></span><span></span>
      </button>
    </div>
  </div>
</nav>

<!-- Mobile Menu -->
<div class="mobile-menu" id="mobileMenu">
  <div class="mobile-menu-inner">
    <a href="#places"><?= htmlspecialchars(t('nav_places')) ?></a>
    <a href="#activities"><?= htmlspecialchars(t('nav_activities')) ?></a>
    <a href="#contact"><?= htmlspecialchars(t('nav_contact')) ?></a>
    <?php if (isset($_SESSION['user_id'])): ?>
      <a href="dashboard.php" style="background:var(--gp);color:var(--g);font-weight:800">👤 <?= htmlspecialchars($_SESSION['username']) ?></a>
    <?php else: ?>
      <a href="auth/login.php<?= $code!=='ar'?'?lang='.$code:'' ?>" style="background:var(--gp);color:var(--g);font-weight:800"><?= htmlspecialchars(t('login')) ?></a>
      <a href="auth/register.php<?= $code!=='ar'?'?lang='.$code:'' ?>"><?= htmlspecialchars(t('register')) ?></a>
    <?php endif; ?>
    <div class="mobile-lang">
      <a href="<?= lang_url('ar') ?>" class="<?= $code==='ar'?'active':'' ?>">العربية</a>
      <a href="<?= lang_url('en') ?>" class="<?= $code==='en'?'active':'' ?>">English</a>
      <a href="<?= lang_url('fr') ?>" class="<?= $code==='fr'?'active':'' ?>">Français</a>
    </div>
  </div>
</div>

<!-- ── HERO ── -->
<section class="hero">
  <!-- Animated background elements -->
  <div class="hero-blob hero-blob-1"></div>
  <div class="hero-blob hero-blob-2"></div>
  <div class="hero-sand hero-sand-1"></div>
  <div class="hero-sand hero-sand-2"></div>
  <div class="hero-sand hero-sand-3"></div>
  <div class="hero-star"></div>
  <div class="hero-star"></div>
  <div class="hero-star"></div>
  <div class="hero-star"></div>
  <div class="hero-star"></div>

  <div class="hero-content">
    <div class="hero-badge">📍 <?= htmlspecialchars(t('hero_location')) ?></div>
    <h1 class="hero-title"><?= t('hero_title') ?></h1>
    <p class="hero-desc"><?= htmlspecialchars(t('hero_desc')) ?></p>
    <div class="hero-btns">
      <a href="#places" class="hero-btn-primary">
        🌴 <?= htmlspecialchars(t('hero_cta')) ?>
      </a>
      <?php if (!isset($_SESSION['user_id'])): ?>
        <a href="auth/register.php<?= $code!=='ar'?'?lang='.$code:'' ?>" class="hero-btn-outline">
          👤 <?= htmlspecialchars(t('register')) ?>
        </a>
      <?php endif; ?>
    </div>
    <div class="hero-stats">
      <div class="hero-stat">
        <div class="hero-stat-num"><?= htmlspecialchars(t('stat1_num')) ?></div>
        <div class="hero-stat-label"><?= htmlspecialchars(t('stat1_label')) ?></div>
      </div>
      <div class="hero-stat">
        <div class="hero-stat-num"><?= htmlspecialchars(t('stat2_num')) ?></div>
        <div class="hero-stat-label"><?= htmlspecialchars(t('stat2_label')) ?></div>
      </div>
      <div class="hero-stat">
        <div class="hero-stat-num"><?= htmlspecialchars(t('stat3_num')) ?></div>
        <div class="hero-stat-label"><?= htmlspecialchars(t('stat3_label')) ?></div>
      </div>
    </div><!-- /.hero-stats -->
  </div><!-- /.hero-content -->

  <!-- Scroll indicator -->
  <div class="hero-scroll" onclick="document.getElementById('places').scrollIntoView({behavior:'smooth'})">
    <div class="hero-scroll-wheel"></div>
  </div>

</section>
<section class="section" id="places">
  <div class="container">
    <div class="reveal">
      <div class="section-tag">🗺️ <?= htmlspecialchars(t('places_label')) ?></div>
      <h2 class="section-title"><?= htmlspecialchars(t('places_title')) ?></h2>
      <p class="section-desc"><?= htmlspecialchars(t('places_desc')) ?></p>
    </div>

    <?php if ($places): ?>
    <div class="places-grid stagger-children">
      <?php foreach ($places as $i => $pl): ?>
      <div class="place-card reveal reveal-delay-<?= min($i+1, 3) ?>">
        <?php if ($pl['image']): ?>
          <img src="<?= htmlspecialchars($pl['image']) ?>" alt="<?= htmlspecialchars($pl[$name_col] ?: $pl['name_ar']) ?>" class="place-img">
        <?php else: ?>
          <div class="place-img"><?= $cat_icons[$pl['category']] ?? '📍' ?></div>
        <?php endif; ?>
        <div class="place-body">
          <span class="place-cat"><?= htmlspecialchars(t('cat_'.$pl['category'])) ?></span>
          <div class="place-name"><?= htmlspecialchars($pl[$name_col] ?: $pl['name_ar']) ?></div>
          <?php if ($pl[$desc_col] ?: $pl['desc_ar']): ?>
            <p class="place-desc"><?= htmlspecialchars(mb_substr($pl[$desc_col] ?: $pl['desc_ar'], 0, 100)) ?>…</p>
          <?php endif; ?>
          <a href="#placeMap<?= $pl['id'] ?>"
             class="place-map-btn"
             onclick="openPlaceMap(<?= $pl['lat'] ?>,<?= $pl['lng'] ?>,'<?= addslashes($pl[$name_col]?:$pl['name_ar']) ?>');return false">
            📍 <?= htmlspecialchars(t('view_map')) ?>
          </a>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <div style="margin-top:32px">
      <!-- Map Search — upgraded -->
      <div class="map-section-wrap">
        <div class="map-search-hero">
          <div class="map-search-hero-inner">
            <div class="map-search-label">🗺️ استكشف الأماكن على الخريطة</div>
            <div class="map-search-bar-new">
              <svg class="map-search-svg-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
              <input type="text" id="mapSearchInput" class="map-search-input-new" placeholder="ابحث عن واحة، شط، قصر..." autocomplete="off" spellcheck="false">
              <button class="map-search-clear-new" id="mapSearchClear" style="display:none" aria-label="مسح">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
              </button>
            </div>
            <div class="map-search-results-new" id="mapSearchResults"></div>
            <div class="map-search-tags" id="mapSearchTags">
              <?php
              $cats = array_unique(array_column($places,'category'));
              $tag_icons = ['lake'=>'💧','oasis'=>'🌴','desert'=>'🏜️','heritage'=>'🏛️','nature'=>'🌿','monument'=>'🗿','other'=>'📍'];
              foreach($cats as $c):
              ?>
              <button class="map-tag" data-cat="<?= $c ?>"><?= $tag_icons[$c]??'📍' ?> <?= htmlspecialchars(t('cat_'.$c)) ?></button>
              <?php endforeach; ?>
              <button class="map-tag map-tag-all active" data-cat="all">🔍 الكل</button>
            </div>
          </div>
        </div>
        <div id="mapWrapper" style="width:100%;height:480px;border-radius:0 0 20px 20px;overflow:hidden;position:relative;background:#e8f4ec;">
  <div id="allPlacesMap" style="width:100%;height:100%;"></div>
</div>

<!-- Place info popup

<!-- Place info popup (shown when clicking a marker) -->
<div id="placeInfoBar" style="display:none;background:#fff;border-radius:12px;padding:14px 18px;margin-top:12px;box-shadow:0 4px 20px rgba(0,0,0,.1);display:none;align-items:center;gap:14px;justify-content:space-between;">
  <div>
    <div id="placeInfoName" style="font-weight:800;font-size:1rem;color:#1b4332;font-family:Cairo,sans-serif;"></div>
    <div id="placeInfoCat" style="font-size:.78rem;color:#6b7c74;margin-top:2px;font-family:Cairo,sans-serif;"></div>
  </div>
  <a id="placeInfoLink" href="#" target="_blank"
     style="background:#2d6a4f;color:white;padding:8px 16px;border-radius:50px;font-size:.82rem;font-weight:700;font-family:Cairo,sans-serif;white-space:nowrap;text-decoration:none;">
    فتح في خرائط Google ↗
  </a>
</div>
      </div>
    </div>
    <?php else: ?>
      <p style="color:var(--muted);text-align:center;padding:40px">لم تُضاف أماكن بعد. تحقق قريباً!</p>
    <?php endif; ?>
  </div>
</section>

<!-- ── ACTIVITIES ── -->
<section class="section" id="activities" style="background:linear-gradient(180deg,var(--g-pale) 0%,var(--cream) 100%)">
  <div class="container">
    <div class="reveal">
      <div class="section-tag">🏪 <?= htmlspecialchars(t('activities_label')) ?></div>
      <h2 class="section-title"><?= htmlspecialchars(t('activities_title')) ?></h2>
      <p class="section-desc"><?= htmlspecialchars(t('activities_desc')) ?></p>
    </div>

    <?php if ($providers): ?>
    <div class="acts-grid stagger-children" style="margin-top:32px">
      <?php foreach ($providers as $pr): ?>
      <div class="act-card reveal">
        <div class="act-card-icon"><?= $act_icons[$pr['activity_type']] ?? '🏪' ?></div>
        <div class="act-card-type"><?= htmlspecialchars($pr['activity_type']) ?></div>
        <div class="act-card-name"><?= htmlspecialchars(mb_substr($pr['business_name'],0,40)) ?></div>
        <?php if ($pr['address']): ?>
          <div class="act-card-addr">📍 <?= htmlspecialchars(mb_substr($pr['address'],0,50)) ?></div>
        <?php endif; ?>
        <?php if ($pr['phone']): ?>
          <div style="font-size:.78rem;color:var(--muted);margin-top:4px">📞 <?= htmlspecialchars($pr['phone']) ?></div>
        <?php endif; ?>

        <!-- Stars Rating Display -->
        <div class="provider-rating-display">
          <?php $avg = round((float)$pr['avg_rating'],1); $cnt = (int)$pr['rating_count']; ?>
          <div class="stars-row">
            <?php for($s=1;$s<=5;$s++): ?>
              <span class="star <?= $s<=$avg?'star-filled':'star-empty' ?>">★</span>
            <?php endfor; ?>
          </div>
          <span class="rating-num"><?= $avg > 0 ? number_format($avg,1) : '—' ?></span>
          <span class="rating-count">(<?= $cnt ?>)</span>
        </div>

        <?php if (isset($_SESSION['user_id'])): ?>
          <!-- Rate this provider (tourist only) -->
          <?php if (($_SESSION['role']??'tourist') === 'tourist'): ?>
            <button class="rate-btn" onclick="openRateModal(<?= $pr['id'] ?>,'<?= addslashes($pr['business_name']) ?>')" title="تقييم الخدمة">
              ⭐ تقييم الخدمة
            </button>
            <button class="req-service-btn" onclick="openRequestModal(<?= $pr['id'] ?>,'<?= addslashes($pr['business_name']) ?>')" title="طلب خدمة">
              📩 طلب خدمة
            </button>
          <?php endif; ?>
        <?php else: ?>
          <a href="auth/login.php<?= $code!=='ar'?'?lang='.$code:'' ?>" class="req-service-btn-ghost">
            📩 سجّل دخولك لطلب خدمة
          </a>
        <?php endif; ?>
      </div>
      <?php endforeach; ?>
    </div>
    <?php else: ?>
      <div style="text-align:center;padding:48px;color:var(--muted)">
        <div style="font-size:3rem;margin-bottom:12px">🏪</div>
        <p>لم تُضاف خدمات بعد.</p>
        <a href="auth/register.php<?= $code!=='ar'?'?lang='.$code:'' ?>" style="display:inline-block;margin-top:16px;color:var(--g-main);font-weight:700">
          + سجّل نشاطك الآن
        </a>
      </div>
    <?php endif; ?>
  </div>
</section>

<!-- ── CONTACT ── -->
<section class="section" id="contact">
  <div class="container">
    <div class="reveal">
      <div class="section-tag">✉️ <?= htmlspecialchars(t('contact_label')) ?></div>
      <h2 class="section-title"><?= htmlspecialchars(t('contact_title')) ?></h2>
      <p class="section-desc"><?= htmlspecialchars(t('contact_desc')) ?></p>
    </div>

    <div class="contact-grid">
      <div class="contact-info reveal">
        <div class="contact-info-item">
          <div class="contact-icon">📍</div>
          <div class="contact-info-text">
            <strong>العنوان</strong>
            <span><?= htmlspecialchars(t('info_address')) ?></span>
          </div>
        </div>
        <div class="contact-info-item">
          <div class="contact-icon">📞</div>
          <div class="contact-info-text">
            <strong>الهاتف</strong>
            <span><?= htmlspecialchars(t('info_phone')) ?></span>
          </div>
        </div>
        <div class="contact-info-item">
          <div class="contact-icon">✉️</div>
          <div class="contact-info-text">
            <strong>البريد الإلكتروني</strong>
            <span><?= htmlspecialchars(t('info_email')) ?></span>
          </div>
        </div>
        <div class="contact-info-item">
          <div class="contact-icon">🕒</div>
          <div class="contact-info-text">
            <strong>أوقات العمل</strong>
            <span><?= htmlspecialchars(t('info_hours')) ?></span>
          </div>
        </div>
      </div>

      <div class="reveal reveal-delay-2">
        <div id="formSuccess" class="form-success"><?= htmlspecialchars(t('form_success')) ?></div>
        <form class="contact-form" id="contactForm" novalidate>
          <input type="hidden" name="lang" value="<?= htmlspecialchars($code) ?>">
          <input type="text"  name="name"    class="form-input" placeholder="<?= htmlspecialchars(t('form_name')) ?>" required>
          <input type="email" name="email"   class="form-input" placeholder="<?= htmlspecialchars(t('form_email')) ?>" required>
          <input type="tel"   name="phone"   class="form-input" placeholder="<?= htmlspecialchars(t('form_phone')) ?>">
          <textarea           name="message" class="form-input" rows="4" placeholder="<?= htmlspecialchars(t('form_message')) ?>" required style="resize:vertical"></textarea>
          <button type="submit" class="form-submit"><?= htmlspecialchars(t('form_send')) ?></button>
        </form>
      </div>
    </div>
  </div>
</section>

<!-- ── FOOTER ── -->
<footer class="footer">
  <div class="footer-grid">
    <div>
      <div class="footer-logo">تحويسة<span>.</span></div>
      <p class="footer-tagline"><?= htmlspecialchars(t('footer_tagline')) ?></p>
    </div>
    <div>
      <div style="font-size:.75rem;font-weight:700;text-transform:uppercase;letter-spacing:.1em;color:rgba(255,255,255,.5);margin-bottom:12px"><?= htmlspecialchars(t('footer_nav')) ?></div>
      <div class="footer-links">
        <a href="#places"><?= htmlspecialchars(t('nav_places')) ?></a>
        <a href="#activities"><?= htmlspecialchars(t('nav_activities')) ?></a>
        <a href="#contact"><?= htmlspecialchars(t('nav_contact')) ?></a>
        <a href="auth/login.php"><?= htmlspecialchars(t('login')) ?></a>
        <a href="auth/register.php"><?= htmlspecialchars(t('register')) ?></a>
      </div>
    </div>
  </div>
  <div class="footer-bottom">
    <span><?= htmlspecialchars(t('footer_copy')) ?></span>
    <span><?= htmlspecialchars(t('footer_made')) ?></span>
  </div>
</footer>

<!-- Place map modal -->
<div id="placeMapModal" style="position:fixed;inset:0;background:rgba(0,0,0,.6);z-index:900;display:none;align-items:center;justify-content:center;padding:20px">
  <div style="background:#fff;border-radius:20px;width:100%;max-width:540px;overflow:hidden;box-shadow:0 20px 60px rgba(0,0,0,.3)">
    <div style="padding:16px 20px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--border)">
      <div id="placeMapTitle" style="font-weight:800;font-size:1rem;font-family:var(--font)"></div>
      <button onclick="document.getElementById('placeMapModal').style.display='none'" style="font-size:1.3rem;cursor:pointer;font-family:var(--font);color:var(--muted)">✕</button>
    </div>
    <div id="singleMap" style="width:100%;height:300px"></div>
  </div>
</div>

<script src="js/main.js"></script>
<script>
// Leaflet map with Esri tiles (no OSM dependency)
(function() {

// Places from DB (empty if DB not connected)
var dbPlaces = <?= json_encode($places ? array_map(fn($p) => [
  'lat'  => (float)$p['lat'],
  'lng'  => (float)$p['lng'],
  'name' => $p[$name_col] ?: $p['name_ar'],
  'cat'  => $p['category'],
  'desc' => mb_substr($p[$desc_col] ?: $p['desc_ar'] ?: '', 0, 120),
  'img'  => $p['image'] ?? '',
], $places) : []) ?>;

// Fallback default places (El M'Ghair region) — always shown
var defaultPlaces = [
  { lat:33.9500, lng:5.9200, name:'بحيرة مليلة',         cat:'lake',    desc:'بحيرة مالحة رائعة تعكس السماء كالمرآة في قلب الصحراء الجزائرية', img:'' },
  { lat:33.9536, lng:5.9256, name:'واحة المغير',          cat:'oasis',   desc:'واحة خلابة مليئة بأشجار النخيل الباسقة والظل الرائع في وادي ريغ', img:'' },
  { lat:33.8800, lng:5.8500, name:'كثبان الرمال الذهبية', cat:'desert',  desc:'كثبان رملية ذهبية لا نهاية لها تمتد حتى الأفق مع غروب الشمس', img:'' },
  { lat:33.9580, lng:5.9300, name:'قصر المغير التاريخي',  cat:'heritage',desc:'قصر تاريخي عريق يحكي قصص الحضارات المتعاقبة في هذه المنطقة', img:'' },
  { lat:34.1800, lng:6.3000, name:'شط ملغيغ',             cat:'lake',    desc:'أحد أكبر البحيرات المالحة في الجزائر، تجربة فريدة من نوعها', img:'' }
];

// Use DB places if available, otherwise fallback
var placesData = (dbPlaces && dbPlaces.length > 0) ? dbPlaces : defaultPlaces;

var CAT_COLOR = {
  nature:   '#40916c',
  heritage: '#a07060',
  oasis:    '#52B788',
  desert:   '#C9A84C',
  lake:     '#3b9fd4',
  monument: '#7c6f8f',
  other:    '#888888'
};
var CAT_ICON = {
  nature:'🌿', heritage:'🏛️', oasis:'🌴',
  desert:'🏜️', lake:'💧', monument:'🗿', other:'📍'
};

document.addEventListener('DOMContentLoaded', function() {

  if (!placesData.length) return;

  // Init Leaflet map
  var map = L.map('allPlacesMap', {
    center: [33.95, 5.92],
    zoom: 10,
    zoomControl: true,
    scrollWheelZoom: false
  });

  // Esri World Street Map — no usage limits, works without API key
  L.tileLayer(
    'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}',
    { attribution: 'Tiles © Esri', maxZoom: 18 }
  ).addTo(map);

  // Force render after mount
  [100, 400, 900].forEach(function(ms) {
    setTimeout(function() { map.invalidateSize(true); }, ms);
  });

  // Add markers
  var markers = [];
  var openPopupId = null;

  placesData.forEach(function(p, i) {
    var color = CAT_COLOR[p.cat] || '#2d6a4f';
    var icon  = CAT_ICON[p.cat]  || '📍';

    // Custom HTML marker
    var markerHtml = [
      '<div class="custom-marker" style="--mc:' + color + '">',
        '<div class="cm-bubble">',
          '<span class="cm-icon">' + icon + '</span>',
          '<span class="cm-name">' + p.name + '</span>',
        '</div>',
        '<div class="cm-arrow"></div>',
      '</div>'
    ].join('');

    var divIcon = L.divIcon({
      html: markerHtml,
      className: '',
      iconAnchor: [60, 44],
      popupAnchor: [0, -48]
    });

    var marker = L.marker([p.lat, p.lng], { icon: divIcon }).addTo(map);

    // Rich popup content
    var imgHtml = p.img
      ? '<img src="' + p.img + '" style="width:100%;height:100px;object-fit:cover;border-radius:8px;margin-bottom:8px;display:block;">'
      : '';

    var popupContent = [
      '<div class="lf-popup" dir="rtl">',
        imgHtml,
        '<div class="lf-popup-cat" style="color:' + color + ';">' + icon + ' ' + (p.cat || '') + '</div>',
        '<div class="lf-popup-title">' + p.name + '</div>',
        p.desc ? '<div class="lf-popup-desc">' + p.desc + '...</div>' : '',
        '<a class="lf-popup-btn" style="background:' + color + ';" href="https://www.google.com/maps?q=' + p.lat + ',' + p.lng + '" target="_blank">',
          '🌐 فتح في Google Maps',
        '</a>',
      '</div>'
    ].join('');

    marker.bindPopup(popupContent, {
      maxWidth: 260,
      className: 'custom-leaflet-popup'
    });

    markers.push(marker);
  });

  // Fit map to all markers
  if (markers.length > 1) {
    var group = L.featureGroup(markers);
    map.fitBounds(group.getBounds().pad(0.2));
  }

  // Search & filter
  var searchInput = document.getElementById('mapSearchInput');
  var searchClear = document.getElementById('mapSearchClear');
  var searchRes   = document.getElementById('mapSearchResults');

  if (searchInput) {
    searchInput.addEventListener('input', function() {
      var q = this.value.trim().toLowerCase();
      if (searchClear) searchClear.style.display = q ? 'flex' : 'none';
      if (!q) { if(searchRes) searchRes.innerHTML = ''; return; }
      var matched = placesData.filter(function(p) {
        return p.name.toLowerCase().indexOf(q) > -1;
      });
      if (searchRes) {
        searchRes.innerHTML = matched.length
          ? matched.map(function(p, i) {
              return '<div class="map-result-item" onclick="focusMarker(' + i + ')">'
                + '<span>' + (CAT_ICON[p.cat]||'📍') + '</span>'
                + '<span class="map-result-name">' + p.name + '</span></div>';
            }).join('')
          : '<div class="map-result-empty">😔 لا توجد نتائج</div>';
      }
    });
    if (searchClear) {
      searchClear.addEventListener('click', function() {
        searchInput.value = '';
        if(searchRes) searchRes.innerHTML = '';
        this.style.display = 'none';
      });
    }
    document.addEventListener('click', function(e) {
      if (searchRes && !e.target.closest('#mapSearchResults') && !e.target.closest('#mapSearchInput')) {
        searchRes.innerHTML = '';
      }
    });
  }

  // Focus on a marker
  window.focusMarker = function(idx) {
    var p = placesData[idx];
    if (!p) return;
    map.setView([p.lat, p.lng], 14);
    markers[idx].openPopup();
    if (searchRes) searchRes.innerHTML = '';
    if (searchInput) searchInput.value = p.name;
    // hide search results
  };

  // Category filter tags
  document.querySelectorAll('.map-tag').forEach(function(btn) {
    btn.addEventListener('click', function() {
      document.querySelectorAll('.map-tag').forEach(function(b){ b.classList.remove('active'); });
      this.classList.add('active');
      var cat = this.dataset.cat;
      markers.forEach(function(m, i) {
        var el = m.getElement();
        if (el) el.style.opacity = (cat === 'all' || placesData[i].cat === cat) ? '1' : '0.2';
      });
      if (cat !== 'all') {
        var filtered = placesData.filter(function(p){ return p.cat === cat; });
        if (filtered.length === 1) map.setView([filtered[0].lat, filtered[0].lng], 13);
      } else {
        var group = L.featureGroup(markers);
        map.fitBounds(group.getBounds().pad(0.2));
      }
    });
  });

  // openPlaceMap called from place cards
  window.openPlaceMap = function(lat, lng, name) {
    map.setView([lat, lng], 14);
    var idx = placesData.findIndex(function(p){ return Math.abs(p.lat-lat)<0.001 && Math.abs(p.lng-lng)<0.001; });
    if (idx >= 0) markers[idx].openPopup();
    // show modal too
    document.getElementById('placeMapTitle').textContent = name;
    document.getElementById('placeMapModal').style.display = 'flex';
    document.getElementById('singleMap').innerHTML =
      '<iframe src="https://maps.google.com/maps?q='+lat+','+lng+'&z=15&output=embed&hl=ar" width="100%" height="300" style="border:0;display:block;" allowfullscreen loading="lazy"></iframe>';
  };

  // Info bar
  var infoBar = document.getElementById('placeInfoBar');
  if (infoBar) infoBar.style.display = 'none';

});

})();
}); // end DOMContentLoaded
</script>

<!-- ── Rating Modal ── -->
<div id="rateModal" class="modal-overlay" style="display:none">
  <div class="modal-box">
    <div class="modal-header">
      <div class="modal-title">⭐ تقييم الخدمة</div>
      <button class="modal-close" onclick="document.getElementById('rateModal').style.display='none'">✕</button>
    </div>
    <div class="modal-body">
      <div id="rateModalName" style="font-weight:700;margin-bottom:12px;color:var(--dark)"></div>
      <div class="stars-input" id="starsInput">
        <span data-v="1">★</span><span data-v="2">★</span><span data-v="3">★</span>
        <span data-v="4">★</span><span data-v="5">★</span>
      </div>
      <p style="font-size:.78rem;color:var(--muted);margin-bottom:8px" id="rateHint">اختر عدد النجوم</p>
      <textarea id="rateComment" class="form-input" rows="3" placeholder="اكتب تعليقك (اختياري)..." style="margin-top:8px;width:100%;box-sizing:border-box"></textarea>
      <button class="btn-modal-submit" id="rateSubmitBtn" onclick="submitRating()">إرسال التقييم</button>
      <div id="rateMsg" style="margin-top:8px;font-size:.85rem;text-align:center"></div>
    </div>
  </div>
</div>

<!-- ── Service Request Modal ── -->
<div id="requestModal" class="modal-overlay" style="display:none">
  <div class="modal-box">
    <div class="modal-header">
      <div class="modal-title">📩 طلب خدمة</div>
      <button class="modal-close" onclick="document.getElementById('requestModal').style.display='none'">✕</button>
    </div>
    <div class="modal-body">
      <div id="requestModalName" style="font-weight:700;margin-bottom:12px;color:var(--dark)"></div>
      <textarea id="requestMessage" class="form-input" rows="4" placeholder="اكتب رسالتك إلى مقدم الخدمة..." style="width:100%;box-sizing:border-box"></textarea>
      <button class="btn-modal-submit" id="reqSubmitBtn" onclick="submitRequest()">إرسال الطلب</button>
      <div id="requestMsg" style="margin-top:8px;font-size:.85rem;text-align:center"></div>
    </div>
  </div>
</div>

<!-- ── Settings Modal ── -->
<div id="settingsModal" class="modal-overlay" style="display:none">
  <div class="modal-box">
    <div class="modal-header">
      <div class="modal-title">⚙️ الإعدادات</div>
      <button class="modal-close" onclick="document.getElementById('settingsModal').style.display='none'">✕</button>
    </div>
    <div class="modal-body">
      <div class="settings-section">
        <div class="settings-label">🌐 اللغة</div>
        <div class="settings-options">
          <a href="<?= lang_url('ar') ?>" class="settings-opt <?= $code==='ar'?'active':'' ?>">العربية</a>
          <a href="<?= lang_url('en') ?>" class="settings-opt <?= $code==='en'?'active':'' ?>">English</a>
          <a href="<?= lang_url('fr') ?>" class="settings-opt <?= $code==='fr'?'active':'' ?>">Français</a>
        </div>
      </div>
      <?php if (isset($_SESSION['user_id'])): ?>
      <div class="settings-section">
        <div class="settings-label">👤 الحساب</div>
        <a href="dashboard.php" class="settings-link">📊 لوحة التحكم</a>
        <a href="auth/logout.php" class="settings-link settings-link-danger">🚪 تسجيل الخروج</a>
      </div>
      <?php endif; ?>
      <div class="settings-section">
        <div class="settings-label">🎨 المظهر</div>
        <button class="settings-opt" id="darkToggle" onclick="toggleDark()">🌙 الوضع المظلم</button>
      </div>
    </div>
  </div>
</div>

<script>
/* ── Modals logic ── */
var currentProviderId = null;
var currentStars = 0;

function openRateModal(pid, name) {
  currentProviderId = pid; currentStars = 0;
  document.getElementById('rateModalName').textContent = name;
  document.getElementById('rateComment').value = '';
  document.getElementById('rateMsg').textContent = '';
  document.getElementById('rateHint').textContent = 'اختر عدد النجوم';
  document.querySelectorAll('#starsInput span').forEach(function(s){ s.style.color='#ccc'; });
  document.getElementById('rateModal').style.display = 'flex';
}
function openRequestModal(pid, name) {
  currentProviderId = pid;
  document.getElementById('requestModalName').textContent = name;
  document.getElementById('requestMessage').value = '';
  document.getElementById('requestMsg').textContent = '';
  document.getElementById('requestModal').style.display = 'flex';
}

/* Stars click */
document.querySelectorAll('#starsInput span').forEach(function(s) {
  s.addEventListener('click', function() {
    currentStars = parseInt(this.getAttribute('data-v'));
    document.querySelectorAll('#starsInput span').forEach(function(x,i){
      x.style.color = i < currentStars ? '#C9A84C' : '#ccc';
    });
    var labels = ['','ضعيف','مقبول','جيد','جيد جداً','ممتاز'];
    document.getElementById('rateHint').textContent = labels[currentStars];
  });
  s.addEventListener('mouseenter', function() {
    var v = parseInt(this.getAttribute('data-v'));
    document.querySelectorAll('#starsInput span').forEach(function(x,i){
      x.style.color = i < v ? '#C9A84C' : '#ccc';
    });
  });
  s.addEventListener('mouseleave', function() {
    document.querySelectorAll('#starsInput span').forEach(function(x,i){
      x.style.color = i < currentStars ? '#C9A84C' : '#ccc';
    });
  });
});

function submitRating() {
  if (!currentStars) { document.getElementById('rateMsg').textContent = '⚠️ الرجاء اختيار تقييم'; return; }
  var btn = document.getElementById('rateSubmitBtn');
  btn.disabled = true;
  btn.textContent = '⏳ جاري الإرسال...';
  var fd = new FormData();
  fd.append('provider_id', currentProviderId);
  fd.append('rating', currentStars);
  fd.append('comment', document.getElementById('rateComment').value);
  fetch('api_rate.php', {method:'POST', body:fd})
    .then(function(r){return r.json();})
    .then(function(d){
      btn.disabled = false; btn.textContent = 'إرسال التقييم';
      if (d.ok) {
        document.getElementById('rateMsg').innerHTML = '<span style="color:var(--g-main)">✅ تم إرسال تقييمك بنجاح!</span>';
        setTimeout(function(){ document.getElementById('rateModal').style.display='none'; location.reload(); }, 1500);
      } else {
        document.getElementById('rateMsg').innerHTML = '<span style="color:var(--error)">❌ ' + (d.error||'خطأ') + '</span>';
      }
    }).catch(function(){
      btn.disabled=false; btn.textContent='إرسال التقييم';
      document.getElementById('rateMsg').innerHTML='<span style="color:var(--error)">❌ خطأ في الاتصال</span>';
    });
}

function submitRequest() {
  var msg = document.getElementById('requestMessage').value.trim();
  if (!msg) { document.getElementById('requestMsg').textContent = '⚠️ الرجاء كتابة رسالة'; return; }
  var btn = document.getElementById('reqSubmitBtn');
  btn.disabled = true; btn.textContent = '⏳ جاري الإرسال...';
  var fd = new FormData();
  fd.append('provider_id', currentProviderId);
  fd.append('message', msg);
  fetch('api_request.php', {method:'POST', body:fd})
    .then(function(r){return r.json();})
    .then(function(d){
      btn.disabled=false; btn.textContent='إرسال الطلب';
      if (d.ok) {
        document.getElementById('requestMsg').innerHTML='<span style="color:var(--g-main)">✅ تم إرسال طلبك بنجاح!</span>';
        setTimeout(function(){ document.getElementById('requestModal').style.display='none'; }, 2000);
      } else {
        document.getElementById('requestMsg').innerHTML='<span style="color:var(--error)">❌ '+(d.error||'خطأ')+'</span>';
      }
    }).catch(function(){
      btn.disabled=false; btn.textContent='إرسال الطلب';
      document.getElementById('requestMsg').innerHTML='<span style="color:var(--error)">❌ خطأ في الاتصال</span>';
    });
}

/* Close modals on overlay click */
document.querySelectorAll('.modal-overlay').forEach(function(m){
  m.addEventListener('click', function(e){ if(e.target===this) this.style.display='none'; });
});

/* Settings button */
var settingsBtn = document.getElementById('navSettingsBtn');
if (settingsBtn) settingsBtn.addEventListener('click', function(){ document.getElementById('settingsModal').style.display='flex'; });

/* Dark mode toggle */
function toggleDark() {
  document.body.classList.toggle('dark-mode');
  localStorage.setItem('darkMode', document.body.classList.contains('dark-mode') ? '1' : '0');
}
if (localStorage.getItem('darkMode') === '1') document.body.classList.add('dark-mode');
</script>
