<?php
// ─── Autenticação obrigatória ───────────────────────────
if ($_settings->userdata('id') == '') {
    echo '<script>location.replace(\'/\');</script>';
    exit();
}
$customer_id    = (int) $_settings->userdata('id');
$customer_fname = $_settings->userdata('firstname');
$customer_lname = $_settings->userdata('lastname');
$customer_email = $_settings->userdata('email');
$customer_phone = $_settings->userdata('phone');
$customer_cpf   = $_settings->userdata('cpf');
$customer_name  = trim($customer_fname . ' ' . $customer_lname);

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

// ─── Garante que carteira existe ────────────────────────
$wallet = wallet_get($customer_id);

// ─── Configurações ──────────────────────────────────────
$min_deposit    = (float) ($_settings->info('deposit_min_amount') ?: 10);
$payment_method = $_settings->info('payment_method');

// ─── Processa formulário de depósito ────────────────────
$error   = '';
$success = '';
$deposit_row = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['amount_deposit'])) {
    $amount = (float) str_replace(['.', ','], ['', '.'], $_POST['amount_deposit']);

    if ($amount < $min_deposit) {
        $error = "Valor mínimo para depósito é R$ " . number_format($min_deposit, 2, ',', '.');
    } elseif (!$payment_method) {
        $error = "Nenhum gateway de pagamento configurado. Contate o suporte.";
    } else {
        $expiry  = (int) ($_settings->info('deposit_expiration_minutes') ?: 30);
        $insert  = $conn->query("INSERT INTO deposits
                                 SET customer_id = $customer_id,
                                     amount      = $amount,
                                     order_expiration = $expiry");
        if ($insert) {
            $deposit_id = $conn->insert_id;
            generate_deposit_pix($deposit_id, $amount, $customer_name,
                                  $customer_email, $customer_phone, $customer_cpf);
            // Recarrega os dados do depósito com o PIX gerado
            $deposit_row = $conn->query("SELECT * FROM deposits WHERE id = $deposit_id")->fetch_assoc();
        } else {
            $error = "Erro ao criar depósito. Tente novamente.";
        }
    }
}

// ─── Histórico de Depósitos ─────────────────────────────
$history = $conn->query("SELECT * FROM deposits WHERE customer_id = $customer_id
                          ORDER BY created_at DESC LIMIT 20");
?>

<style>
.wallet-card       { background: linear-gradient(135deg, #6c5ce7 0%, #a29bfe 100%); border-radius: 20px; color: #fff; }
.deposit-card      { border-radius: 16px; border: none; box-shadow: 0 4px 24px rgba(108,92,231,.12); }
.pix-box           { background: #f8f7ff; border: 2px dashed #6c5ce7; border-radius: 14px; }
.pix-qr            { max-width: 200px; border-radius: 10px; }
.badge-status-1    { background: rgba(255,165,0,.15); color: #e67e22; }
.badge-status-2    { background: rgba(0,200,100,.15);  color: #00b894; }
.badge-status-3    { background: rgba(220,50,50,.15);  color: #d63031; }
.amount-btn        { border-radius: 50px !important; font-weight: 600; transition: all .2s; }
.amount-btn:hover  { transform: translateY(-2px); box-shadow: 0 6px 16px rgba(108,92,231,.3); }
.deposit-input     { border-radius: 12px !important; border: 2px solid #e8e5f5 !important;
                     font-size: 1.3rem !important; font-weight: 700 !important;
                     text-align: center !important; }
.deposit-input:focus { border-color: #6c5ce7 !important; box-shadow: 0 0 0 4px rgba(108,92,231,.15) !important; }
.copy-btn          { cursor: pointer; transition: all .2s; }
.copy-btn:active   { transform: scale(.95); }
.hist-row          { border-left: 4px solid transparent; transition: .2s; }
.hist-row:hover    { background: #f8f7ff; }
.hist-row.s1       { border-color: #e67e22; }
.hist-row.s2       { border-color: #00b894; }
.hist-row.s3       { border-color: #d63031; }
</style>

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

  <!-- ══ Cabeçalho ══════════════════════════════════════ -->
  <div class="app-title mb-3">
    <h1>💰 Depositar</h1>
    <div class="app-title-desc" style="color:#424b58">Adicione saldo à sua carteira</div>
  </div>

  <!-- ══ Card da Carteira ═══════════════════════════════ -->
  <div class="wallet-card p-4 mb-4 d-flex align-items-center justify-content-between">
    <div>
      <div class="opacity-75 small mb-1">💼 Saldo Disponível</div>
      <div class="fw-bold" style="font-size:1.8rem">
        R$ <?= number_format((float)$wallet['balance_available'], 2, ',', '.') ?>
      </div>
    </div>
    <div class="text-end">
      <div class="opacity-75 small mb-1">📈 Total Ganho</div>
      <div class="fw-bold fs-5">
        R$ <?= number_format((float)$wallet['balance_total_earned'], 2, ',', '.') ?>
      </div>
    </div>
  </div>

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

  <!-- ══ Formulário de Depósito ═════════════════════════ -->
  <?php if (!$deposit_row): ?>
  <div class="card deposit-card mb-4">
    <div class="card-body p-4">
      <h5 class="fw-bold mb-3">🏦 Novo Depósito via PIX</h5>

      <form method="POST" id="form-deposit">
        <!-- Atalhos de valor -->
        <div class="d-flex flex-wrap gap-2 mb-3">
          <?php foreach ([10, 25, 50, 100, 250, 500] as $v): ?>
            <button type="button" class="btn btn-outline-primary amount-btn btn-sm"
                    onclick="setAmount(<?= $v ?>)">
              R$<?= $v ?>
            </button>
          <?php endforeach; ?>
        </div>

        <div class="mb-3">
          <label class="form-label fw-semibold">Valor do Depósito</label>
          <div class="input-group">
            <span class="input-group-text rounded-start-3 border-end-0 fw-bold">R$</span>
            <input type="text" id="amount_deposit" name="amount_deposit"
                   class="form-control deposit-input"
                   placeholder="0,00"
                   required autocomplete="off">
          </div>
          <small class="text-muted">Mínimo: R$ <?= number_format($min_deposit, 2, ',', '.') ?></small>
        </div>

        <button type="submit" class="btn btn-primary w-100 rounded-4 py-3 fw-bold"
                style="background:linear-gradient(90deg,#6c5ce7,#a29bfe);border:none">
          ⚡ Gerar PIX agora
        </button>
      </form>
    </div>
  </div>

  <?php else: // Depósito criado — exibe QR Code ?>

  <div class="card deposit-card mb-4">
    <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 com Sucesso!</h5>
      <p class="text-muted small mb-4">
        Pague com PIX e o saldo será creditado automaticamente na sua carteira.
      </p>

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

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

      <div class="alert alert-warning rounded-4 small text-start">
        <strong>⚠️ Atenção:</strong>
        <ul class="mb-0 mt-1">
          <li>O PIX expira em <strong><?= $deposit_row['order_expiration'] ?> minutos</strong></li>
          <li>Após o pagamento, seu saldo será creditado automaticamente</li>
          <li>Pedido: <strong>#<?= $deposit_row['id'] ?></strong></li>
          <li>Valor: <strong>R$ <?= number_format($deposit_row['amount'], 2, ',', '.') ?></strong></li>
        </ul>
      </div>

      <!-- Polling automático de status -->
      <div id="status-check" class="mt-3">
        <div class="spinner-border spinner-border-sm text-primary me-2"></div>
        <small class="text-muted">Aguardando confirmação do pagamento...</small>
      </div>

    </div>
  </div>
  <?php endif; ?>

  <!-- ══ Histórico de Depósitos ═════════════════════════ -->
  <div class="card deposit-card">
    <div class="card-body p-4">
      <h6 class="fw-bold mb-3">📋 Histórico de Depósitos</h6>
      <?php if ($history->num_rows === 0): ?>
        <p class="text-muted text-center py-3">Nenhum depósito realizado ainda.</p>
      <?php else: ?>
        <div class="list-group list-group-flush">
          <?php while ($dep = $history->fetch_assoc()):
            $sc = ['1'=>'s1','2'=>'s2','3'=>'s3'][$dep['status']] ?? '';
            $slabel = ['1'=>'Pendente','2'=>'Confirmado','3'=>'Cancelado'][$dep['status']] ?? '-';
            $badgeClass = 'badge-status-'.$dep['status'];
          ?>
          <div class="list-group-item hist-row <?= $sc ?> px-2 py-3 border-0 border-bottom">
            <div class="d-flex justify-content-between align-items-center">
              <div>
                <div class="fw-semibold">R$ <?= number_format($dep['amount'], 2, ',', '.') ?></div>
                <small class="text-muted"><?= date('d/m/Y H:i', strtotime($dep['created_at'])) ?></small>
                <?php if ($dep['payment_method']): ?>
                  <small class="text-muted ms-2">· <?= htmlspecialchars($dep['payment_method']) ?></small>
                <?php endif; ?>
              </div>
              <div>
                <span class="badge rounded-pill px-3 py-2 small fw-semibold <?= $badgeClass ?>">
                  <?= $slabel ?>
                </span>
                <?php if ($dep['status'] == 1 && !empty($dep['pix_code'])): ?>
                <a href="/depositar?id=<?= $dep['id'] ?>"
                   class="btn btn-sm btn-warning rounded-pill ms-2 py-1 px-2 small">
                  Pagar
                </a>
                <?php endif; ?>
              </div>
            </div>
          </div>
          <?php endwhile; ?>
        </div>
      <?php endif; ?>
    </div>
  </div>

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

<script>
function setAmount(v) {
  document.getElementById('amount_deposit').value = v.toFixed(2).replace('.', ',');
}

function copyPix() {
  const el = document.getElementById('pix-code-val');
  el.select(); el.setSelectionRange(0, 99999);
  navigator.clipboard.writeText(el.value).then(() => {
    const fb = document.getElementById('copy-feedback');
    fb.style.display = 'block';
    setTimeout(() => fb.style.display = 'none', 2500);
  });
}

// Formatar campo de valor
document.getElementById('amount_deposit')?.addEventListener('input', function() {
  let v = this.value.replace(/\D/g, '');
  if (v.length < 3) v = v.padStart(3, '0');
  v = (parseInt(v) / 100).toFixed(2);
  this.value = v.replace('.', ',');
});

<?php if ($deposit_row && $deposit_row['status'] == 1): ?>
// Polling automático de status a cada 5s
let checkCount = 0;
const checkInterval = setInterval(() => {
  checkCount++;
  fetch('/ajax?f=check_deposit_status&id=<?= $deposit_row['id'] ?>')
    .then(r => r.json())
    .then(data => {
      if (data.status == 2) {
        clearInterval(checkInterval);
        document.getElementById('status-check').innerHTML =
          '<div class="alert alert-success rounded-4">✅ <strong>Pagamento Confirmado!</strong> Redirecionando...</div>';
        setTimeout(() => location.href = '/depositar', 2000);
      }
    });
  if (checkCount > 120) clearInterval(checkInterval); // Para após 10 min
}, 5000);
<?php endif; ?>
</script>
