<?php
if ($_settings->userdata('id') == '') {
    echo '<script>location.replace(\'/\');</script>'; exit();
}
$customer_id   = (int) $_settings->userdata('id');
$customer_name = trim($_settings->userdata('firstname') . ' ' . $_settings->userdata('lastname'));

require_once BASE_APP . 'includes/wallet-functions.php';

$wallet = wallet_get($customer_id);

// ─── Dados da Rede / MLM ────────────────────────────────
$binary = $conn->query("SELECT * FROM binary_tree WHERE customer_id = $customer_id")->fetch_assoc();
$ref_link = BASE_URL . 'cadastrar?ref=' . ($conn->query("SELECT referral_code FROM referral WHERE customer_id = $customer_id")->fetch_assoc()['referral_code'] ?? $customer_id);

// ─── Investimento Ativo ─────────────────────────────────
$active_inv = $conn->query("SELECT i.*, p.name as plan_name, p.color, p.icon
                             FROM investments i
                             JOIN investment_plans p ON i.plan_id = p.id
                             WHERE i.customer_id = $customer_id AND i.status = 1
                             ORDER BY i.created_at DESC LIMIT 1")->fetch_assoc();

// ─── Créditos de lance ──────────────────────────────────
$bid_cred = $conn->query("SELECT credits FROM bid_credits WHERE customer_id = $customer_id")->fetch_assoc();
$bid_credits = (int) ($bid_cred['credits'] ?? 0);

// ─── Leilão ao vivo ─────────────────────────────────────
$live_auction = $conn->query("SELECT * FROM auction_list WHERE status = 2 ORDER BY featured DESC, id DESC LIMIT 1")->fetch_assoc();

// ─── Últimas transações ─────────────────────────────────
$transactions = $conn->query("SELECT * FROM wallet_transactions WHERE customer_id = $customer_id
                               ORDER BY created_at DESC LIMIT 6");

// ─── Ganhos da rede ─────────────────────────────────────
$binary_earned   = (float)($binary['total_binary_earned'] ?? 0);
$unilevel_earned = (float)($conn->query("SELECT COALESCE(SUM(commission_amount),0) as total
                                          FROM unilevel_commissions WHERE beneficiary_id = $customer_id")->fetch_assoc()['total'] ?? 0);

// ─── Ícones e labels para transações ───────────────────
$tx_icons = [
    'deposit'         => ['💰', 'Depósito', 'text-success'],
    'yield'           => ['📈', 'Rendimento', 'text-success'],
    'binary_bonus'    => ['🌐', 'Bônus Binário', 'text-success'],
    'unilevel_bonus'  => ['🔗', 'Comissão', 'text-success'],
    'auction_prize'   => ['🏆', 'Prêmio Leilão', 'text-warning'],
    'raffle_prize'    => ['🎟', 'Prêmio Rifa', 'text-warning'],
    'investment'      => ['💎', 'Investimento', 'text-danger'],
    'bid_cost'        => ['⚡', 'Lance', 'text-danger'],
    'withdrawal'      => ['💵', 'Saque', 'text-danger'],
    'upgrade'         => ['🚀', 'Upgrade', 'text-danger'],
    'adjustment'      => ['⚙️', 'Ajuste', 'text-muted'],
];

// ─── Timer do leilão ────────────────────────────────────
$seconds_left = 0;
if ($live_auction && $live_auction['timer_reset_at']) {
    $elapsed = time() - strtotime($live_auction['timer_reset_at']);
    $seconds_left = max(0, $live_auction['timer_seconds'] - $elapsed);
    if ($live_auction['phase'] == 1) $seconds_left = $live_auction['timer_seconds']; // Fase fake: sempre cheio
}
?>

<style>
/* ── Tokens de cor ───────────────────────────────────── */
:root {
  --p1: #6c5ce7; --p2: #a29bfe;
  --g1: #00b09b; --g2: #96c93d;
  --o1: #fd79a8; --o2: #e17055;
}

/* ── Cards principais ────────────────────────────────── */
.dash-card    { border-radius: 18px; border: none;
                box-shadow: 0 4px 24px rgba(0,0,0,.07); }
.wallet-card  { background: linear-gradient(135deg, var(--p1), var(--p2)); color: #fff; }
.invest-card  { background: linear-gradient(135deg, var(--g1), var(--g2)); color: #fff; }
.network-card { background: linear-gradient(135deg, #2d3436, #636e72); color: #fff; }

/* ── Saldo em destaque ───────────────────────────────── */
.big-balance  { font-size: 2.2rem; font-weight: 800; letter-spacing: -1px; }

/* ── Barra de progresso do invest. ──────────────────── */
.invest-bar   { height: 10px; border-radius: 50px;
                background: rgba(255,255,255,.25); overflow: hidden; }
.invest-bar-fill { height: 100%; border-radius: 50px;
                   background: #fff; transition: width .6s ease; }

/* ── Leilão ao vivo ──────────────────────────────────── */
.auction-live { background: linear-gradient(135deg, #2d3436 0%, #1a1a2e 100%);
                border-radius: 18px; color: #fff; position: relative; overflow: hidden; }
.auction-live::before { content:'🔴 AO VIVO';
  position: absolute; top: 12px; right: 12px;
  background: #e74c3c; border-radius: 50px; padding: 3px 10px;
  font-size: .65rem; font-weight: 800; letter-spacing: 1px; animation: blink 1.5s infinite; }
@keyframes blink { 0%,100%{opacity:1} 50%{opacity:.4} }

.auction-price { font-size: 1.9rem; font-weight: 800; color: #ffd700; }
.timer-display { font-size: 1.4rem; font-weight: 800; color: #00cec9; font-family: monospace; }

/* ── Botões de ação rápida ───────────────────────────── */
.quick-btn    { border-radius: 14px !important; font-weight: 700; padding: .8rem !important;
                border: none; transition: all .2s; }
.quick-btn:hover { transform: translateY(-3px); box-shadow: 0 8px 20px rgba(0,0,0,.15); }
.qb-deposit   { background: linear-gradient(135deg, var(--p1), var(--p2)); color: #fff; }
.qb-withdraw  { background: linear-gradient(135deg, var(--g1), var(--g2)); color: #fff; }
.qb-invest    { background: linear-gradient(135deg, #ffeaa7, #fdcb6e); color: #2d3436; }
.qb-invite    { background: linear-gradient(135deg, var(--o1), var(--o2)); color: #fff; }

/* ── Transações ─────────────────────────────────────── */
.tx-row       { border-radius: 10px; transition: .15s; }
.tx-row:hover { background: #f8f7ff; }
.tx-icon      { width: 38px; height: 38px; border-radius: 50%; display: flex;
                align-items: center; justify-content: center;
                background: #f0eeff; font-size: 1.1rem; flex-shrink: 0; }

/* ── Rede binária mini ───────────────────────────────── */
.net-bar      { height: 8px; border-radius: 50px; background: rgba(255,255,255,.2); overflow: hidden; }
.net-bar-fill { height: 100%; border-radius: 50px; }
</style>

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

  <!-- ══ Saudação ════════════════════════════════════════ -->
  <div class="app-title mb-3">
    <h1>👋 Olá, <?= htmlspecialchars($_settings->userdata('firstname')) ?>!</h1>
    <div class="app-title-desc" style="color:#424b58">Sua central de controle</div>
  </div>

  <!-- ══ Carteira Central ════════════════════════════════ -->
  <div class="dash-card wallet-card p-4 mb-3">
    <div class="small opacity-75 mb-1">💼 Saldo Disponível</div>
    <div class="big-balance mb-1">
      R$ <?= number_format((float)$wallet['balance_available'], 2, ',', '.') ?>
    </div>
    <div class="d-flex gap-4 mt-2 small opacity-85">
      <div>
        <div class="opacity-75">📈 Total Ganho</div>
        <div class="fw-semibold">R$ <?= number_format((float)$wallet['balance_total_earned'], 2, ',', '.') ?></div>
      </div>
      <div>
        <div class="opacity-75">⚡ Créditos de Lance</div>
        <div class="fw-semibold"><?= $bid_credits ?> créditos</div>
      </div>
    </div>
  </div>

  <!-- ══ Ações Rápidas ═══════════════════════════════════ -->
  <div class="row g-2 mb-3">
    <div class="col-6">
      <a href="/depositar" class="btn quick-btn qb-deposit w-100">
        <div style="font-size:1.4rem">💰</div>
        <div class="small mt-1">Depositar</div>
      </a>
    </div>
    <div class="col-6">
      <a href="/sacar" class="btn quick-btn qb-withdraw w-100">
        <div style="font-size:1.4rem">💵</div>
        <div class="small mt-1">Sacar</div>
      </a>
    </div>
    <div class="col-6">
      <a href="/investir" class="btn quick-btn qb-invest w-100">
        <div style="font-size:1.4rem">📈</div>
        <div class="small mt-1">Investir</div>
      </a>
    </div>
    <div class="col-6">
      <a href="#" onclick="copyLink()" class="btn quick-btn qb-invite w-100">
        <div style="font-size:1.4rem">🔗</div>
        <div class="small mt-1">Indicar</div>
      </a>
    </div>
  </div>

  <!-- ══ Investimento Ativo ══════════════════════════════ -->
  <?php if ($active_inv): ?>
  <?php
    $pct = ($active_inv['cap_limit'] > 0)
           ? min(100, round(($active_inv['amount_earned'] / $active_inv['cap_limit']) * 100, 1))
           : 0;
  ?>
  <div class="dash-card invest-card p-4 mb-3">
    <div class="d-flex justify-content-between align-items-start mb-2">
      <div>
        <div class="small opacity-75 mb-1">📈 Plano Ativo</div>
        <div class="fw-bold fs-5"><?= $active_inv['icon'] ?> <?= htmlspecialchars($active_inv['plan_name']) ?></div>
      </div>
      <div class="text-end">
        <div class="small opacity-75">Rendimento/dia</div>
        <div class="fw-bold fs-5"><?= $active_inv['daily_rate'] ?>%</div>
      </div>
    </div>
    <div class="d-flex justify-content-between small mb-1 opacity-85">
      <span>R$ <?= number_format($active_inv['amount_earned'], 2, ',', '.') ?> ganhos</span>
      <span><?= $pct ?>% do teto</span>
    </div>
    <div class="invest-bar mb-2">
      <div class="invest-bar-fill" style="width:<?= $pct ?>%"></div>
    </div>
    <div class="d-flex justify-content-between small opacity-75">
      <span>Investido: R$ <?= number_format($active_inv['amount_invested'], 2, ',', '.') ?></span>
      <span>Teto: R$ <?= number_format($active_inv['cap_limit'], 2, ',', '.') ?></span>
    </div>
  </div>
  <?php else: ?>
  <a href="/investir" class="text-decoration-none">
    <div class="dash-card p-4 mb-3 d-flex align-items-center gap-3"
         style="background:#f8f7ff;border:2px dashed #a29bfe">
      <div style="font-size:2rem">💎</div>
      <div>
        <div class="fw-bold text-primary">Comece a investir!</div>
        <small class="text-muted">Planos a partir de R$50 com rendimento diário</small>
      </div>
      <i class="bi bi-chevron-right ms-auto text-primary"></i>
    </div>
  </a>
  <?php endif; ?>

  <!-- ══ Leilão ao Vivo ══════════════════════════════════ -->
  <?php if ($live_auction): ?>
  <div class="auction-live p-4 mb-3">
    <div class="small opacity-75 mb-2">🎯 Leilão em Andamento</div>
    <div class="fw-bold fs-5 mb-2"><?= htmlspecialchars($live_auction['name']) ?></div>
    <div class="d-flex align-items-center justify-content-between mb-3">
      <div>
        <div class="small opacity-75">Preço atual</div>
        <div class="auction-price" id="live-price">
          R$ <?= number_format($live_auction['current_price'], 2, ',', '.') ?>
        </div>
      </div>
      <div class="text-center">
        <div class="small opacity-75 mb-1">⏱ Timer</div>
        <div class="timer-display" id="live-timer">
          <?= str_pad($seconds_left, 2, '0', STR_PAD_LEFT) ?>s
        </div>
      </div>
      <div class="text-end">
        <div class="small opacity-75">Lances</div>
        <div class="fw-bold fs-5"><?= number_format($live_auction['total_bids']) ?></div>
      </div>
    </div>
    <a href="/leilao/<?= $live_auction['slug'] ?>"
       class="btn w-100 fw-bold py-2"
       style="background:linear-gradient(90deg,#6c5ce7,#a29bfe);color:#fff;border-radius:12px">
      ⚡ Participar agora — <?= $bid_credits ?> crédito(s) disponíveis
    </a>
  </div>
  <?php endif; ?>

  <!-- ══ Rede Binária Mini ═══════════════════════════════ -->
  <?php if ($binary): ?>
  <div class="dash-card network-card p-4 mb-3">
    <div class="small opacity-75 mb-2">🌐 Minha Rede Binária</div>
    <div class="d-flex justify-content-between mb-2">
      <div class="text-center" style="flex:1">
        <div class="small opacity-75">Esquerda</div>
        <div class="fw-bold">R$ <?= number_format($binary['left_volume'], 2, ',', '.') ?></div>
      </div>
      <div class="vr opacity-25 mx-3"></div>
      <div class="text-center" style="flex:1">
        <div class="small opacity-75">Direita</div>
        <div class="fw-bold">R$ <?= number_format($binary['right_volume'], 2, ',', '.') ?></div>
      </div>
    </div>
    <?php
      $total_vol = $binary['left_volume'] + $binary['right_volume'];
      $left_pct = $total_vol > 0 ? round(($binary['left_volume'] / $total_vol) * 100) : 50;
    ?>
    <div class="net-bar mb-2">
      <div class="net-bar-fill"
           style="width:<?= $left_pct ?>%;background:linear-gradient(90deg,#6c5ce7,#a29bfe)"></div>
    </div>
    <div class="d-flex justify-content-between small opacity-75">
      <span>💰 Total Ganho: R$ <?= number_format($binary_earned, 2, ',', '.') ?></span>
      <span>🔗 Comissões: R$ <?= number_format($unilevel_earned, 2, ',', '.') ?></span>
    </div>
  </div>
  <?php endif; ?>

  <!-- ══ Link de indicação ═══════════════════════════════ -->
  <div class="dash-card p-3 mb-3" style="background:#fff5f0;border:1px solid #ffd6b0;border-radius:14px">
    <div class="small fw-semibold mb-1">🔗 Seu Link de Indicação</div>
    <div class="d-flex align-items-center gap-2">
      <input type="text" class="form-control form-control-sm rounded-3 border-0"
             id="ref-link" value="<?= htmlspecialchars($ref_link) ?>"
             style="background:#fff8f5;font-size:.8rem" readonly onclick="this.select()">
      <button class="btn btn-sm btn-warning rounded-3 fw-semibold" onclick="copyLink()">
        Copiar
      </button>
    </div>
  </div>

  <!-- ══ Últimas Transações ══════════════════════════════ -->
  <div class="dash-card p-4 mb-3">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h6 class="fw-bold mb-0">📋 Últimas Movimentações</h6>
      <a href="/carteira/extrato" class="small text-primary text-decoration-none">Ver tudo →</a>
    </div>

    <?php if ($transactions->num_rows === 0): ?>
      <p class="text-muted text-center small py-3">Nenhuma movimentação ainda.</p>
    <?php else: ?>
      <div class="d-flex flex-column gap-2">
        <?php while ($tx = $transactions->fetch_assoc()):
          $ti = $tx_icons[$tx['type']] ?? ['💲', 'Transação', 'text-muted'];
          $isCredit = $tx['amount'] > 0;
        ?>
        <div class="d-flex align-items-center gap-3 tx-row p-2">
          <div class="tx-icon"><?= $ti[0] ?></div>
          <div style="flex:1">
            <div class="small fw-semibold"><?= $ti[1] ?></div>
            <div class="text-muted" style="font-size:.72rem">
              <?= date('d/m/Y H:i', strtotime($tx['created_at'])) ?>
              <?= $tx['description'] ? '· ' . htmlspecialchars(substr($tx['description'],0,40)) : '' ?>
            </div>
          </div>
          <div class="fw-bold <?= $isCredit ? 'text-success' : 'text-danger' ?>">
            <?= $isCredit ? '+' : '' ?>R$ <?= number_format(abs($tx['amount']), 2, ',', '.') ?>
          </div>
        </div>
        <?php endwhile; ?>
      </div>
    <?php endif; ?>
  </div>

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

<script>
// ── Copiar link de indicação ──────────────────────────────
function copyLink() {
  const el = document.getElementById('ref-link');
  el.select(); el.setSelectionRange(0, 99999);
  navigator.clipboard.writeText(el.value).then(() => {
    alert_toast('Link copiado!', 'success');
  }).catch(() => {
    el.select(); document.execCommand('copy');
    alert_toast('Link copiado!', 'success');
  });
}

// ── Timer do leilão ao vivo ───────────────────────────────
<?php if ($live_auction): ?>
let timerVal = <?= $seconds_left ?>;
let phase    = <?= $live_auction['phase'] ?>;

const timerEl = document.getElementById('live-timer');
const priceEl = document.getElementById('live-price');

setInterval(() => {
  if (phase === 2 && timerVal > 0) {
    timerVal--;
    timerEl.textContent = timerVal + 's';
    if (timerVal <= 10) timerEl.style.color = '#e74c3c';
  }
}, 1000);

// Polling do estado real a cada 5s
setInterval(() => {
  fetch('/ajax?f=auction_status&id=<?= $live_auction['id'] ?>')
    .then(r => r.json())
    .then(d => {
      if (d.current_price) priceEl.textContent = 'R$ ' + d.current_price;
      if (typeof d.seconds_left !== 'undefined') timerVal = d.seconds_left;
      if (d.phase) phase = d.phase;
    });
}, 5000);
<?php endif; ?>
</script>
