<?php
// admin/withdrawals/index.php — Gestão de Saques
require_once '../../settings.php';

// Verifica acesso admin
if (!$_settings->userdata('type') || $_settings->userdata('type') != 1) {
    header('Location: /admin'); exit();
}

// ─── Processar aprovação/recusa ─────────────────────────
$msg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $wid    = (int)($_POST['wid'] ?? 0);
    $action = $_POST['action'] ?? '';
    $note   = $conn->real_escape_string($_POST['admin_note'] ?? '');

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

    if ($action === 'approve' && $wid) {
        $w = $conn->query("SELECT * FROM withdrawals WHERE id = $wid AND status = 1")->fetch_assoc();
        if ($w) {
            $conn->query("UPDATE withdrawals SET status=2, admin_note='$note', approved_at=NOW() WHERE id=$wid");
            enqueue_whatsapp($w['customer_id'], 'withdrawal_approved', $w['amount_net']);
            $msg = "✅ Saque #{$wid} aprovado com sucesso!";
        }
    } elseif ($action === 'reject' && $wid) {
        $w = $conn->query("SELECT * FROM withdrawals WHERE id = $wid AND status = 1")->fetch_assoc();
        if ($w) {
            // Devolve saldo
            wallet_credit($w['customer_id'], $w['amount'], 'adjustment',
                          "Estorno de saque recusado #{$wid}", $wid, 'withdrawal');
            $conn->query("UPDATE withdrawals SET status=3, admin_note='$note' WHERE id=$wid");
            enqueue_whatsapp($w['customer_id'], 'withdrawal_rejected', $w['amount']);
            $msg = "❌ Saque #{$wid} recusado e valor estornado.";
        }
    }
}

// ─── Filtros ────────────────────────────────────────────
$filter_status = (int)($_GET['status'] ?? 1); // Padrão: pendentes
$withdrawals = $conn->query("SELECT w.*, c.firstname, c.lastname, c.phone
                              FROM withdrawals w
                              JOIN customer_list c ON w.customer_id = c.id
                              WHERE w.status = $filter_status
                              ORDER BY w.created_at DESC");

// ─── Totais ─────────────────────────────────────────────
$totals = $conn->query("SELECT
                          SUM(CASE WHEN status=1 THEN amount ELSE 0 END) as pending,
                          SUM(CASE WHEN status=2 THEN amount ELSE 0 END) as approved,
                          COUNT(CASE WHEN status=1 THEN 1 END) as qtd_pending
                        FROM withdrawals")->fetch_assoc();
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Gestão de Saques — 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; }
.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; }
.action-bar { position: sticky; top: 0; background: #f4f6fb; z-index: 10; padding: .75rem 0; }
</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 Saques</h4>
      <small class="text-muted">Aprovar ou recusar solicitações de saque</small>
    </div>
    <a href="/admin" class="btn btn-outline-secondary btn-sm rounded-3">← Voltar</a>
  </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-md-4">
      <div class="stat-card" style="background:linear-gradient(135deg,#f39c12,#f1c40f)">
        <div class="small opacity-85">⏳ Pendentes</div>
        <div class="fs-4 fw-bold"><?= $totals['qtd_pending'] ?? 0 ?> saques</div>
        <div class="small opacity-85">R$ <?= number_format($totals['pending'] ?? 0, 2, ',', '.') ?></div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="stat-card" style="background:linear-gradient(135deg,#00b09b,#96c93d)">
        <div class="small opacity-85">✅ Aprovados (total)</div>
        <div class="fs-4 fw-bold">R$ <?= number_format($totals['approved'] ?? 0, 2, ',', '.') ?></div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="stat-card" style="background:linear-gradient(135deg,#6c5ce7,#a29bfe)">
        <div class="small opacity-85">📊 Filtro Atual</div>
        <div class="fs-5 fw-bold">
          <?= ['1'=>'Pendentes','2'=>'Aprovados','3'=>'Recusados'][$filter_status] ?? 'Todos' ?>
        </div>
      </div>
    </div>
  </div>

  <!-- ── Filtros ── -->
  <div class="action-bar mb-3">
    <div class="d-flex gap-2 flex-wrap">
      <?php foreach (['1'=>'⏳ Pendentes','2'=>'✅ Aprovados','3'=>'❌ Recusados'] as $s => $label): ?>
        <a href="?status=<?= $s ?>"
           class="btn btn-sm rounded-3 <?= $filter_status == $s ? 'btn-primary' : 'btn-outline-secondary' ?>">
          <?= $label ?>
        </a>
      <?php endforeach; ?>
    </div>
  </div>

  <!-- ── Tabela de Saques ── -->
  <div class="admin-card">
    <div class="card-body p-0">
      <?php if ($withdrawals->num_rows === 0): ?>
        <div class="text-center text-muted py-5">
          <div style="font-size:3rem">📭</div>
          <p>Nenhum saque encontrado.</p>
        </div>
      <?php else: ?>
      <div class="table-responsive">
        <table class="table align-middle mb-0">
          <thead class="table-light">
            <tr>
              <th class="ps-4">#</th>
              <th>Usuário</th>
              <th>Valor</th>
              <th>Taxa</th>
              <th>Líquido</th>
              <th>Chave PIX</th>
              <th>Data</th>
              <th>Status</th>
              <th class="pe-4">Ações</th>
            </tr>
          </thead>
          <tbody>
            <?php while ($w = $withdrawals->fetch_assoc()):
              $badgeCls = 'badge-s'.$w['status'];
              $slabel   = ['1'=>'Pendente','2'=>'Aprovado','3'=>'Recusado'][$w['status']] ?? '-';
            ?>
            <tr>
              <td class="ps-4 text-muted small">#<?= $w['id'] ?></td>
              <td>
                <div class="fw-semibold"><?= htmlspecialchars($w['firstname'].' '.$w['lastname']) ?></div>
                <small class="text-muted"><?= htmlspecialchars($w['phone']) ?></small>
              </td>
              <td class="fw-bold">R$ <?= number_format($w['amount'], 2, ',', '.') ?></td>
              <td class="text-danger small">-R$ <?= number_format($w['fee'], 2, ',', '.') ?></td>
              <td class="fw-bold text-success">R$ <?= number_format($w['amount'] - $w['fee'], 2, ',', '.') ?></td>
              <td>
                <div class="small"><span class="badge bg-light text-dark"><?= htmlspecialchars($w['pix_key_type']) ?></span></div>
                <code class="small"><?= htmlspecialchars($w['pix_key']) ?></code>
              </td>
              <td class="small text-muted"><?= date('d/m/Y H:i', strtotime($w['created_at'])) ?></td>
              <td><span class="badge rounded-pill px-3 py-2 <?= $badgeCls ?>"><?= $slabel ?></span></td>
              <td class="pe-4">
                <?php if ($w['status'] == 1): ?>
                <div class="d-flex gap-1">
                  <!-- Aprovar -->
                  <button class="btn btn-success btn-sm rounded-3"
                          onclick="processAction(<?= $w['id'] ?>, 'approve')">
                    ✅
                  </button>
                  <!-- Recusar -->
                  <button class="btn btn-danger btn-sm rounded-3"
                          onclick="processAction(<?= $w['id'] ?>, 'reject')">
                    ❌
                  </button>
                </div>
                <?php else: ?>
                  <?php if ($w['admin_note']): ?>
                    <small class="text-muted">📝 <?= htmlspecialchars($w['admin_note']) ?></small>
                  <?php endif; ?>
                <?php endif; ?>
              </td>
            </tr>
            <?php endwhile; ?>
          </tbody>
        </table>
      </div>
      <?php endif; ?>
    </div>
  </div>

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

<!-- ── Modal de confirmação ── -->
<div class="modal fade" id="actionModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content" style="border-radius:16px">
      <div class="modal-header border-0">
        <h5 class="modal-title fw-bold" id="modalTitle">Confirmar Ação</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST">
        <input type="hidden" name="wid" id="modal-wid">
        <input type="hidden" name="action" id="modal-action">
        <div class="modal-body">
          <div id="modal-msg" class="mb-3"></div>
          <label class="form-label small fw-semibold">Observação (opcional)</label>
          <textarea name="admin_note" class="form-control rounded-3" rows="3"
                    placeholder="Motivo, comprovante, etc."></textarea>
        </div>
        <div class="modal-footer border-0">
          <button type="button" class="btn btn-outline-secondary rounded-3" data-bs-dismiss="modal">Cancelar</button>
          <button type="submit" class="btn rounded-3 fw-bold" id="modal-submit-btn">Confirmar</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script src="/admin/assets/js/bootstrap.bundle.min.js"></script>
<script>
function processAction(wid, action) {
  document.getElementById('modal-wid').value    = wid;
  document.getElementById('modal-action').value = action;
  const isApprove = action === 'approve';
  document.getElementById('modalTitle').textContent    = isApprove ? '✅ Aprovar Saque' : '❌ Recusar Saque';
  document.getElementById('modal-msg').innerHTML       = isApprove
    ? '<div class="alert alert-success rounded-3">O saque será <strong>aprovado</strong> e o usuário será notificado via WhatsApp.</div>'
    : '<div class="alert alert-danger rounded-3">O saque será <strong>recusado</strong> e o valor será <strong>estornado</strong> para a carteira do usuário.</div>';
  const btn = document.getElementById('modal-submit-btn');
  btn.className = 'btn rounded-3 fw-bold ' + (isApprove ? 'btn-success' : 'btn-danger');
  btn.textContent = isApprove ? '✅ Aprovar' : '❌ Recusar';
  new bootstrap.Modal(document.getElementById('actionModal')).show();
}
</script>
</body>
</html>
