<?php
require_once 'db.php';

// Datos
$familias   = $pdo->query("SELECT * FROM familias   WHERE activo=1 ORDER BY orden,id")->fetchAll();
$subfamilias= $pdo->query("SELECT * FROM subfamilias WHERE activo=1 ORDER BY orden,id")->fetchAll();
$platos     = $pdo->query("SELECT * FROM platos      WHERE activo=1 ORDER BY orden,id")->fetchAll();
$alergenos  = get_alergenos();
$nombre_rest= cfg($pdo,'nombre_restaurante','Mi Restaurante');
$header_text= cfg($pdo,'header_text','');
$footer_text= cfg($pdo,'footer_text','');
$footer_logo= cfg($pdo,'footer_logo','');
$banners    = json_decode(cfg($pdo,'banner_images','[]'), true) ?: [];
$promos     = json_decode(cfg($pdo,'promo_images','[]'), true) ?: [];

// Agrupar subfamilias y platos por familia
$subs_by_fam = [];
foreach ($subfamilias as $s) $subs_by_fam[$s['familia_id']][] = $s;

$platos_by_sub = [];
foreach ($platos as $p) {
    if ($p['subfamilia_id']) $platos_by_sub[$p['subfamilia_id']][] = $p;
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Carta digital de <?= htmlspecialchars($nombre_rest) ?>">
<title><?= htmlspecialchars($nombre_rest) ?> – Carta</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap">
<link rel="stylesheet" href="assets/css/menu.css">
</head>
<body>

<?php if (!empty($banners)): ?>
<!-- ─── Banner Carousel ───────────────────────────────────── -->
<div class="banner-wrap" id="banner">
  <div class="banner-track" id="bannerTrack">
    <?php foreach ($banners as $b): ?>
      <img src="<?= htmlspecialchars($b) ?>" alt="Banner <?= htmlspecialchars($nombre_rest) ?>">
    <?php endforeach; ?>
  </div>
  <?php if (count($banners) > 1): ?>
  <button class="banner-btn prev" onclick="moveBanner(-1)" aria-label="Anterior">&#8249;</button>
  <button class="banner-btn next" onclick="moveBanner(1)"  aria-label="Siguiente">&#8250;</button>
  <div class="banner-dots" id="bannerDots">
    <?php foreach ($banners as $i => $_): ?>
      <button class="banner-dot <?= $i===0?'active':'' ?>" onclick="goBanner(<?= $i ?>)" aria-label="Ir a imagen <?= $i+1 ?>"></button>
    <?php endforeach; ?>
  </div>
  <?php endif; ?>
</div>
<?php endif; ?>

<?php if ($header_text): ?>
<div class="header-text"><?= $header_text ?></div>
<?php endif; ?>

<?php if (!empty($promos)): ?>
<div class="content" style="padding-top:0; padding-bottom:1rem">
  <div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(140px, 1fr)); gap:1rem;">
    <?php foreach ($promos as $pimg): ?>
      <img src="<?= htmlspecialchars($pimg) ?>" style="width:100%; border-radius:var(--radius); box-shadow:var(--shadow); aspect-ratio:3/2; object-fit:cover;">
    <?php endforeach; ?>
  </div>
</div>
<?php endif; ?>

<!-- ─── Tabs familias ─────────────────────────────────────── -->
<div class="tabs-bar">
  <div class="tabs-inner" id="tabsInner">
    <button class="tab-btn active" data-fam="all" onclick="selectFam('all',this)">🍽️ Todo</button>
    <?php foreach ($familias as $f): ?>
    <button class="tab-btn" data-fam="<?= $f['id'] ?>" onclick="selectFam(<?= $f['id'] ?>,this)">
      <?= $f['icono'] ?> <?= htmlspecialchars($f['nombre']) ?>
    </button>
    <?php endforeach; ?>
  </div>
</div>

<!-- ─── Subfamilia pills ──────────────────────────────────── -->
<div class="subtabs-bar" id="subtabsBar" style="display:none">
  <div class="subtabs-inner" id="subtabsInner"></div>
</div>

<!-- ─── Contenido ────────────────────────────────────────── -->
<div class="content">
  <?php foreach ($familias as $f):
    $fsubs = $subs_by_fam[$f['id']] ?? [];
    // Comprobamos si hay platos en esta familia
    $hasDishes = false;
    foreach ($fsubs as $s) { if (!empty($platos_by_sub[$s['id']])) { $hasDishes = true; break; } }
    if (!$hasDishes) continue;
  ?>
  <section class="family-section" data-fam="<?= $f['id'] ?>" style="display:block">

    <?php if ($f['imagen']): ?>
    <img src="<?= htmlspecialchars($f['imagen']) ?>" class="family-img" alt="<?= htmlspecialchars($f['nombre']) ?>">
    <?php else: ?>
    <h2 class="family-title"><?= $f['icono'] ?> <?= htmlspecialchars($f['nombre']) ?></h2>
    <?php endif; ?>
    <?php if (!empty($f['descripcion'])): ?>
    <div class="family-desc ql-content" style="color:var(--muted); margin-top:.5rem; margin-bottom:1rem; font-size:.95rem; line-height:1.5;"><?= $f['descripcion'] ?></div>
    <?php endif; ?>

    <?php foreach ($fsubs as $s):
      $dish_list = $platos_by_sub[$s['id']] ?? [];
      if (empty($dish_list)) continue;
    ?>
    <div class="subfam-block" data-sub="<?= $s['id'] ?>">
      <?php if (!empty($s['imagen'])): ?>
      <img src="<?= strpos($s['imagen'], 'http') === 0 ? htmlspecialchars($s['imagen']) : htmlspecialchars($s['imagen']) ?>" class="family-img" alt="<?= htmlspecialchars($s['nombre']) ?>" style="max-height: 140px;">
      <?php endif; ?>
      <h3 class="sub-title"><?= $s['icono'] ?> <?= htmlspecialchars($s['nombre']) ?></h3>
      <?php if (!empty($s['descripcion'])): ?>
      <div class="sub-desc ql-content" style="color:var(--text); opacity:0.8; margin-bottom:1rem; font-size:.9rem; line-height:1.4;"><?= $s['descripcion'] ?></div>
      <?php endif; ?>
      <div class="dish-grid">
        <?php foreach ($dish_list as $p):
          $als = json_decode($p['alergenos'] ?? '[]', true) ?: [];
        ?>
        <article class="dish-card">
          <?php if ($p['imagen']): ?>
          <div class="dish-photo"><img src="<?= htmlspecialchars($p['imagen']) ?>" alt="<?= htmlspecialchars($p['nombre']) ?>" loading="lazy"></div>
          <?php endif; ?>
          <div class="dish-body">
            <div class="dish-row">
              <span class="dish-name"><?= htmlspecialchars($p['nombre']) ?></span>
              <span class="dish-price"><?= number_format($p['precio'],2,',','.') ?>&nbsp;€</span>
            </div>
            <?php if ($p['descripcion']): ?>
            <div class="dish-desc ql-content"><?= $p['descripcion'] ?></div>
            <?php endif; ?>
            <?php if (!empty($als)): ?>
            <div class="dish-allergens">
              <?php foreach ($als as $aid): if (!isset($alergenos[$aid])) continue; $al=$alergenos[$aid]; ?>
              <span class="al-tag" title="<?= htmlspecialchars($al['label']) ?>"><?= $al['emoji'] ?></span>
              <?php endforeach; ?>
            </div>
            <?php endif; ?>
          </div>
        </article>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endforeach; ?>
  </section>
  <?php endforeach; ?>

  <div style="text-align:center; padding:2rem 1rem 1rem; color:var(--muted); font-size:.9rem; font-weight:600; text-transform:uppercase; letter-spacing:.05em;">
    10% IVA INCLUIDO
    <div style="margin-top:.5rem; font-size:.8rem; font-weight:400; opacity:.8;">MUCHAS GRACIAS POR SU VISITA</div>
  </div>

  <!-- ─── Leyenda alérgenos ─────────────────────────────── -->
  <div class="legend-wrap">
    <details class="legend-details">
      <summary class="legend-summary">ℹ️ &nbsp;Información de alérgenos – Reglamento UE 1169/2011</summary>
      <div class="legend-grid">
        <?php foreach ($alergenos as $al): ?>
        <div class="legend-item"><?= $al['emoji'] ?> <?= htmlspecialchars($al['label']) ?></div>
        <?php endforeach; ?>
      </div>
    </details>
  </div>
  <!-- ─── Google Maps ────────────────────────────────────── -->
  <?php 
  $gmaps = cfg($pdo, 'google_maps', '');
  if ($gmaps): ?>
  <div class="maps-wrap">
    <?= $gmaps ?>
  </div>
  <?php endif; ?>

</div><!-- /content -->

<!-- ─── Footer ───────────────────────────────────────────── -->
<footer>
<?php 
  $footer_logo_link = cfg($pdo, 'footer_logo_link', '');
  $footer_extra = cfg($pdo, 'footer_extra', '');
  $f_logo_html = '<img src="'.htmlspecialchars($footer_logo).'" alt="Logo" style="height:60px;margin-bottom:1rem;border-radius:8px">';
  
  echo '<div class="footer-logos">';
  if ($footer_logo) {
    if ($footer_logo_link) echo '<a href="'.htmlspecialchars($footer_logo_link).'" target="_blank">'.$f_logo_html.'</a>';
    else echo $f_logo_html;
  }
  if ($footer_extra) echo '<div class="ql-content">'.$footer_extra.'</div>';
  echo '</div>';
?>
  <?= $footer_text ?>
  <p class="footer-copy">Carta digital · <?= htmlspecialchars($nombre_rest) ?></p>
</footer>

<script>
// Subfamilias JSON para filtrado por JS
const SF = <?= json_encode(array_values($subfamilias)) ?>;
let curFam = 'all', curSub = null;

function selectFam(fam, btn) {
  curFam = fam; curSub = null;
  document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
  btn.classList.add('active');

  document.querySelectorAll('.family-section').forEach(s => {
    s.style.display = (fam === 'all' || s.dataset.fam == fam) ? 'block' : 'none';
  });
  document.querySelectorAll('.subfam-block').forEach(b => b.style.display = 'block');

  const bar = document.getElementById('subtabsBar');
  const inner = document.getElementById('subtabsInner');
  if (fam === 'all') { bar.style.display = 'none'; return; }

  const subs = SF.filter(s => s.familia_id == fam);
  if (!subs.length) { bar.style.display = 'none'; return; }

  bar.style.display = 'block';
  inner.innerHTML = `<button class="sub-btn active" onclick="selectSub('all',this)">Todos</button>` +
    subs.map(s=>`<button class="sub-btn" onclick="selectSub(${s.id},this)">${s.nombre}</button>`).join('');
}

function selectSub(sub, btn) {
  curSub = sub;
  document.querySelectorAll('.sub-btn').forEach(b=>b.classList.remove('active'));
  btn.classList.add('active');
  document.querySelectorAll('.subfam-block').forEach(b => {
    b.style.display = (sub === 'all' || b.dataset.sub == sub) ? 'block' : 'none';
  });
}

// Banner
let bIdx = 0;
const track = document.getElementById('bannerTrack');
const dots  = document.querySelectorAll('.banner-dot');
function goBanner(n) {
  bIdx = n;
  if (track) track.style.transform = `translateX(-${bIdx*100}%)`;
  dots.forEach((d,i)=>d.classList.toggle('active',i===bIdx));
}
function moveBanner(dir) {
  const total = <?= count($banners) ?>;
  goBanner((bIdx + dir + total) % total);
}
<?php if (count($banners) > 1): ?>
setInterval(() => moveBanner(1), 5000);
<?php endif; ?>

// Back to top
window.addEventListener('scroll', () => {
  const btnTop = document.getElementById('btnTop');
  if (btnTop) {
    if (window.scrollY > 400) btnTop.classList.add('show');
    else btnTop.classList.remove('show');
  }
});
function scrollToTop() {
  window.scrollTo({ top: 0, behavior: 'smooth' });
}

// Drag to scroll for category bars
function enableDragScroll(selector) {
  const el = document.querySelector(selector);
  if (!el) return;
  let isDown = false, startX, scrollLeft;
  el.addEventListener('mousedown', (e) => {
    isDown = true; el.classList.add('grabbing');
    startX = e.pageX - el.offsetLeft;
    scrollLeft = el.scrollLeft;
  });
  el.addEventListener('mouseleave', () => { isDown = false; el.classList.remove('grabbing'); });
  el.addEventListener('mouseup', () => { isDown = false; el.classList.remove('grabbing'); });
  el.addEventListener('mousemove', (e) => {
    if (!isDown) return;
    e.preventDefault();
    const x = e.pageX - el.offsetLeft;
    const walk = (x - startX) * 2;
    el.scrollLeft = scrollLeft - walk;
  });
}
enableDragScroll('.tabs-inner');
// Also enable for subtabs after they are generated
const observer = new MutationObserver(() => enableDragScroll('.subtabs-inner'));
observer.observe(document.getElementById('subtabsInner'), { childList: true });
</script>
<button id="btnTop" class="btn-top" onclick="scrollToTop()">↑</button>
</body>
</html>
