<?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 * FROM providers WHERE status='approved' 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>
      <?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">
  <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>
  </div>
</section>

<!-- ── PLACES ── -->
<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">
      <?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">
      <div id="allPlacesMap" class="places-map-full"></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" 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; ?>
      </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>
var allMap = L.map('allPlacesMap').setView([33.95, 5.92], 9);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {attribution:'© OpenStreetMap',maxZoom:18}).addTo(allMap);

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

places.forEach(function(p) {
  L.marker([p.lat, p.lng])
   .addTo(allMap)
   .bindPopup('<strong style="font-family:Cairo,sans-serif">'+p.name+'</strong>');
});

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();
  }, 100);
}
document.getElementById('placeMapModal').addEventListener('click', function(e) {
  if (e.target === this) this.style.display = 'none';
});
</script>
<?php endif; ?>

</body>
</html>
