<?php
// admin/auctions/index.php — Painel Admin de Leilões
require_once '../../settings.php';
if (!$_settings->userdata('type') || $_settings->userdata('type') != 1) {
    header('Location: /admin'); exit();
}

$msg = '';
if (isset($_GET['msg'])) $msg = htmlspecialchars($_GET['msg']);

// Excluir
if ($_POST['action'] ?? '' === 'delete' && !empty($_POST['id'])) {
    $conn->query("UPDATE auction_list SET status=3 WHERE id=" . (int)$_POST['id']);
    $msg = "Leilão encerrado.";
}

// Ativar/Pause toggle
if (!empty($_POST['toggle_id'])) {
    $tid = (int)$_POST['toggle_id'];
    $cur = $conn->query("SELECT status FROM auction_list WHERE id=$tid")->fetch_assoc();
    $new_status = $cur['status'] == 2 ? 1 : 2;
    if ($new_status == 2) {
        // Inicia o timer
        $conn->query("UPDATE auction_list SET status=2, timer_reset_at=NOW() WHERE id=$tid");
    } else {
        $conn->query("UPDATE auction_list SET status=1 WHERE id=$tid");
    }
    header("Location: ?msg=Status+atualizado!"); exit();
}

// Stats rápidos
$stats = $conn->query("SELECT
    COUNT(CASE WHEN status=2 THEN 1 END) as ativos,
    COUNT(CASE WHEN status=1 THEN 1 END) as breve,
    COUNT(CASE WHEN status=3 THEN 1 END) as encerrados,
    COALESCE(SUM(total_bids),0) as total_bids,
    COALESCE(SUM(total_revenue),0) as total_revenue
    FROM auction_list")->fetch_assoc();

$auctions = $conn->query("SELECT a.*, c.firstname as last_bidder_name
                           FROM auction_list a
                           LEFT JOIN customer_list c ON a.last_bidder_id = c.id
                           ORDER BY a.status ASC, a.featured DESC, a.id DESC");
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Leilões — Admin</title>
<link rel="stylesheet" href="/admin/assets/css/bootstrap/bootstrap.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
<style>
body { background:#f4f6fb; font-family:'Inter',sans-serif; }
.admin-card { border-radius:14px; border:none; box-shadow:0 2px 12px rgba(0,0,0,.06); }
.stat-card  { border-radius:12px; border:none; color:#fff; padding:1.2rem; }
.auction-thumb { width:54px; height:54px; border-radius:10px; object-fit:cover; }
.phase-1 { background:rgba(108,92,231,.1); color:#6c5ce7; border-radius:50px; font-size:.7rem; font-weight:700; padding:3px 10px; }
.phase-2 { background:rgba(231,76,60,.1); color:#e74c3c; border-radius:50px; font-size:.7rem; font-weight:700; padding:3px 10px; animation:blink 1.5s infinite; }
@keyframes blink { 0%,100%{opacity:1} 50%{opacity:.5} }
.badge-s1 { background:rgba(255,165,0,.12); color:#e67e22; }
.badge-s2 { background:rgba(0,200,100,.12);  color:#00b894; }
.badge-s3 { background:rgba(220,50,50,.12);  color:#d63031; }
</style>
</head>
<body>
<div class="container-fluid py-4 px-4">

  <!-- Cabeçalho -->
  <div class="d-flex align-items-center justify-content-between mb-4">
    <div>
      <h4 class="fw-bold mb-0">🎯 Gestão de Leilões</h4>
      <small class="text-muted">Criar, ativar e monitorar leilões de centavos</small>
    </div>
    <div class="d-flex gap-2">
      <a href="bids.php" class="btn btn-outline-secondary btn-sm rounded-3">⚡ Todos os Lances</a>
      <a href="create.php" class="btn btn-primary btn-sm rounded-3 fw-bold">+ Novo Leilão</a>
    </div>
  </div>

  <?php if ($msg): ?>
    <div class="alert alert-info rounded-3 mb-3"><?= $msg ?></div>
  <?php endif; ?>

  <!-- Estatísticas -->
  <div class="row g-3 mb-4">
    <div class="col-6 col-md-3">
      <div class="stat-card" style="background:linear-gradient(135deg,#e74c3c,#c0392b)">
        <div class="small opacity-85">🔴 Ativos</div>
        <div class="fs-3 fw-bold"><?= $stats['ativos'] ?></div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="stat-card" style="background:linear-gradient(135deg,#f39c12,#e67e22)">
        <div class="small opacity-85">📅 Em Breve</div>
        <div class="fs-3 fw-bold"><?= $stats['breve'] ?></div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="stat-card" style="background:linear-gradient(135deg,#6c5ce7,#a29bfe)">
        <div class="small opacity-85">⚡ Total de Lances</div>
        <div class="fs-3 fw-bold"><?= number_format($stats['total_bids']) ?></div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="stat-card" style="background:linear-gradient(135deg,#00b09b,#96c93d)">
        <div class="small opacity-85">💰 Receita Total</div>
        <div class="fs-3 fw-bold">R$ <?= number_format($stats['total_revenue'],2,',','.') ?></div>
      </div>
    </div>
  </div>

  <!-- Tabela de Leilões -->
  <div class="admin-card">
    <div class="card-body p-0">
      <?php if ($auctions->num_rows === 0): ?>
        <div class="text-center text-muted py-5">
          <div style="font-size:3rem">🎯</div>
          <p>Nenhum leilão criado ainda. <a href="create.php">Criar primeiro leilão</a></p>
        </div>
      <?php else: ?>
      <div class="table-responsive">
        <table class="table align-middle mb-0">
          <thead class="table-light">
            <tr>
              <th class="ps-4">Produto</th>
              <th>Fase</th>
              <th>Preço Atual</th>
              <th>Lances</th>
              <th>Receita</th>
              <th>Último Lance</th>
              <th>Status</th>
              <th class="pe-4">Ações</th>
            </tr>
          </thead>
          <tbody>
          <?php while ($a = $auctions->fetch_assoc()):
            $slabel = ['1'=>'Em Breve','2'=>'Ativo','3'=>'Encerrado'][$a['status']] ?? '-';
            $badgeC = 'badge-s'.$a['status'];
          ?>
          <tr>
            <td class="ps-4">
              <div class="d-flex align-items-center gap-3">
                <?php if ($a['image_path']): ?>
                  <img src="<?= validate_image($a['image_path']) ?>" class="auction-thumb" alt="">
                <?php else: ?>
                  <div class="auction-thumb d-flex align-items-center justify-content-center"
                       style="background:linear-gradient(135deg,#6c5ce7,#a29bfe);font-size:1.5rem">🎁</div>
                <?php endif; ?>
                <div>
                  <div class="fw-semibold"><?= htmlspecialchars($a['name']) ?></div>
                  <small class="text-muted">Valor real: R$ <?= number_format($a['real_value'],2,',','.') ?></small>
                  <?php if ($a['featured']): ?><span class="ms-1 badge bg-warning text-dark">⭐ Destaque</span><?php endif; ?>
                </div>
              </div>
            </td>
            <td>
              <span class="phase-<?= $a['phase'] ?>">
                <?= $a['phase']==2 ? '🔥 Real':'🎭 Crescimento' ?>
              </span>
              <?php if ($a['phase2_trigger']): ?>
                <div class="text-muted" style="font-size:.72rem">
                  Trigger: R$ <?= number_format($a['phase2_trigger'],2,',','.') ?>
                </div>
              <?php endif; ?>
            </td>
            <td class="fw-bold text-primary">R$ <?= number_format($a['current_price'],2,',','.') ?></td>
            <td><?= number_format($a['total_bids']) ?></td>
            <td class="fw-bold text-success">R$ <?= number_format($a['total_revenue'],2,',','.') ?></td>
            <td>
              <?php if ($a['last_bidder_name']): ?>
                <div class="small fw-semibold"><?= $a['last_bidder_name'][0].'***' ?></div>
                <?php if ($a['timer_reset_at']): ?>
                  <div class="text-muted" style="font-size:.72rem">
                    <?= date('H:i:s', strtotime($a['timer_reset_at'])) ?>
                  </div>
                <?php endif; ?>
              <?php else: ?>
                <span class="text-muted">—</span>
              <?php endif; ?>
            </td>
            <td><span class="badge rounded-pill px-3 py-2 small fw-semibold <?= $badgeC ?>"><?= $slabel ?></span></td>
            <td class="pe-4">
              <div class="d-flex gap-1 flex-wrap">
                <a href="create.php?id=<?= $a['id'] ?>" class="btn btn-sm btn-outline-primary rounded-3">✏️</a>
                <a href="bids.php?auction_id=<?= $a['id'] ?>" class="btn btn-sm btn-outline-secondary rounded-3">⚡</a>
                <?php if ($a['status'] != 3): ?>
                <form method="POST" class="m-0">
                  <input type="hidden" name="toggle_id" value="<?= $a['id'] ?>">
                  <button class="btn btn-sm <?= $a['status']==2 ? 'btn-warning':'btn-success' ?> rounded-3">
                    <?= $a['status']==2 ? '⏸':'▶️' ?>
                  </button>
                </form>
                <?php endif; ?>
                <a href="/leilao/<?= $a['slug'] ?>" target="_blank"
                   class="btn btn-sm btn-outline-dark rounded-3">👁</a>
              </div>
            </td>
          </tr>
          <?php endwhile; ?>
          </tbody>
        </table>
      </div>
      <?php endif; ?>
    </div>
  </div>

</div>
<script src="/admin/assets/js/bootstrap.bundle.min.js"></script>
</body>
</html>
