<?php
session_start();
$page_title = 'Restaurants';
$active_nav = 'restaurants';
include("includes/header.php");

$uid = (int)$_SESSION['user_id'];

// Full partner restaurant list — no limit (the homepage only shows a short
// preview). Same ordering as the homepage: the user's most recently
// visited/ordered restaurants first, then the rest alphabetically.
$rests_q = $conn->prepare(
    "SELECT r.id, r.name, r.address, r.logo, r.description,
            COUNT(DISTINCT m.id) AS menu_count,
            MAX(o.created_at)    AS last_used
     FROM restaurants r
     LEFT JOIN menu_items m ON m.restaurant_id = r.id AND m.is_available = 1
     LEFT JOIN orders o ON o.restaurant_id = r.id AND o.user_id = ?
     WHERE r.status = 1
     GROUP BY r.id
     ORDER BY (MAX(o.created_at) IS NULL), MAX(o.created_at) DESC, r.name ASC"
);
$rests_q->bind_param("i", $uid);
$rests_q->execute();
$restaurants = $rests_q->get_result()->fetch_all(MYSQLI_ASSOC);
?>

<style>
  /* Menu-count line — identical treatment to the homepage partner cards */
  .rest-list-item .rest-menu { display: flex; align-items: center; gap: 5px; font-size: clamp(.68rem, 2vw, .75rem); color: var(--primary); font-weight: 700; }
  .rest-list-item .rest-menu svg { stroke: currentColor; fill: none; flex-shrink: 0; }
  .rest-list-item .rest-menu.muted { color: var(--text-light); }
</style>

<div style="margin-bottom:clamp(16px,4vw,24px)">
  <h1 style="font-size:clamp(1.4rem,6vw,1.75rem);font-weight:800;letter-spacing:-.04em;margin-bottom:4px">Restaurants</h1>
  <p style="color:var(--text-muted);font-size:clamp(.78rem,2.5vw,.88rem)">Browse every restaurant that accepts Dabil</p>
</div>

<!-- ── Search ─────────────────────────────────────────────────────────── -->
<div class="search-wrap">
  <span class="search-icon">
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
      <circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/>
    </svg>
  </span>
  <input type="text"
         id="restSearch"
         placeholder="Search restaurants..."
         oninput="filterRestaurants()"
         autocomplete="off"
         autocorrect="off"
         autocapitalize="off"
         spellcheck="false">
  <button class="filter-btn" title="Filter" type="button">
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
      <line x1="4" y1="6" x2="20" y2="6"/>
      <line x1="8" y1="12" x2="16" y2="12"/>
      <line x1="11" y1="18" x2="13" y2="18"/>
    </svg>
  </button>
</div>

<!-- Category pills -->
<div class="cat-pills">
  <button class="cat-pill active" onclick="setCat(this,'all')" type="button">All</button>
  <button class="cat-pill" onclick="setCat(this,'fine dining')" type="button">Fine Dining</button>
  <button class="cat-pill" onclick="setCat(this,'local')" type="button">Local spot</button>
  <button class="cat-pill" onclick="setCat(this,'affordable')" type="button">Affordable</button>
  <button class="cat-pill" onclick="setCat(this,'quick service')" type="button">Quick Service</button>
</div>

<!-- ── Full Restaurant List ──────────────────────────────────────────── -->
<div class="rest-list-header">
  <h2>All Partner Restaurants</h2>
  <span style="font-size:clamp(.72rem,2.2vw,.8rem);color:var(--text-muted);font-weight:600"><?php echo count($restaurants); ?> total</span>
</div>

<?php if (empty($restaurants)): ?>
<div class="rest-empty">
  <svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="var(--border)" stroke-width="1.5" stroke-linecap="round" style="margin:0 auto 12px;display:block">
    <path d="M3 11l19-9-9 19-2-8-8-2z"/>
  </svg>
  <p style="font-weight:700;margin-bottom:4px">No restaurants yet</p>
  <p style="font-size:.8rem">Check back soon — partners are being added</p>
</div>
<?php else: ?>
<div id="restList">
  <?php foreach ($restaurants as $r):
    $logo_path = $r['logo'] ? '../restaurantadmin/uploads/logos/' . $r['logo'] : null;
    $has_logo  = $logo_path && file_exists(dirname(__FILE__) . '/' . $logo_path);
    $initials  = strtoupper(substr($r['name'], 0, 2));
    $cuisine   = !empty($r['description']) ? $r['description'] : 'Restaurant';
    $meta      = $cuisine . (!empty($r['address']) ? ' · ' . htmlspecialchars($r['address']) : '');
    $data_str  = strtolower($r['name'] . ' ' . $r['description'] . ' ' . $r['address']);
    $mc        = (int)($r['menu_count'] ?? 0);
  ?>
  <a href="scan.php?rid=<?php echo $r['id']; ?>"
     class="rest-list-item"
     data-search="<?php echo htmlspecialchars($data_str); ?>">
    <div class="rest-logo">
      <?php if ($has_logo): ?>
        <img src="<?php echo htmlspecialchars($logo_path); ?>" alt="">
      <?php else: ?>
        <?php echo $initials; ?>
      <?php endif; ?>
    </div>
    <div class="rest-info">
      <div class="rest-name"><?php echo htmlspecialchars($r['name']); ?></div>
      <div class="rest-meta"><?php echo $meta; ?></div>
      <?php if ($mc > 0): ?>
      <div class="rest-menu">
        <svg width="12" height="12" viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 2v7c0 1.1.9 2 2 2h2a2 2 0 002-2V2"/><path d="M7 2v20"/><path d="M21 15V2a5 5 0 00-5 5v6c0 1.1.9 2 2 2h3Zm0 0v7"/></svg>
        <?php echo $mc; ?> dish<?php echo $mc === 1 ? '' : 'es'; ?> on the menu
      </div>
      <?php else: ?>
      <div class="rest-menu muted">
        <svg width="12" height="12" viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 8v4l3 2"/></svg>
        New on Dabil
      </div>
      <?php endif; ?>
    </div>
    <div class="rest-chevron">
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
        <polyline points="9 18 15 12 9 6"/>
      </svg>
    </div>
  </a>
  <?php endforeach; ?>
</div>
<div id="restNoResults" style="display:none;padding:26px;text-align:center;color:var(--text-muted);font-size:.86rem;font-weight:600;background:#fff;border:1.5px solid var(--border);border-radius:14px">
  No restaurants match your search.
</div>
<?php endif; ?>

<script>
let _activeCat = 'all';

function setCat(btn, cat) {
  document.querySelectorAll('.cat-pill').forEach(p => p.classList.remove('active'));
  btn.classList.add('active');
  _activeCat = cat;
  filterRestaurants();
}

function filterRestaurants() {
  const q = (document.getElementById('restSearch').value || '').toLowerCase().trim();
  const items = document.querySelectorAll('#restList .rest-list-item');
  let shown = 0;
  items.forEach(item => {
    const data = (item.getAttribute('data-search') || '').toLowerCase();
    const okSearch = !q || data.includes(q);
    const okCat    = _activeCat === 'all' || data.includes(_activeCat);
    const show = okSearch && okCat;
    item.style.display = show ? 'flex' : 'none';
    if (show) shown++;
  });
  const nr = document.getElementById('restNoResults');
  if (nr) nr.style.display = shown === 0 ? 'block' : 'none';
}
</script>

<?php include("includes/footer.php"); ?>
