<?php
// pages/creditos.php — Compra de Créditos de Lance

if ($_settings->userdata('id') == '') {
    echo '<script>location.replace(\'/entrar?redirect=/creditos\');</script>'; exit();
}
$customer_id   = (int) $_settings->userdata('id');
$customer_name = trim($_settings->userdata('firstname') . ' ' . $_settings->userdata('lastname'));
$customer_email = $_settings->userdata('email');
$customer_phone = $_settings->userdata('phone');
$customer_cpf   = $_settings->userdata('cpf');

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

// Créditos atuais
$credits_row  = $conn->query("SELECT credits FROM bid_credits WHERE customer_id=$customer_id")->fetch_assoc();
$user_credits = (int)($credits_row['credits'] ?? 0);

// Pacotes
$packages = $conn->query("SELECT * FROM bid_packages WHERE is_active=1 ORDER BY credits ASC");

// ─── Processar compra ────────────────────────────────────
$error   = '';
$checkout_order = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['package_id'])) {
    $pkg_id = (int)$_POST['package_id'];
    $pkg    = $conn->query("SELECT * FROM bid_packages WHERE id=$pkg_id AND is_active=1")->fetch_assoc();

    if (!$pkg) {
        $error = "Pacote inválido.";
    } else {
        $insert = $conn->query("INSERT INTO bid_package_orders
                                SET customer_id=$customer_id,
                                    package_id=$pkg_id,
                                    credits_qty={$pkg['credits']},
                                    amount={$pkg['price']}");
        if ($insert) {
            $order_id = $conn->insert_id;
            // Gera PIX usando o mesmo padrão do sistema
            generate_deposit_pix($order_id, $pkg['price'], $customer_name,
                                  $customer_email, $customer_phone, $customer_cpf);
            // Nota: reutiliza deposits mas salva em bid_package_orders
            // Precisamos gerar direto:
            $pix_data = generate_pix_for_credits($order_id, $pkg, $customer_name, $customer_email, $customer_phone, $customer_cpf);
            if ($pix_data) {
                $conn->query("UPDATE bid_package_orders SET
                              payment_method='" . $conn->real_escape_string($pix_data['method']) . "',
                              pix_code='" . $conn->real_escape_string($pix_data['code']) . "',
                              pix_qrcode='" . $conn->real_escape_string($pix_data['qrcode']) . "',
                              id_mp='" . $conn->real_escape_string($pix_data['id_mp']) . "'
                              WHERE id=$order_id");
            }
            $checkout_order = $conn->query("SELECT bpo.*, bp.name as pkg_name, bp.credits
                                            FROM bid_package_orders bpo
                                            JOIN bid_packages bp ON bpo.package_id=bp.id
                                            WHERE bpo.id=$order_id")->fetch_assoc();
        } else {
            $error = "Erro ao criar pedido.";
        }
    }
}

// Gera PIX para créditos
function generate_pix_for_credits($order_id, $pkg, $name, $email, $phone, $cpf) {
    global $_settings, $conn;
    $gateway = $_settings->info('payment_method');
    $amount  = $pkg['price'];

    switch ($gateway) {
        case 'openpix':
            $appId = $_settings->info('openpix_app_id');
            $data  = ['correlationID' => 'CRED-' . $order_id, 'value' => (int)round($amount * 100),
                      'comment' => 'Créditos de Lance #' . $order_id, 'expiresIn' => 1800,
                      'customer' => ['name' => $name, 'email' => ($email ?: 'noreply@site.com'), 'phone' => $phone]];
            $curl  = curl_init();
            curl_setopt_array($curl, [CURLOPT_URL => 'https://api.openpix.com.br/api/v1/charge',
                CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS => json_encode($data),
                CURLOPT_HTTPHEADER => ['Authorization: ' . $appId, 'content-type: application/json']]);
            $resp = json_decode(curl_exec($curl), true); curl_close($curl);
            return ['method'=>'OpenPix','code'=>$resp['charge']['brCode']??'',
                    'qrcode'=>$resp['charge']['qrCodeImage']??'','id_mp'=>$resp['charge']['globalID']??''];
    }
    return null;
}

// Histórico de pedidos de crédito
$history = $conn->query("SELECT bpo.*, bp.name as pkg_name, bp.credits
                          FROM bid_package_orders bpo
                          JOIN bid_packages bp ON bpo.package_id=bp.id
                          WHERE bpo.customer_id=$customer_id
                          ORDER BY bpo.created_at DESC LIMIT 10");
?>

<style>
.credits-hero {
  background:linear-gradient(135deg,#2d3436 0%,#1a1a2e 100%);
  border-radius:20px; color:#fff; padding:2rem; margin-bottom:1.5rem;
}
.credits-big { font-size:3rem; font-weight:900; color:#ffd700; }
.pkg-card {
  border-radius:18px; border:2px solid #e8e5f5; cursor:pointer;
  transition:all .25s; overflow:hidden; background:#fff;
}
.pkg-card:hover { border-color:#6c5ce7; transform:translateY(-4px);
                  box-shadow:0 12px 32px rgba(108,92,231,.2); }
.pkg-card.featured { border-color:#6c5ce7; position:relative; }
.pkg-banner { background:linear-gradient(90deg,#6c5ce7,#a29bfe);
              color:#fff; font-size:.75rem; font-weight:800;
              text-align:center; padding:5px; letter-spacing:1px; }
.pkg-credits-big { font-size:2.8rem; font-weight:900; color:#2d3436; }
.pkg-price { font-size:1.4rem; font-weight:800; color:#6c5ce7; }
.pkg-per   { color:#636e72; font-size:.8rem; }
.pix-box   { background:#f8f7ff; border:2px dashed #6c5ce7; border-radius:14px; }
.pix-qr    { max-width:180px; border-radius:10px; }
.badge-s1  { background:rgba(255,165,0,.15); color:#e67e22; }
.badge-s2  { background:rgba(0,200,100,.15);  color:#00b894; }
.badge-s3  { background:rgba(220,50,50,.15);  color:#d63031; }
</style>

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

  <!-- ── Hero ─────────────────────────────────────────── -->
  <div class="credits-hero">
    <div class="small opacity-75 mb-1">⚡ Créditos de Lance</div>
    <div class="credits-big"><?= $user_credits ?></div>
    <div class="small opacity-75">créditos disponíveis</div>
    <div class="mt-3 small opacity-60">1 crédito = 1 lance no leilão · Sem expiração</div>
  </div>

  <?php if ($error): ?>
    <div class="alert alert-danger rounded-4 mb-3">⚠️ <?= htmlspecialchars($error) ?></div>
  <?php endif; ?>

  <!-- ── Checkout (após escolher pacote) ───────────────── -->
  <?php if ($checkout_order): ?>
  <div class="card mb-4" style="border-radius:18px;border:none;box-shadow:0 4px 24px rgba(108,92,231,.12)">
    <div class="card-body p-4 text-center">
      <div class="mb-2" style="font-size:2.5rem">📲</div>
      <h5 class="fw-bold mb-1">PIX Gerado!</h5>
      <p class="text-muted small mb-3">
        Pague o PIX para receber
        <strong><?= $checkout_order['credits'] ?> créditos de lance</strong>
        instantaneamente.
      </p>

      <div class="pix-box p-3 mb-3 mx-auto" style="max-width:340px">
        <?php if (!empty($checkout_order['pix_qrcode'])): ?>
          <img src="<?= str_starts_with($checkout_order['pix_qrcode'],'http')
                    ? htmlspecialchars($checkout_order['pix_qrcode'])
                    : 'data:image/png;base64,'.$checkout_order['pix_qrcode'] ?>"
               class="pix-qr mb-3 d-block mx-auto" alt="QR PIX">
        <?php endif; ?>

        <small class="text-muted d-block mb-1">Código Copia e Cola:</small>
        <div class="d-flex gap-2">
          <input type="text" class="form-control form-control-sm rounded-3"
                 id="pix-code" value="<?= htmlspecialchars($checkout_order['pix_code']) ?>"
                 readonly onclick="this.select()">
          <button class="btn btn-sm btn-outline-primary rounded-3" onclick="copyCode()">
            <i class="bi bi-clipboard"></i>
          </button>
        </div>
        <div id="copy-ok" class="text-success small mt-1" style="display:none">✅ Copiado!</div>
      </div>

      <div class="alert alert-info rounded-4 small text-start">
        📦 <strong><?= htmlspecialchars($checkout_order['pkg_name']) ?></strong>
        · <?= $checkout_order['credits'] ?> créditos
        · <strong>R$ <?= number_format($checkout_order['amount'],2,',','.') ?></strong>
      </div>

      <div class="spinner-border spinner-border-sm text-primary me-2"></div>
      <small class="text-muted">Aguardando confirmação do pagamento...</small>
    </div>
  </div>

  <script>
  // Polling de status de pedido de crédito
  let ck = 0;
  const credInterval = setInterval(() => {
    ck++;
    fetch('/ajax?f=check_credit_order&id=<?= $checkout_order['id'] ?>')
      .then(r=>r.json())
      .then(d => {
        if (d.status == 2) {
          clearInterval(credInterval);
          document.querySelector('.spinner-border').remove();
          document.querySelector('.text-muted').textContent = '✅ Créditos adicionados! Redirecionando...';
          setTimeout(() => location.href = '/creditos', 2000);
        }
      });
    if (ck > 120) clearInterval(credInterval);
  }, 5000);

  function copyCode() {
    const el = document.getElementById('pix-code');
    el.select(); navigator.clipboard.writeText(el.value);
    document.getElementById('copy-ok').style.display = 'block';
    setTimeout(() => document.getElementById('copy-ok').style.display='none', 2500);
  }
  </script>

  <?php else: ?>
  <!-- ── Pacotes ──────────────────────────────────────── -->
  <h5 class="fw-bold mb-3">🎁 Escolha seu Pacote</h5>

  <div class="row g-3 mb-4">
    <?php $pkgs_arr = []; $packages->data_seek(0); while ($p = $packages->fetch_assoc()) $pkgs_arr[] = $p; ?>
    <?php foreach ($pkgs_arr as $p):
      $price_per = $p['credits'] > 0 ? round($p['price'] / $p['credits'], 3) : 0;
    ?>
    <div class="col-6 col-md-3">
      <div class="pkg-card <?= $p['is_featured'] ? 'featured':'' ?>">
        <?php if ($p['is_featured']): ?>
          <div class="pkg-banner">🔥 MAIS POPULAR</div>
        <?php endif; ?>
        <div class="p-3 text-center">
          <div class="pkg-credits-big"><?= number_format($p['credits']) ?></div>
          <div class="small text-muted mb-2">créditos</div>
          <div class="pkg-price">R$ <?= number_format($p['price'],2,',','.') ?></div>
          <div class="pkg-per mb-3">= R$ <?= number_format($price_per,3,',','.') ?>/lance</div>

          <form method="POST">
            <input type="hidden" name="package_id" value="<?= $p['id'] ?>">
            <button type="submit" class="btn w-100 fw-bold rounded-3 py-2"
                    style="background:linear-gradient(135deg,#6c5ce7,#a29bfe);color:#fff;border:none">
              Comprar
            </button>
          </form>
        </div>
      </div>
    </div>
    <?php endforeach; ?>
  </div>

  <!-- ── Como funciona ──────────────────────────────── -->
  <div class="card mb-4" style="border-radius:18px;background:#f8f7ff;border:2px solid #e8e5f5">
    <div class="card-body p-4">
      <h6 class="fw-bold mb-3">⚡ Como funcionam os Créditos?</h6>
      <div class="d-flex flex-column gap-2 small">
        <div>✅ <strong>Sem expiração</strong> — use quando quiser</div>
        <div>✅ <strong>Qualquer leilão</strong> — vale para todos</div>
        <div>✅ <strong>PIX instantâneo</strong> — créditos liberados em segundos</div>
        <div>⚡ <strong>1 crédito = 1 lance</strong> → aumenta o preço em R$0,01 e reinicia o timer</div>
        <div>🏆 <strong>Último a dar lance</strong> quando o timer zerar = VENCEDOR!</div>
      </div>
    </div>
  </div>
  <?php endif; ?>

  <!-- ── Histórico de pedidos ─────────────────────────── -->
  <div class="card" style="border-radius:18px;border:none;box-shadow:0 4px 20px rgba(0,0,0,.07)">
    <div class="card-body p-4">
      <h6 class="fw-bold mb-3">📋 Histórico de Créditos</h6>
      <?php if ($history->num_rows === 0): ?>
        <p class="text-muted text-center small py-3">Nenhuma compra realizada ainda.</p>
      <?php else: ?>
        <div class="list-group list-group-flush">
          <?php while ($h = $history->fetch_assoc()):
            $sc = ['1'=>'s1','2'=>'s2','3'=>'s3'][$h['status']] ?? '';
            $slabel = ['1'=>'Pendente','2'=>'Confirmado','3'=>'Cancelado'][$h['status']] ?? '-';
          ?>
          <div class="list-group-item border-0 border-bottom px-0 py-3">
            <div class="d-flex justify-content-between align-items-center">
              <div>
                <div class="fw-semibold"><?= htmlspecialchars($h['pkg_name']) ?>
                  <span class="text-muted">· <?= $h['credits'] ?> créditos</span></div>
                <small class="text-muted"><?= date('d/m/Y H:i', strtotime($h['created_at'])) ?></small>
              </div>
              <div class="text-end">
                <div class="fw-bold">R$ <?= number_format($h['amount'],2,',','.') ?></div>
                <span class="badge rounded-pill px-3 py-1 small <?= 'badge-'.$h['status'] ?>">
                  <?= $slabel ?>
                </span>
              </div>
            </div>
          </div>
          <?php endwhile; ?>
        </div>
      <?php endif; ?>
    </div>
  </div>

</div>
