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

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

$first_name = explode(' ', $__name)[0];

// Homepage shows a short preview of partner restaurants — the full,
// searchable list lives on restaurants.php
// Partner restaurants ordered by the user's most recent visit/order first
// (so the places they use most appear at the top), then alphabetically for
// any they haven't ordered from yet.
$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
     LIMIT 5"
);
$rests_q->bind_param("i", $uid);
$rests_q->execute();
$restaurants = $rests_q->get_result()->fetch_all(MYSQLI_ASSOC);
?>

<style>
/* ═══════════════════════════════════════════════════════════════════════
   DASHBOARD — FULLY RESPONSIVE
   Base styles (mobile-first) → tablets → desktop
   ═══════════════════════════════════════════════════════════════════════ */

/* ── 0. Global resets for this page ─────────────────────────────── */
* { -webkit-tap-highlight-color: transparent; }
.main-content { overflow-x: hidden; }

/* ── 1. Welcome header ────────────────────────────────────────────── */
.dash-welcome {
  margin-bottom: clamp(16px, 4vw, 24px);
}
.dash-welcome p {
  font-size: clamp(.78rem, 2.5vw, .88rem);
  color: var(--text-muted);
  margin-bottom: 4px;
}
.dash-welcome h1 {
  font-size: clamp(1.4rem, 6vw, 1.75rem);
  font-weight: 800;
  letter-spacing: -.04em;
  line-height: 1.1;
}
.subtitle-dots {
  display: flex;
  gap: clamp(10px, 3vw, 16px);
  margin-top: 8px;
  flex-wrap: wrap;
}
.subtitle-dots span {
  font-size: clamp(.7rem, 2vw, .78rem);
  color: var(--text-muted);
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 5px;
  white-space: nowrap;
}
.subtitle-dots span::before {
  content: '';
  width: 7px; height: 7px;
  border-radius: 50%;
  background: var(--primary);
  flex-shrink: 0;
}
.subtitle-dots span:nth-child(2)::before { background: #10B981; }
.subtitle-dots span:nth-child(3)::before { background: #F59E0B; }

/* ── Wallet card, search bar, category pills, and partner restaurant
   list styles now live in includes/header.php so they're shared with
   restaurants.php and wallet.php ───────────────────────────────────── */

/* ── 3. Quick Actions ─────────────────────────────────────────────── */
.qa-section-title {
  font-size: clamp(.92rem, 3vw, 1.05rem);
  font-weight: 800;
  letter-spacing: -.02em;
  margin-bottom: clamp(10px, 3vw, 14px);
}
.quick-actions-bar {
  display: flex;
  gap: clamp(6px, 2.5vw, 12px);
  margin-bottom: clamp(18px, 5vw, 24px);
}
.qa-pill {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: clamp(6px, 2vw, 9px);
  padding: clamp(10px, 3vw, 16px) clamp(4px, 1.5vw, 10px);
  background: #fff;
  border: 1.5px solid var(--border);
  border-radius: clamp(12px, 3vw, 16px);
  text-decoration: none;
  color: var(--text);
  transition: border-color .2s, box-shadow .2s;
  cursor: pointer;
  touch-action: manipulation;
  min-height: 80px; /* guaranteed touch-friendly height */
}
.qa-pill:hover {
  border-color: var(--primary);
  box-shadow: 0 4px 16px rgba(34,90,227,.12);
}
/* Touch devices: replace hover with active */
@media (hover: none) {
  .qa-pill:hover { border-color: var(--border); box-shadow: none; }
  .qa-pill:active { border-color: var(--primary); transform: scale(0.96); background: var(--primary-bg); }
}
.qa-pill .qa-icon-wrap {
  width: clamp(38px, 11vw, 46px);
  height: clamp(38px, 11vw, 46px);
  border-radius: clamp(10px, 3vw, 13px);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}
.qa-pill .qa-label {
  font-size: clamp(.68rem, 2vw, .78rem);
  font-weight: 700;
  text-align: center;
  line-height: 1.2;
  white-space: nowrap;
}

/* ── Fine-grain breakpoints ───────────────────────────────────────── */

/* Tablet portrait */
@media (min-width: 481px) and (max-width: 767px) {
  .quick-actions-bar { gap: 10px; }
  .qa-pill { padding: 14px 10px; }
}

/* Large phones (480px and down) */
@media (max-width: 480px) {
  .quick-actions-bar { gap: 8px; }
  .qa-pill { border-radius: 14px; }
}

/* iPhone SE / small Android (375px) */
@media (max-width: 375px) {
  .quick-actions-bar { gap: 7px; }
  .qa-pill {
    padding: 10px 3px;
    border-radius: 12px;
  }
  .qa-pill svg { width: 18px !important; height: 18px !important; }
}

/* Very small phones (320px — old Galaxy S / iPhone 5) */
@media (max-width: 320px) {
  .quick-actions-bar { gap: 5px; }
  .qa-pill { padding: 9px 2px; border-radius: 10px; min-height: 70px; }
  .qa-pill .qa-icon-wrap { width: 34px !important; height: 34px !important; border-radius: 9px !important; }
}

/* ── Landscape on small phones ────────────────────────────────────── */
@media (max-height: 480px) and (orientation: landscape) {
  .dash-welcome { margin-bottom: 12px; }
  .quick-actions-bar { margin-bottom: 14px; }
}

/* ── Live animated gradient on the wallet card (dashboard only) ─────── */
.wallet-card {
  background: linear-gradient(120deg, #1d4ccb 0%, #225AE3 26%, #3d76f0 50%, #1a47b8 76%, #225AE3 100%);
  background-size: 280% 280%;
  animation: walletGradient 9s ease-in-out infinite;
}
@keyframes walletGradient {
  0%   { background-position: 0% 50%; }
  50%  { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
}
@media (prefers-reduced-motion: reduce) { .wallet-card { animation: none; } }

/* ── Partner restaurant: useful detail line (replaces "Accepts Dabil") ─ */
.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>

<!-- ── Welcome Header ──────────────────────────────────────────────────── -->
<div class="dash-welcome">
  <p>Welcome back</p>
  <h1><?php echo htmlspecialchars($first_name); ?></h1>
  <div class="subtitle-dots">
    <span>Cashless</span>
    <span>Cardless</span>
    <span>Seamless</span>
  </div>
</div>

<!-- ── Wallet Balance Card ─────────────────────────────────────────────── -->
<div class="wallet-card">
  <div class="wc-label">
    <span>Wallet balance</span>
    <button class="eye-btn" onclick="toggleBalance()" title="Show/hide balance">
      <svg id="eyeIcon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
        <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
        <circle cx="12" cy="12" r="3"/>
      </svg>
    </button>
  </div>
  <div class="wc-amount" id="walletBalance">
    ₦<?php echo number_format($__balance, 2); ?>
  </div>
  <a href="fund_wallet.php" class="wc-fund-btn">
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
      <circle cx="12" cy="12" r="10"/><path d="M12 8v8M8 12h8"/>
    </svg>
    Fund Wallet
  </a>
</div>

<!-- ── Quick Actions ───────────────────────────────────────────────────── -->
<h2 class="qa-section-title">Quick Actions</h2>
<div class="quick-actions-bar">
  <a href="scan.php" class="qa-pill">
    <div class="qa-icon-wrap">
      <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="var(--primary)" stroke-width="2" stroke-linecap="round">
        <path d="M3 7V5a2 2 0 012-2h2M17 3h2a2 2 0 012 2v2M21 17v2a2 2 0 01-2 2h-2M7 21H5a2 2 0 01-2-2v-2"/>
        <rect x="7" y="7" width="10" height="10" rx="1"/>
      </svg>
    </div>
    <span class="qa-label">Scan QR</span>
  </a>
  <a href="orders.php" class="qa-pill">
    <div class="qa-icon-wrap">
      <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#10B981" stroke-width="2" stroke-linecap="round">
        <path d="M6 2L4 6v14a2 2 0 002 2h12a2 2 0 002-2V6l-2-4"/>
        <path d="M4 6h16"/>
        <path d="M9 10a3 3 0 006 0"/>
      </svg>
    </div>
    <span class="qa-label">Orders</span>
  </a>
  <a href="restaurants.php" class="qa-pill">
    <div class="qa-icon-wrap">
      <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#9333EA" stroke-width="2" stroke-linecap="round">
        <path d="M17 8h1a4 4 0 010 8h-1"/>
        <path d="M3 8h14v9a4 4 0 01-4 4H7a4 4 0 01-4-4V8z"/>
        <line x1="6" y1="1" x2="6" y2="4"/>
        <line x1="10" y1="1" x2="10" y2="4"/>
        <line x1="14" y1="1" x2="14" y2="4"/>
      </svg>
    </div>
    <span class="qa-label">Restaurants</span>
  </a>
</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">
</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>

<!-- ── Partner Restaurants ─────────────────────────────────────────────── -->
<div class="rest-list-header" id="partner-restaurants">
  <h2>Partner Restaurants</h2>
  <a href="restaurants.php">View All</a>
</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; ?>

<?php if ($__balance == 0): ?>
<div class="alert alert-info" style="margin-top:26px;margin-bottom:18px">
  <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" style="flex-shrink:0;width:16px;height:16px">
    <circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/>
  </svg>
  <span style="font-size:clamp(.78rem,2.5vw,.88rem)">Your wallet is empty.
    <a href="fund_wallet.php" style="color:var(--primary);font-weight:700;margin-left:4px">Fund it now →</a>
  </span>
</div>
<?php endif; ?>

<script>
// ── Balance toggle (persisted across pages/tabs via localStorage) ───────
const _realBal = '₦<?php echo number_format($__balance, 2); ?>';
const _EYE_OPEN = '<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/>';
const _EYE_OFF  = '<path d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19m-6.72-1.07a3 3 0 11-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/>';
function _balHidden() { try { return localStorage.getItem('dabil_bal_hidden') === '1'; } catch (e) { return false; } }
function _applyBalance(hidden) {
  const amt = document.getElementById('walletBalance'); const ic = document.getElementById('eyeIcon');
  if (amt) amt.textContent = hidden ? '₦ ••••••' : _realBal;
  if (ic)  ic.innerHTML = hidden ? _EYE_OFF : _EYE_OPEN;
}
function toggleBalance() {
  const hidden = !_balHidden();
  try { localStorage.setItem('dabil_bal_hidden', hidden ? '1' : '0'); } catch (e) {}
  _applyBalance(hidden);
}
_applyBalance(_balHidden());

// ── Restaurant search + category filter ────────────────────────────────
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';
}

// ── Smooth scroll for anchor links on iOS ─────────────────────────────
document.querySelectorAll('a[href^="#"]').forEach(a => {
  a.addEventListener('click', function(e) {
    const target = document.querySelector(this.getAttribute('href'));
    if (target) {
      e.preventDefault();
      target.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  });
});
</script>

<?php
// Thank-you modal after submitting Dabil feedback with no attached order (?fb=dabil)
include("includes/feedback_thanks.php");
?>

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