<?php
// pages/leiloes.php — Listagem de Leilões

$leiloes_ativos = $conn->query(
    "SELECT * FROM auction_list WHERE status = 2 ORDER BY featured DESC, id DESC"
);
$leiloes_breve = $conn->query(
    "SELECT * FROM auction_list WHERE status = 1 ORDER BY id DESC LIMIT 6"
);
$leiloes_encerrados = $conn->query(
    "SELECT a.*, c.firstname as winner_name FROM auction_list a
     LEFT JOIN customer_list c ON a.winner_id = c.id
     WHERE a.status = 3 ORDER BY id DESC LIMIT 8"
);

// Créditos do usuário logado
$user_credits = 0;
if ($_settings->userdata('id')) {
    $cr = $conn->query("SELECT credits FROM bid_credits WHERE customer_id = "
                        . (int)$_settings->userdata('id'));
    $user_credits = (int)($cr->fetch_assoc()['credits'] ?? 0);
}
?>

<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap');

.leiloes-wrap { font-family:'Inter',sans-serif; }

/* ── Hero ─────────────────────────────── */
.auctions-hero {
  background: linear-gradient(135deg,#1a1a2e 0%,#16213e 50%,#0f3460 100%);
  border-radius: 20px; padding: 2rem; color: #fff; margin-bottom: 1.5rem;
  position: relative; overflow: hidden;
}
.auctions-hero::before {
  content:''; position:absolute; top:-50%; right:-10%;
  width:300px; height:300px; border-radius:50%;
  background:radial-gradient(circle,rgba(108,92,231,.3) 0%,transparent 70%);
}
.hero-live-badge {
  background:#e74c3c; border-radius:50px; padding:4px 14px;
  font-size:.7rem; font-weight:800; letter-spacing:1.5px;
  animation: blink 1.5s infinite; display:inline-block; margin-bottom:.75rem;
}
@keyframes blink { 0%,100%{opacity:1} 50%{opacity:.5} }

/* ── Cards de leilão ─────────────────── */
.auction-card {
  border-radius: 18px; border: none; overflow: hidden;
  box-shadow: 0 6px 24px rgba(0,0,0,.08);
  transition: all .3s ease; cursor: pointer; background: #fff;
}
.auction-card:hover {
  transform: translateY(-6px);
  box-shadow: 0 16px 40px rgba(108,92,231,.2);
}
.auction-img-wrap { position:relative; height: 200px; overflow:hidden; }
.auction-img-wrap img { width:100%; height:100%; object-fit:cover; transition:.3s; }
.auction-card:hover .auction-img-wrap img { transform: scale(1.06); }

/* ── Badge Ao Vivo ───────────────────── */
.badge-live {
  position:absolute; top:12px; left:12px;
  background:#e74c3c; color:#fff; border-radius:50px;
  font-size:.65rem; font-weight:800; padding:4px 12px; letter-spacing:1px;
  animation: blink 1.5s infinite;
}
.badge-phase { position:absolute; top:12px; right:12px; border-radius:50px;
               font-size:.65rem; font-weight:700; padding:4px 12px; }
.badge-fase1 { background:rgba(108,92,231,.9); color:#fff; }
.badge-fase2 { background:rgba(231,76,60,.9); color:#fff; }
.badge-soon  { position:absolute; top:12px; left:12px;
               background:rgba(0,0,0,.6); color:#fff; border-radius:50px;
               font-size:.65rem; font-weight:700; padding:4px 12px; }

/* ── Detalhes do card ────────────────── */
.auction-info { padding: 1.2rem; }
.auction-price-big { font-size:1.5rem; font-weight:800; color:#6c5ce7; }
.auction-real-val  { text-decoration:line-through; color:#aaa; font-size:.85rem; }
.timer-badge {
  background:#fff3; backdrop-filter:blur(4px);
  border:1px solid rgba(255,255,255,.3); border-radius:50px;
  font-family:monospace; font-weight:800; font-size:1rem;
  padding:4px 14px; color:#ffd700;
}
.bids-counter { color:#636e72; font-size:.82rem; }

/* ── CTA Comprar créditos ────────────── */
.credits-cta {
  background:linear-gradient(135deg,#ffeaa7,#fdcb6e);
  border-radius:18px; padding:1.5rem; color:#2d3436;
}

/* ── Encerrados ──────────────────────── */
.winner-card {
  border-radius:14px; background:#fff; border:none;
  box-shadow:0 2px 12px rgba(0,0,0,.06);
  padding:1rem;
}
.winner-trophy { font-size:2rem; }

/* ── Aba de seções ──────────────────── */
.section-tabs .nav-link { border-radius:50px !important; font-weight:600; }
.section-tabs .nav-link.active { background:#6c5ce7 !important; color:#fff !important; border:none; }
.section-tabs .nav-link:not(.active) { color:#6c5ce7; border:1px solid #6c5ce7; }
</style>

<div class="container app-main leiloes-wrap pb-5">

  <!-- ── Hero ─────────────────────────────────────────── -->
  <div class="auctions-hero mb-4">
    <div class="hero-live-badge">🔴 AO VIVO</div>
    <h1 class="fw-black mb-1" style="font-size:1.9rem">🎯 Leilão de Centavos</h1>
    <p class="opacity-75 mb-3">Cada lance aumenta R$0,01 e reinicia o timer. Último a dar lance VENCE!</p>
    <div class="d-flex align-items-center gap-3 flex-wrap">
      <div class="d-flex align-items-center gap-2">
        <div style="background:rgba(255,255,255,.15);border-radius:12px;padding:.5rem 1rem">
          <div class="small opacity-75">⚡ Seus Créditos</div>
          <div class="fw-bold fs-5"><?= $user_credits ?></div>
        </div>
        <?php if ($user_credits < 5): ?>
        <a href="/creditos" class="btn btn-warning rounded-pill fw-bold">
          + Comprar Créditos
        </a>
        <?php endif; ?>
      </div>
      <a href="/creditos" class="btn btn-outline-light rounded-pill btn-sm">
        Como funciona?
      </a>
    </div>
  </div>

  <!-- ── Abas ─────────────────────────────────────────── -->
  <ul class="nav section-tabs gap-2 mb-4">
    <li class="nav-item">
      <a class="nav-link active" href="#ativos" data-bs-toggle="tab">🔥 Em andamento</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#breve" data-bs-toggle="tab">📅 Em breve</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#encerrados" data-bs-toggle="tab">🏆 Encerrados</a>
    </li>
  </ul>

  <div class="tab-content">

    <!-- ── Leilões Ativos ────────────────────────────── -->
    <div class="tab-pane fade show active" id="ativos">
      <?php if ($leiloes_ativos->num_rows === 0): ?>
        <div class="text-center text-muted py-5">
          <div style="font-size:3.5rem">🎯</div>
          <h5>Nenhum leilão ativo no momento</h5>
          <p class="small">Fique de olho! Novos leilões em breve.</p>
        </div>
      <?php else: ?>
      <div class="row g-3">
        <?php while ($a = $leiloes_ativos->fetch_assoc()):
          $elapsed = $a['timer_reset_at'] ? time() - strtotime($a['timer_reset_at']) : 0;
          $secs    = ($a['phase'] == 2) ? max(0, (int)$a['timer_seconds'] - $elapsed)
                                        : (int)$a['timer_seconds'];
        ?>
        <div class="col-12 col-md-6">
          <a href="/leilao/<?= $a['slug'] ?>" class="text-decoration-none">
            <div class="auction-card">
              <div class="auction-img-wrap">
                <?php if ($a['image_path']): ?>
                  <img src="<?= validate_image($a['image_path']) ?>" alt="<?= htmlspecialchars($a['name']) ?>">
                <?php else: ?>
                  <div style="height:200px;background:linear-gradient(135deg,#6c5ce7,#a29bfe);display:flex;align-items:center;justify-content:center;font-size:4rem">🎁</div>
                <?php endif; ?>
                <span class="badge-live">🔴 AO VIVO</span>
                <span class="badge-phase <?= $a['phase']==2 ? 'badge-fase2' : 'badge-fase1' ?>">
                  <?= $a['phase']==2 ? '🔥 Fase Real' : '🎭 Fase Crescimento' ?>
                </span>
              </div>
              <div class="auction-info">
                <h5 class="fw-bold mb-1"><?= htmlspecialchars($a['name']) ?></h5>
                <div class="d-flex align-items-end justify-content-between mb-2">
                  <div>
                    <div class="auction-real-val">Valor real: R$ <?= number_format($a['real_value'],2,',','.') ?></div>
                    <div class="auction-price-big" id="price-<?= $a['id'] ?>">
                      R$ <?= number_format($a['current_price'],2,',','.') ?>
                    </div>
                  </div>
                  <div class="text-end">
                    <div class="timer-badge" id="timer-<?= $a['id'] ?>"
                         data-seconds="<?= $secs ?>"
                         data-phase="<?= $a['phase'] ?>"
                         data-auction="<?= $a['id'] ?>">
                      <?= str_pad(floor($secs/60),2,'0',STR_PAD_LEFT) ?>:<?= str_pad($secs%60,2,'0',STR_PAD_LEFT) ?>
                    </div>
                  </div>
                </div>
                <div class="d-flex justify-content-between align-items-center">
                  <span class="bids-counter">⚡ <?= number_format($a['total_bids']) ?> lances</span>
                  <span class="btn btn-sm rounded-pill fw-bold"
                        style="background:#6c5ce7;color:#fff;font-size:.8rem">
                    Participar →
                  </span>
                </div>
              </div>
            </div>
          </a>
        </div>
        <?php endwhile; ?>
      </div>
      <?php endif; ?>
    </div>

    <!-- ── Em Breve ──────────────────────────────────── -->
    <div class="tab-pane fade" id="breve">
      <?php if ($leiloes_breve->num_rows === 0): ?>
        <p class="text-muted text-center py-5">Nenhum leilão programado ainda.</p>
      <?php else: ?>
      <div class="row g-3">
        <?php while ($a = $leiloes_breve->fetch_assoc()): ?>
        <div class="col-12 col-md-6">
          <div class="auction-card" style="opacity:.85">
            <div class="auction-img-wrap">
              <?php if ($a['image_path']): ?>
                <img src="<?= validate_image($a['image_path']) ?>" alt="<?= htmlspecialchars($a['name']) ?>">
              <?php else: ?>
                <div style="height:200px;background:linear-gradient(135deg,#636e72,#2d3436);display:flex;align-items:center;justify-content:center;font-size:4rem">🔐</div>
              <?php endif; ?>
              <span class="badge-soon">📅 Em Breve</span>
            </div>
            <div class="auction-info">
              <h5 class="fw-bold mb-1"><?= htmlspecialchars($a['name']) ?></h5>
              <div class="auction-real-val">Valor real: R$ <?= number_format($a['real_value'],2,',','.') ?></div>
              <small class="text-muted">Preço inicial: R$ <?= number_format($a['start_price'],2,',','.') ?></small>
            </div>
          </div>
        </div>
        <?php endwhile; ?>
      </div>
      <?php endif; ?>
    </div>

    <!-- ── Encerrados / Vencedores ───────────────────── -->
    <div class="tab-pane fade" id="encerrados">
    <?php if ($leiloes_encerrados->num_rows === 0): ?>
      <p class="text-muted text-center py-5">Nenhum leilão encerrado ainda.</p>
    <?php else: ?>
      <div class="row g-3">
        <?php while ($a = $leiloes_encerrados->fetch_assoc()): ?>
        <div class="col-12 col-md-6">
          <div class="winner-card d-flex align-items-center gap-3">
            <?php if ($a['image_path']): ?>
              <img src="<?= validate_image($a['image_path']) ?>"
                   style="width:70px;height:70px;border-radius:12px;object-fit:cover" alt="">
            <?php else: ?>
              <div class="winner-trophy">🏆</div>
            <?php endif; ?>
            <div style="flex:1">
              <div class="fw-bold"><?= htmlspecialchars($a['name']) ?></div>
              <div class="small text-muted">
                Valor real: R$ <?= number_format($a['real_value'],2,',','.') ?>
                → Vendido por: <strong class="text-success">R$ <?= number_format($a['current_price'],2,',','.') ?></strong>
              </div>
              <div class="small mt-1">
                🏆 Vencedor: <strong><?= $a['winner_name'] ? $a['winner_name'][0].'***' : 'Anônimo' ?></strong>
                · <?= number_format($a['total_bids']) ?> lances
              </div>
            </div>
          </div>
        </div>
        <?php endwhile; ?>
      </div>
    <?php endif; ?>
    </div>

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

  <!-- ── CTA Créditos ──────────────────────────────────── -->
  <div class="credits-cta mt-4">
    <div class="row align-items-center">
      <div class="col">
        <h5 class="fw-bold mb-1">⚡ Precisa de mais créditos de lance?</h5>
        <p class="mb-0 small">Pacotes a partir de R$ 4,90 — Lance quanto quiser!</p>
      </div>
      <div class="col-auto">
        <a href="/creditos" class="btn fw-bold rounded-pill"
           style="background:#2d3436;color:#fff">Comprar Créditos →</a>
      </div>
    </div>
  </div>

</div><!-- /container -->

<script>
// ── Timers nos cards de listagem ──────────────────────────
document.querySelectorAll('.timer-badge').forEach(el => {
  let secs  = parseInt(el.dataset.seconds);
  let phase = parseInt(el.dataset.phase);
  const auctionId = el.dataset.auction;
  const priceEl   = document.getElementById('price-' + auctionId);

  setInterval(() => {
    if (phase === 2 && secs > 0) {
      secs--;
      const m = String(Math.floor(secs/60)).padStart(2,'0');
      const s = String(secs%60).padStart(2,'0');
      el.textContent = m + ':' + s;
      if (secs <= 10) el.style.color = '#e74c3c';
    } else if (phase === 1) {
      el.textContent = el.dataset.seconds + 's ∞';
    }
  }, 1000);

  // Polling a cada 8s para atualizar preços
  setInterval(() => {
    fetch('/classes/Auction.php?f=get_status&id=' + auctionId)
      .then(r => r.json())
      .then(d => {
        if (d.current_price && priceEl)
          priceEl.textContent = 'R$ ' + d.current_price;
        if (typeof d.seconds_left !== 'undefined') secs = d.seconds_left;
        if (d.phase) phase = d.phase;
      });
  }, 8000);
});
</script>
