<?php
session_start();
$page_title = 'Withdrawals';
$active_nav = 'withdrawals';
include("includes/header.php");

$status_filter = $_GET['status'] ?? 'all';
$search        = trim($_GET['search'] ?? '');

$query = "SELECT wd.*, u.name as user_name, u.email as user_email
          FROM withdrawals wd
          LEFT JOIN users u ON wd.user_id=u.id
          WHERE 1=1";
$params=[]; $types="";

if ($status_filter !== 'all') { $query.=" AND wd.status=?"; $params[]=$status_filter; $types.="s"; }
if ($search) {
    $query.=" AND (u.name LIKE ? OR u.email LIKE ? OR wd.reference LIKE ?)";
    $s="%$search%"; $params=array_merge($params,[$s,$s,$s]); $types.="sss";
}
$query.=" ORDER BY wd.created_at DESC";

$stmt=$conn->prepare($query);
if($params) $stmt->bind_param($types,...$params);
$stmt->execute();
$withdrawals=$stmt->get_result();

// Totals
$totals=$conn->query("SELECT
    COALESCE(SUM(CASE WHEN status='success' THEN amount ELSE 0 END),0) as paid_out,
    COALESCE(SUM(CASE WHEN status='pending' THEN amount ELSE 0 END),0) as pending_amount,
    COUNT(CASE WHEN status='pending' THEN 1 END) as pending_count
    FROM withdrawals")->fetch_assoc();
?>

<div style="margin-bottom:28px">
  <h1 style="font-size:1.5rem;font-weight:800;letter-spacing:-.03em;margin-bottom:4px">Withdrawals</h1>
  <p style="color:var(--text-muted);font-size:.875rem">All withdrawal requests processed via Paystack</p>
</div>

<!-- Summary -->
<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:16px;margin-bottom:28px">
  <div class="card" style="padding:20px;border-top:3px solid var(--success)">
    <div style="font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:10px">Total Paid Out</div>
    <div style="font-size:1.6rem;font-weight:800;color:var(--success)">₦<?php echo number_format($totals['paid_out'],0); ?></div>
  </div>
  <div class="card" style="padding:20px;border-top:3px solid var(--warning)">
    <div style="font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:10px">Pending Amount</div>
    <div style="font-size:1.6rem;font-weight:800;color:var(--warning)">₦<?php echo number_format($totals['pending_amount'],0); ?></div>
  </div>
  <div class="card" style="padding:20px;border-top:3px solid var(--primary)">
    <div style="font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:10px">Pending Requests</div>
    <div style="font-size:1.6rem;font-weight:800;color:var(--primary)"><?php echo $totals['pending_count']; ?></div>
  </div>
</div>

<!-- Filters -->
<div style="display:flex;gap:8px;margin-bottom:16px;flex-wrap:wrap;align-items:center">
  <?php foreach(['all'=>'All','pending'=>'Pending','success'=>'Successful','failed'=>'Failed'] as $k=>$l): ?>
  <a href="?status=<?php echo $k; ?><?php echo $search?"&search=".urlencode($search):''; ?>"
     class="btn btn-sm <?php echo $status_filter===$k?'btn-primary':'btn-secondary'; ?>"><?php echo $l; ?></a>
  <?php endforeach; ?>
  <form method="GET" style="margin-left:auto">
    <input type="hidden" name="status" value="<?php echo htmlspecialchars($status_filter); ?>">
    <div style="position:relative">
      <svg style="position:absolute;left:11px;top:50%;transform:translateY(-50%);width:14px;height:14px;stroke:var(--text-light);fill:none" viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
      <input type="text" name="search" placeholder="Search user or reference…" value="<?php echo htmlspecialchars($search); ?>"
             style="height:38px;border:1.5px solid var(--border);border-radius:10px;background:var(--white);padding:0 12px 0 32px;font-size:.83rem;font-family:var(--font);outline:none;width:240px"
             onfocus="this.style.borderColor='var(--primary)'" onblur="this.style.borderColor='var(--border)'">
    </div>
  </form>
</div>

<div class="card">
  <?php if($withdrawals->num_rows===0): ?>
    <div style="padding:60px;text-align:center;color:var(--text-muted)">
      <p style="font-weight:700;margin-bottom:6px">No withdrawals found</p>
    </div>
  <?php else: ?>
  <div style="overflow-x:auto">
  <table class="data-table">
    <thead><tr><th>User</th><th>Amount</th><th>Reference</th><th>Transfer Code</th><th>Status</th><th>Date</th></tr></thead>
    <tbody>
    <?php while($w=$withdrawals->fetch_assoc()):
      $sc=['success'=>'badge-success','pending'=>'badge-warning','failed'=>'badge-error'];
    ?>
      <tr>
        <td>
          <div style="font-weight:600;font-size:.84rem"><?php echo htmlspecialchars($w['user_name']??'—'); ?></div>
          <div style="font-size:.7rem;color:var(--text-muted)"><?php echo htmlspecialchars($w['user_email']??''); ?></div>
        </td>
        <td style="font-weight:800;color:var(--error)">-₦<?php echo number_format($w['amount'],2); ?></td>
        <td style="font-size:.72rem;color:var(--text-muted)"><?php echo htmlspecialchars($w['reference']??'—'); ?></td>
        <td style="font-size:.72rem;color:var(--text-muted)"><?php echo htmlspecialchars($w['transfer_code']??'—'); ?></td>
        <td>
          <span class="badge <?php echo $sc[$w['status']]??'badge-muted'; ?>"><?php echo ucfirst($w['status']); ?></span>
          <?php if($w['failure_reason']): ?>
          <div style="font-size:.7rem;color:var(--error);margin-top:2px"><?php echo htmlspecialchars($w['failure_reason']); ?></div>
          <?php endif; ?>
        </td>
        <td style="font-size:.78rem;color:var(--text-muted);white-space:nowrap"><?php echo date('M j, Y g:i A', strtotime($w['created_at'])); ?></td>
      </tr>
    <?php endwhile; ?>
    </tbody>
  </table>
  </div>
  <?php endif; ?>
</div>

<?php include("includes/footer.php"); ?>
