<?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">
</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 class="reveal" 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="allPlacesMap" class="places-map-full-new"></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="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script src="js/main.js"></script>
<?php if ($places): ?>
<script>
// Wait for DOM + CSS to fully paint before init
window.addEventListener('load', function() {

var allMap = L.map('allPlacesMap', {
  zoomControl: false,
  scrollWheelZoom: false
}).setView([33.95, 5.92], 9);

L.control.zoom({ position: 'bottomleft' }).addTo(allMap);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
  maxZoom: 18,
  crossOrigin: true
}).addTo(allMap);

// Force correct size after render
setTimeout(function() { allMap.invalidateSize(true); }, 300);
setTimeout(function() { allMap.setView([33.95, 5.92], 9); allMap.invalidateSize(true); }, 700);

var catColors = {
  lake:'#3b9fd4', oasis:'#52B788', desert:'#C9A84C',
  heritage:'#a07060', nature:'#40916c', monument:'#7c6f8f', other:'#888'
};

function makeIcon(cat) {
  var icons = {lake:'💧',oasis:'🌴',desert:'🏜️',heritage:'🏛️',nature:'🌿',monument:'🗿',other:'📍'};
  var color = catColors[cat] || '#52B788';
  var emoji = icons[cat] || '📍';
  var svg = '<svg xmlns="http://www.w3.org/2000/svg" width="36" height="44" viewBox="0 0 36 44">'
    + '<path d="M18 0C8.06 0 0 8.06 0 18c0 12 18 26 18 26S36 30 36 18C36 8.06 27.94 0 18 0z" fill="' + color + '" opacity=".9"/>'
    + '<circle cx="18" cy="18" r="12" fill="white" opacity=".85"/>'
    + '<text x="18" y="23" text-anchor="middle" font-size="13">' + emoji + '</text>'
    + '</svg>';
  return L.divIcon({
    html: svg,
    className: '',
    iconSize: [36, 44],
    iconAnchor: [18, 44],
    popupAnchor: [0, -44]
  });
}

var places = <?= json_encode(array_map(fn($p) => [
  'lat'  => (float)$p['lat'],
  'lng'  => (float)$p['lng'],
  'name' => $p[$name_col] ?: $p['name_ar'],
  'cat'  => $p['category']
], $places)) ?>;

var mapMarkers = [];
places.forEach(function(p) {
  var popup = '<div style="font-family:Cairo,sans-serif;direction:rtl;text-align:right;min-width:120px">'
    + '<strong style="font-size:.95rem;color:#1a3a2a">' + p.name + '</strong><br>'
    + '<span style="font-size:.75rem;color:#666;margin-top:2px;display:block">📍 ' + p.cat + '</span>'
    + '</div>';
  var m = L.marker([p.lat, p.lng], { icon: makeIcon(p.cat) })
            .addTo(allMap)
            .bindPopup(popup, { maxWidth: 220 });
  m._placeName = p.name;
  m._placeCat  = p.cat;
  m._placeData = p;
  mapMarkers.push(m);
});

/* ── Search ── */
var searchInput   = document.getElementById('mapSearchInput');
var searchClear   = document.getElementById('mapSearchClear');
var searchResults = document.getElementById('mapSearchResults');
var activeTag     = 'all';

function filterMap(q, cat) {
  q = (q || '').trim().toLowerCase();
  searchResults.innerHTML = '';
  searchClear.style.display = q ? 'flex' : 'none';

  var matched = [];
  mapMarkers.forEach(function(m) {
    var nameMatch = !q || m._placeName.toLowerCase().includes(q);
    var catMatch  = cat === 'all' || m._placeCat === cat;
    var show = nameMatch && catMatch;
    if (show) { m.addTo(allMap); matched.push(m); }
    else { allMap.removeLayer(m); }
  });

  if (q) {
    matched.forEach(function(m) {
      var item = document.createElement('div');
      item.className = 'map-result-item';
      item.innerHTML = '<span class="map-result-icon">' + (
        {lake:'💧',oasis:'🌴',desert:'🏜️',heritage:'🏛️',nature:'🌿',monument:'🗿',other:'📍'}[m._placeCat]||'📍'
      ) + '</span><span class="map-result-name">' + m._placeData.name + '</span>'
        + '<svg class="map-result-arrow" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>';
      item.addEventListener('click', function() {
        allMap.flyTo([m._placeData.lat, m._placeData.lng], 14, {animate:true, duration:0.9});
        setTimeout(function(){ m.openPopup(); }, 900);
        searchResults.innerHTML = '';
        searchInput.value = m._placeData.name;
        searchClear.style.display = 'flex';
      });
      searchResults.appendChild(item);
    });
    if (matched.length === 0) {
      searchResults.innerHTML = '<div class="map-result-empty"><span>😔</span> لم يتم العثور على نتائج</div>';
    }
  }

  // Fit bounds if filtering
  if (matched.length > 1 && !q) {
    var group = L.featureGroup(matched);
    allMap.fitBounds(group.getBounds().pad(0.2));
  } else if (matched.length > 0 && !q) {
    allMap.setView([matched[0]._placeData.lat, matched[0]._placeData.lng], 13);
  } else if (!q && cat === 'all') {
    allMap.setView([33.95, 5.92], 9);
  }
}

searchInput.addEventListener('input', function() { filterMap(this.value, activeTag); });
searchInput.addEventListener('keydown', function(e) {
  if (e.key === 'Escape') { this.value = ''; filterMap('', activeTag); }
});
searchClear.addEventListener('click', function() {
  searchInput.value = ''; filterMap('', activeTag); searchInput.focus();
});
document.addEventListener('click', function(e) {
  if (!e.target.closest('#mapSearchResults') && !e.target.closest('#mapSearchInput')) {
    searchResults.innerHTML = '';
  }
});

/* ── Category 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');
    activeTag = this.getAttribute('data-cat');
    filterMap(searchInput.value, activeTag);
  });
});

}); // end window.load

/* ── Single place map modal ── */
var singleMap = null, singleMarker = null;
function openPlaceMap(lat, lng, name) {
  document.getElementById('placeMapTitle').textContent = name;
  document.getElementById('placeMapModal').style.display = 'flex';
  setTimeout(function() {
    if (!singleMap) {
      singleMap = L.map('singleMap').setView([lat, lng], 14);
      L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {attribution:'© OpenStreetMap'}).addTo(singleMap);
      singleMarker = L.marker([lat, lng]).addTo(singleMap).bindPopup(name).openPopup();
    } else {
      singleMap.setView([lat, lng], 14);
      singleMarker.setLatLng([lat, lng]).setPopupContent(name).openPopup();
    }
    singleMap.invalidateSize(true);
  }, 200);
}
document.getElementById('placeMapModal').addEventListener('click', function(e) {
  if (e.target === this) this.style.display = 'none';
});
</script>
<?php endif; ?>

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