<?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);
$min_withdraw = (float) ($_settings->info('withdrawal_min_amount') ?: 20);
$fee_percent  = (float) ($_settings->info('withdrawal_fee_percent') ?: 5);

$error   = '';
$success = '';

// ─── Processa solicitação de saque ──────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['amount_withdrawal'])) {
    $amount      = (float) str_replace(['.', ','], ['', '.'], $_POST['amount_withdrawal']);
    $pix_key     = trim($_POST['pix_key'] ?? '');
    $pix_key_type = trim($_POST['pix_key_type'] ?? '');

    if ($amount < $min_withdraw) {
        $error = "Valor mínimo para saque é R$ " . number_format($min_withdraw, 2, ',', '.');
    } elseif ((float)$wallet['balance_available'] < $amount) {
        $error = "Saldo insuficiente. Disponível: R$ " . number_format((float)$wallet['balance_available'], 2, ',', '.');
    } elseif (empty($pix_key) || empty($pix_key_type)) {
        $error = "Informe sua chave PIX e o tipo.";
    } else {
        $fee        = round($amount * ($fee_percent / 100), 2);
        $amount_net = $amount - $fee;

        // Debita saldo (bloqueia na carteira)
        $debited = wallet_debit($customer_id, $amount, 'withdrawal',
                                "Saque solicitado — chave: $pix_key", null, 'withdrawal');
        if ($debited === false) {
            $error = "Erro ao processar saldo. Tente novamente.";
        } else {
            $conn->query("INSERT INTO withdrawals
                          SET customer_id  = $customer_id,
                              amount       = $amount,
                              fee          = $fee,
                              pix_key      = '" . $conn->real_escape_string($pix_key) . "',
                              pix_key_type = '" . $conn->real_escape_string($pix_key_type) . "'");
            $wid = $conn->insert_id;
            enqueue_whatsapp($customer_id, 'withdrawal_requested', $amount_net);
            $success = "Saque de R$ " . number_format($amount, 2, ',', '.') . " solicitado com sucesso! Será processado em até 24 horas.";
            // Recarrega carteira
            $wallet = wallet_get($customer_id);
        }
    }
}

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

<style>
.wallet-card      { background: linear-gradient(135deg,#00b09b 0%,#96c93d 100%); border-radius: 20px; color:#fff; }
.withdraw-card    { border-radius: 16px; border: none; box-shadow: 0 4px 24px rgba(0,176,155,.12); }
.withdraw-input   { border-radius: 12px !important; border: 2px solid #d5f5e3 !important;
                    font-size: 1.3rem !important; font-weight: 700 !important; text-align: center !important; }
.withdraw-input:focus { border-color: #00b09b !important; box-shadow: 0 0 0 4px rgba(0,176,155,.15) !important; }
.amount-btn       { border-radius: 50px !important; font-weight: 600; transition: all .2s; }
.amount-btn:hover { transform: translateY(-2px); box-shadow: 0 6px 16px rgba(0,176,155,.3); }
.fee-info         { background: #f0fefa; border: 1px solid #b2eadf; border-radius: 12px; }
.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; }
.hist-row         { border-left: 4px solid transparent; transition: .2s; }
.hist-row:hover   { background: #f0fefa; }
.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">

  <div class="app-title mb-3">
    <h1>💵 Sacar</h1>
    <div class="app-title-desc" style="color:#424b58">Transfira para sua conta via PIX</div>
  </div>

  <!-- 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" id="wallet-balance" style="font-size:1.8rem">
        R$ <?= number_format((float)$wallet['balance_available'], 2, ',', '.') ?>
      </div>
    </div>
    <div class="text-end" style="font-size:2rem">🏦</div>
  </div>

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

  <?php if ($success): ?>
    <div class="alert alert-success rounded-4 mb-3">✅ <?= htmlspecialchars($success) ?></div>
  <?php endif; ?>

  <!-- Formulário de saque -->
  <div class="card withdraw-card mb-4">
    <div class="card-body p-4">
      <h5 class="fw-bold mb-3">📤 Solicitar Saque</h5>

      <form method="POST" id="form-withdrawal">

        <!-- Atalhos de valor -->
        <div class="d-flex flex-wrap gap-2 mb-3">
          <?php foreach ([20, 50, 100, 250, 500] as $v): ?>
            <button type="button" class="btn btn-outline-success amount-btn btn-sm"
                    onclick="setAmount(<?= $v ?>)">
              R$<?= $v ?>
            </button>
          <?php endforeach; ?>
          <button type="button" class="btn btn-outline-success amount-btn btn-sm"
                  onclick="setMaxAmount()">
            Máximo
          </button>
        </div>

        <div class="mb-3">
          <label class="form-label fw-semibold">Valor do Saque</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_withdrawal" name="amount_withdrawal"
                   class="form-control withdraw-input"
                   placeholder="0,00" required autocomplete="off"
                   oninput="updateFee()">
          </div>
          <small class="text-muted">Mínimo: R$ <?= number_format($min_withdraw, 2, ',', '.') ?></small>
        </div>

        <!-- Tipo de chave PIX -->
        <div class="mb-3">
          <label class="form-label fw-semibold">Tipo de Chave PIX</label>
          <select name="pix_key_type" id="pix_key_type" class="form-select rounded-3"
                  onchange="updatePixPlaceholder()" required>
            <option value="">— Selecione —</option>
            <option value="cpf">CPF</option>
            <option value="telefone">Telefone</option>
            <option value="email">E-mail</option>
            <option value="aleatorio">Chave Aleatória</option>
          </select>
        </div>

        <div class="mb-3">
          <label class="form-label fw-semibold">Sua Chave PIX</label>
          <input type="text" id="pix_key" name="pix_key"
                 class="form-control rounded-3"
                 placeholder="Digite sua chave PIX" required>
        </div>

        <!-- Resumo da taxa -->
        <div class="fee-info p-3 mb-3" id="fee-summary" style="display:none">
          <div class="d-flex justify-content-between small mb-1">
            <span>Valor solicitado:</span>
            <strong id="fee-gross">R$ 0,00</strong>
          </div>
          <div class="d-flex justify-content-between small mb-1 text-danger">
            <span>Taxa (<?= $fee_percent ?>%):</span>
            <strong id="fee-amount">- R$ 0,00</strong>
          </div>
          <hr class="my-1">
          <div class="d-flex justify-content-between fw-bold text-success">
            <span>Você receberá:</span>
            <span id="fee-net">R$ 0,00</span>
          </div>
        </div>

        <button type="submit" class="btn btn-success w-100 rounded-4 py-3 fw-bold"
                style="background:linear-gradient(90deg,#00b09b,#96c93d);border:none">
          💵 Solicitar Saque
        </button>
      </form>
    </div>
  </div>

  <!-- Histórico -->
  <div class="card withdraw-card">
    <div class="card-body p-4">
      <h6 class="fw-bold mb-3">📋 Histórico de Saques</h6>
      <?php if ($history->num_rows === 0): ?>
        <p class="text-muted text-center py-3">Nenhum saque realizado ainda.</p>
      <?php else: ?>
        <div class="list-group list-group-flush">
          <?php while ($w = $history->fetch_assoc()):
            $sc = ['1'=>'s1','2'=>'s2','3'=>'s3'][$w['status']] ?? '';
            $slabel = ['1'=>'Pendente','2'=>'Aprovado','3'=>'Recusado'][$w['status']] ?? '-';
            $badgeClass = 'badge-status-'.$w['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($w['amount'], 2, ',', '.') ?></div>
                <small class="text-muted"><?= date('d/m/Y H:i', strtotime($w['created_at'])) ?></small>
                <?php if ($w['pix_key']): ?>
                  <small class="text-muted ms-2">· <?= htmlspecialchars($w['pix_key_type']) ?>: <em><?= htmlspecialchars($w['pix_key']) ?></em></small>
                <?php endif; ?>
                <?php if ($w['admin_note']): ?>
                  <div class="text-muted small mt-1">📝 <?= htmlspecialchars($w['admin_note']) ?></div>
                <?php endif; ?>
              </div>
              <span class="badge rounded-pill px-3 py-2 small fw-semibold <?= $badgeClass ?>">
                <?= $slabel ?>
              </span>
            </div>
          </div>
          <?php endwhile; ?>
        </div>
      <?php endif; ?>
    </div>
  </div>

</div>

<script>
const maxBalance = <?= (float)$wallet['balance_available'] ?>;
const feeRate    = <?= $fee_percent / 100 ?>;

function setAmount(v) {
  document.getElementById('amount_withdrawal').value = v.toFixed(2).replace('.', ',');
  updateFee();
}
function setMaxAmount() {
  setAmount(maxBalance);
}

function updateFee() {
  const raw = document.getElementById('amount_withdrawal').value.replace(',', '.');
  const v = parseFloat(raw) || 0;
  if (v > 0) {
    const fee = v * feeRate;
    const net = v - fee;
    document.getElementById('fee-gross').textContent  = 'R$ ' + v.toFixed(2).replace('.', ',');
    document.getElementById('fee-amount').textContent = '- R$ ' + fee.toFixed(2).replace('.', ',');
    document.getElementById('fee-net').textContent    = 'R$ ' + net.toFixed(2).replace('.', ',');
    document.getElementById('fee-summary').style.display = 'block';
  } else {
    document.getElementById('fee-summary').style.display = 'none';
  }
}

function updatePixPlaceholder() {
  const type = document.getElementById('pix_key_type').value;
  const placeholders = {
    cpf: '000.000.000-00',
    telefone: '(11) 99999-9999',
    email: 'seuemail@exemplo.com',
    aleatorio: 'Chave aleatória gerada pelo banco'
  };
  document.getElementById('pix_key').placeholder = placeholders[type] || 'Digite sua chave PIX';
}

// Formatar campo de valor
document.getElementById('amount_withdrawal').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('.', ',');
  updateFee();
});
</script>
