<?php
require __DIR__.'/config.php';

$id = (int)($_GET['id'] ?? 0);

// Produit
$res = $mysqli->query("SELECT * FROM produits WHERE id = {$id} LIMIT 1");
if (!$res || $res->num_rows === 0) {
  http_response_code(404);
  die("Produit introuvable");
}
$p = $res->fetch_assoc();

// Prix multiples
$prices = [];
$qr = $mysqli->query("SELECT label, price FROM product_prices WHERE product_id={$id} ORDER BY price ASC");
if ($qr) { while ($row = $qr->fetch_assoc()) $prices[] = $row; }

// Bot cible
$targetUser = $ORDER_BOT_USERNAME ?: $CONTACT_BOT_USERNAME;
$base_link = tg_user_url($targetUser) . "?start=order_".$p['id'];

// Médias
$medias = [];
$mres = $mysqli->query("SELECT file FROM product_media WHERE product_id={$p['id']} ORDER BY id ASC");
if ($mres) { while ($row = $mres->fetch_assoc()) $medias[] = $row['file']; }
if (!$medias && !empty($p['image'])) {
  $medias[] = $p['image'];
}

$channelUrl = $CHANNEL_URL ?: 'https://t.me/';
$contactUrl = tg_user_url($CONTACT_BOT_USERNAME ?: '');
$instagramUrl = $INSTAGRAM_URL ?: '';

function media_path(string $file): string {
  $file = trim($file);
  if ($file === '') return 'assets/placeholder.svg';
  if (str_starts_with($file, 'uploads/')) return $file;
  if (str_contains($file, '/')) return $file; // already a path
  return 'uploads/' . $file;
}
?>
<!doctype html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
  <meta name="color-scheme" content="dark light">
  <meta name="theme-color" content="#0f1115">
  <meta name="app-placeholder" content="assets/placeholder.svg">
  <title><?= h($p['nom']) ?> – <?= h($APP_NAME) ?></title>
  <link rel="stylesheet" href="<?= asset('assets/app.min.css') ?>">
  <script defer src="<?= asset('assets/app.min.js') ?>"></script>
</head>
<body>

<header class="appbar">
  <div class="appbar-row">
    <div class="brand">
      <img class="brand-logo" src="logo.png" alt="<?= h($APP_NAME) ?>">
      <div>
        <div class="brand-title"><?= h($APP_NAME) ?></div>
        <div class="brand-sub">Détail produit</div>
      </div>
    </div>
    <button class="icon-btn" type="button" data-sheet-open="sheetInfos" aria-label="Infos">ℹ️</button>
  </div>
  <div class="hero" aria-hidden="true"></div>
</header>

<main class="page">
  <a class="back" href="index.php">← Retour au menu</a>

  <section class="detail">
    <?php if (!empty($medias)): ?>
      <div class="slider" data-slider>
        <div class="slides" data-slides>
          <?php foreach ($medias as $f):
            $path = media_path((string)$f);
            $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
            $isVid = in_array($ext, ['mp4','webm','ogg','mov','m4v'], true);
          ?>
            <?php if ($isVid): ?>
              <video src="<?= h($path) ?>" playsinline muted controls preload="metadata"></video>
            <?php else: ?>
              <img src="<?= h($path) ?>" alt="" decoding="async" loading="lazy" data-fallback>
            <?php endif; ?>
          <?php endforeach; ?>
        </div>

        <?php if (count($medias) > 1): ?>
          <button class="slider-btn prev" type="button" data-prev aria-label="Précédent">❮</button>
          <button class="slider-btn next" type="button" data-next aria-label="Suivant">❯</button>
        <?php endif; ?>
      </div>
      <?php if (count($medias) > 1): ?>
        <div class="dots" data-dots aria-label="Navigation images"></div>
      <?php endif; ?>
    <?php endif; ?>

    <h1><?= h($p['nom']) ?></h1>

    <?php if (!empty($prices)): ?>
      <div class="chips" data-prices>
        <?php foreach ($prices as $i => $pr): ?>
          <button
            type="button"
            class="chip<?= $i===0 ? ' active' : '' ?>"
            data-label="<?= h($pr['label']) ?>"
            data-price="<?= number_format((float)$pr['price'], 2, '.', '') ?>"
          >
            <?= h($pr['label']) ?> — <b><?= number_format((float)$pr['price'], 2, '.', ' ') ?> €</b>
          </button>
        <?php endforeach; ?>
      </div>

      <div class="brand-sub" data-picked style="margin:0 0 12px"></div>

      <a
        class="cta"
        href="<?= h($base_link) ?>"
        data-order-btn
        data-base="<?= h($base_link) ?>"
        target="_blank"
        rel="noopener"
        data-tg-link
      >
        ✈️ Commander via Telegram
      </a>
    <?php else: ?>
      <?php if (!empty($p['prix'])): ?>
        <div class="brand-sub" style="margin:8px 0 12px">
          Prix : <b><?= number_format((float)$p['prix'], 2, '.', ' ') ?> €</b>
        </div>
      <?php endif; ?>
      <a class="cta" href="<?= h($base_link) ?>" target="_blank" rel="noopener" data-tg-link>
        ✈️ Commander via Telegram
      </a>
    <?php endif; ?>

    <?php if (!empty($p['description'])): ?>
      <p class="desc"><?= nl2br(h($p['description'])) ?></p>
    <?php endif; ?>
  </section>
</main>

<nav class="tabs" aria-label="Navigation">
  <a class="tab" href="index.php"><div class="icon">🏠</div><span>Menu</span></a>
  <a class="tab" href="#" data-sheet-open="sheetCats"><div class="icon">🗂️</div><span>Catégories</span></a>
  <a class="tab" href="<?= h($channelUrl) ?>" target="_blank" rel="noopener" data-tg-link><div class="icon">📢</div><span>Canal</span></a>
  <a class="tab" href="<?= h($contactUrl) ?>" target="_blank" rel="noopener" data-tg-link><div class="icon">✉️</div><span>Contact</span></a>
</nav>

<!-- Sheet: Infos -->
<div id="sheetInfos" class="sheet" role="dialog" aria-modal="true" aria-label="Infos">
  <div class="scrim" data-sheet-scrim="sheetInfos"></div>
  <div class="panel">
    <button class="close" type="button" data-sheet-close="sheetInfos">Fermer ✖</button>
    <h3>ℹ️ Informations</h3>

    <div class="sheet-links">
      <a href="<?= h($channelUrl) ?>" target="_blank" rel="noopener" data-tg-link>
        <span>📢 Canal Telegram</span><span aria-hidden="true">↗</span>
      </a>
      <?php if ($instagramUrl): ?>
        <a href="<?= h($instagramUrl) ?>" target="_blank" rel="noopener" data-tg-link>
          <span>🔗 Instagram</span><span aria-hidden="true">↗</span>
        </a>
      <?php endif; ?>
      <a href="<?= h($contactUrl) ?>" target="_blank" rel="noopener" data-tg-link>
        <span>✉️ Contact</span><span aria-hidden="true">↗</span>
      </a>
    </div>
  </div>
</div>

<!-- Sheet: Catégories (simple: renvoie au menu) -->
<div id="sheetCats" class="sheet" role="dialog" aria-modal="true" aria-label="Catégories">
  <div class="scrim" data-sheet-scrim="sheetCats"></div>
  <div class="panel">
    <button class="close" type="button" data-sheet-close="sheetCats">Fermer ✖</button>
    <h3>🗂️ Catégories</h3>
    <p>Choisis une catégorie depuis le menu.</p>
    <div class="sheet-links">
      <a href="index.php"><span>Aller au menu</span><span aria-hidden="true">›</span></a>
    </div>
  </div>
</div>

</body>
</html>
