<?php
// FILE VERSION: 2.0 - PENDING WITHDRAWALS
require_once '../config/database.php';
require_once '../includes/functions.php';
$pageTitle = 'Pending Withdrawals';
include 'side.php';
require_once 'admin_protect.php';

$conn = getConnection();

// ============================================================================
// HANDLE WITHDRAWAL ACTIONS (with PRG Pattern)
// ============================================================================
if (isset($_GET['action']) && isset($_GET['id'])) {
    $id = intval($_GET['id']);
    $action = $_GET['action'];
    
    if (!in_array($action, ['approve', 'reject'])) {
        setFlash('error', 'Invalid action.');
        redirect('withdrawals.php');
    }
    
    // Get withdrawal details
    $withdrawalStmt = $conn->prepare("
        SELECT w.*, u.username, u.email, u.country,
               c.currency_symbol, c.currency_code
        FROM withdrawals w 
        JOIN users u ON w.user_id=u.id
        LEFT JOIN countries c ON u.country = c.name
        WHERE w.id=?
    ");
    $withdrawalStmt->bind_param("i", $id);
    $withdrawalStmt->execute();
    $withdrawal = $withdrawalStmt->get_result()->fetch_assoc();
    
    if (!$withdrawal) {
        setFlash('error', 'Withdrawal request not found.');
        redirect('withdrawals.php');
    }
    
    if ($withdrawal['status'] !== 'pending') {
        setFlash('error', 'This withdrawal has already been processed.');
        redirect('withdrawals.php');
    }
    
    $currencySymbol = $withdrawal['currency_symbol'] ?? 'Ksh';
    $adminId = $_SESSION['admin_id'] ?? $_SESSION['user_id'];
    
    if ($action === 'approve') {
        $stmt = $conn->prepare("UPDATE withdrawals SET status='completed', processed_at=NOW(), processed_by=? WHERE id=? AND status='pending'");
        $stmt->bind_param("ii", $adminId, $id);
        
        if ($stmt->execute() && $stmt->affected_rows > 0) {
            @require_once "../includes/email.php";
            if (function_exists('sendWithdrawalApprovedEmail')) {
                sendWithdrawalApprovedEmail($id);
            }
            setFlash('success', 'Withdrawal #' . $id . ' approved successfully!');
        } else {
            setFlash('error', 'Failed to approve withdrawal #' . $id);
        }
        
    } elseif ($action === 'reject') {
        $conn->begin_transaction();
        
        try {
            $refunded = false;
            $walletType = $withdrawal['wallet_type'];
            
            $walletColumnMap = [
                'referral' => 'referral_wallet',
                'bonus' => 'bonus_wallet',
                'video' => 'video_wallet',
                'trivia' => 'trivia_wallet',
                'task' => 'survey_wallet',
                'ads' => 'ads_wallet',
                'blog' => 'blog_wallet'
            ];
            
            if (isset($walletColumnMap[$walletType])) {
                $walletColumn = $walletColumnMap[$walletType];
                $stmt = $conn->prepare("UPDATE wallets SET $walletColumn = $walletColumn + ? WHERE user_id = ?");
                $stmt->bind_param("di", $withdrawal['amount'], $withdrawal['user_id']);
                $refunded = $stmt->execute();
            } elseif (strpos($walletType, 'task_wallet_') !== false) {
                preg_match('/#(\d+)/', $walletType, $matches);
                if (isset($matches[1])) {
                    $taskWalletId = $matches[1];
                    $stmt = $conn->prepare("UPDATE task_wallets SET balance = balance + ? WHERE id = ? AND user_id = ?");
                    $stmt->bind_param("dii", $withdrawal['amount'], $taskWalletId, $withdrawal['user_id']);
                    $refunded = $stmt->execute();
                }
            }
            
            if (!$refunded) {
                throw new Exception('Failed to refund amount to wallet');
            }
            
            $stmt = $conn->prepare("UPDATE withdrawals SET status='rejected', processed_at=NOW(), processed_by=? WHERE id=? AND status='pending'");
            $stmt->bind_param("ii", $adminId, $id);
            
            if (!$stmt->execute() || $stmt->affected_rows === 0) {
                throw new Exception('Failed to update withdrawal status');
            }
            
            $conn->commit();
            
            @require_once "../includes/email.php";
            if (function_exists('sendWithdrawalRejectedEmail')) {
                sendWithdrawalRejectedEmail($id);
            }
            setFlash('success', 'Withdrawal #' . $id . ' rejected and refunded!');
            
        } catch (Exception $e) {
            $conn->rollback();
            setFlash('error', 'Failed to reject withdrawal: ' . $e->getMessage());
        }
    }
    
    redirect('withdrawals.php');
}

// ============================================================================
// GET FILTER PARAMETERS
// ============================================================================
$search = isset($_GET['search']) ? sanitize($_GET['search']) : '';
$wallet_type = isset($_GET['wallet_type']) ? sanitize($_GET['wallet_type']) : '';
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$perPage = 15;
$offset = ($page - 1) * $perPage;

// Build query for PENDING only
$where = "w.status = 'pending'";
$params = [];
$types = "";

if ($search) {
    $where .= " AND (u.username LIKE ? OR u.email LIKE ? OR w.phone_number LIKE ?)";
    $searchParam = "%$search%";
    $params[] = $searchParam;
    $params[] = $searchParam;
    $params[] = $searchParam;
    $types .= "sss";
}

if ($wallet_type) {
    $where .= " AND w.wallet_type = ?";
    $params[] = $wallet_type;
    $types .= "s";
}

// Get total count
$countSql = "SELECT COUNT(*) as total FROM withdrawals w JOIN users u ON w.user_id=u.id WHERE $where";
$countStmt = $conn->prepare($countSql);
if (!empty($params)) {
    $countStmt->bind_param($types, ...$params);
}
$countStmt->execute();
$total = $countStmt->get_result()->fetch_assoc()['total'];
$totalPages = ceil($total / $perPage);

// Get withdrawals
$query = "
    SELECT w.*, u.username, u.email, u.country,
           c.currency_symbol, c.currency_code
    FROM withdrawals w 
    JOIN users u ON w.user_id=u.id
    LEFT JOIN countries c ON u.country = c.name
    WHERE $where 
    ORDER BY w.requested_at ASC
    LIMIT ?, ?
";

$stmt = $conn->prepare($query);
$params[] = $offset;
$params[] = $perPage;
$types .= "ii";
$stmt->bind_param($types, ...$params);
$stmt->execute();
$withdrawals = $stmt->get_result();

// Get statistics
$stats = $conn->query("
    SELECT 
        COUNT(*) as pending_count,
        COALESCE(SUM(amount), 0) as pending_amount,
        COALESCE(SUM(net_amount), 0) as pending_net
    FROM withdrawals WHERE status='pending'
")->fetch_assoc();

// Get wallet types for filter
$walletTypes = $conn->query("SELECT DISTINCT wallet_type FROM withdrawals WHERE status='pending' ORDER BY wallet_type");
?>

<style>
.page-wrapper { padding: 16px; max-width: 1400px; margin: 0 auto; }
@media (min-width: 768px) { .page-wrapper { padding: 24px; } }

/* HEADER */
.page-header { margin-bottom: 20px; }

.header-top {
    display: flex;
    flex-direction: column;
    gap: 12px;
    margin-bottom: 16px;
}

@media (min-width: 640px) {
    .header-top {
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
    }
}

.page-title {
    font-size: 24px;
    font-weight: 800;
    color: var(--text-primary);
    display: flex;
    align-items: center;
    gap: 10px;
}

.page-title i {
    color: #f59e0b;
}

.header-actions {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}

.btn {
    padding: 10px 18px;
    border-radius: 10px;
    font-size: 13px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    border: none;
}

.btn-primary {
    background: linear-gradient(135deg, var(--theme-color) 0%, #ec4899 100%);
    color: white;
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(var(--theme-rgb), 0.4);
}

.btn-secondary {
    background: var(--card-bg);
    color: var(--text-primary);
    border: 1px solid var(--border-color);
}

.btn-secondary:hover {
    background: var(--darker-bg);
}

/* ALERT */
.alert {
    padding: 14px 18px;
    border-radius: 12px;
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 14px;
    font-weight: 500;
}

.alert-success {
    background: rgba(16, 185, 129, 0.15);
    border: 1px solid rgba(16, 185, 129, 0.3);
    color: #10b981;
}

.alert-error {
    background: rgba(239, 68, 68, 0.15);
    border: 1px solid rgba(239, 68, 68, 0.3);
    color: #ef4444;
}

/* STATS */
.stats-row {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
    margin-bottom: 20px;
}

@media (max-width: 640px) {
    .stats-row { grid-template-columns: 1fr; }
}

.stat-card {
    background: var(--card-bg);
    border: 1px solid var(--border-color);
    border-radius: 14px;
    padding: 16px;
    text-align: center;
}

.stat-card.highlight {
    background: linear-gradient(135deg, rgba(245, 158, 11, 0.1) 0%, rgba(239, 68, 68, 0.1) 100%);
    border-color: rgba(245, 158, 11, 0.3);
}

.stat-icon {
    width: 44px;
    height: 44px;
    background: linear-gradient(135deg, #f59e0b 0%, #ef4444 100%);
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 10px;
    color: white;
    font-size: 18px;
}

.stat-value {
    font-size: 26px;
    font-weight: 800;
    color: var(--text-primary);
    margin-bottom: 4px;
}

.stat-label {
    font-size: 12px;
    color: var(--text-secondary);
    font-weight: 600;
    text-transform: uppercase;
}

/* FILTERS */
.filters-card {
    background: var(--card-bg);
    border: 1px solid var(--border-color);
    border-radius: 14px;
    padding: 16px;
    margin-bottom: 20px;
}

.filters-form {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    align-items: flex-end;
}

.filter-group {
    flex: 1;
    min-width: 150px;
}

.filter-group.search-group {
    min-width: 200px;
    flex: 2;
}

.filter-label {
    display: block;
    font-size: 11px;
    font-weight: 700;
    color: var(--text-secondary);
    margin-bottom: 6px;
    text-transform: uppercase;
}

.filter-input {
    width: 100%;
    padding: 10px 14px;
    background: var(--darker-bg);
    border: 1px solid var(--border-color);
    border-radius: 10px;
    color: var(--text-primary);
    font-size: 14px;
}

.filter-input:focus {
    outline: none;
    border-color: var(--theme-color);
}

.filter-buttons {
    display: flex;
    gap: 8px;
}

/* WITHDRAWAL CARDS (Mobile First) */
.withdrawals-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.withdrawal-card {
    background: var(--card-bg);
    border: 1px solid var(--border-color);
    border-radius: 14px;
    overflow: hidden;
    transition: all 0.3s;
}

.withdrawal-card:hover {
    border-color: #f59e0b;
    box-shadow: 0 4px 16px rgba(245, 158, 11, 0.15);
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 14px 16px;
    background: var(--darker-bg);
    border-bottom: 1px solid var(--border-color);
}

.card-id {
    font-size: 14px;
    font-weight: 700;
    color: var(--text-primary);
}

.card-time {
    font-size: 12px;
    color: var(--text-secondary);
    display: flex;
    align-items: center;
    gap: 6px;
}

.card-body {
    padding: 16px;
}

.user-info {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 14px;
    padding-bottom: 14px;
    border-bottom: 1px solid var(--border-color);
}

.user-avatar {
    width: 44px;
    height: 44px;
    background: linear-gradient(135deg, var(--theme-color) 0%, #ec4899 100%);
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-weight: 700;
    font-size: 16px;
    flex-shrink: 0;
}

.user-details {
    flex: 1;
    min-width: 0;
}

.user-name {
    font-size: 15px;
    font-weight: 700;
    color: var(--text-primary);
    margin-bottom: 2px;
}

.user-email {
    font-size: 12px;
    color: var(--text-secondary);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.amount-row {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
    margin-bottom: 14px;
}

.amount-item {
    text-align: center;
    padding: 10px;
    background: var(--darker-bg);
    border-radius: 10px;
}

.amount-label {
    font-size: 10px;
    color: var(--text-secondary);
    text-transform: uppercase;
    font-weight: 600;
    margin-bottom: 4px;
}

.amount-value {
    font-size: 15px;
    font-weight: 700;
    color: var(--text-primary);
}

.amount-value.net {
    color: #10b981;
}

.detail-row {
    display: flex;
    justify-content: space-between;
    padding: 8px 0;
    border-bottom: 1px solid var(--border-color);
    font-size: 13px;
}

.detail-row:last-child {
    border-bottom: none;
}

.detail-label {
    color: var(--text-secondary);
    font-weight: 500;
}

.detail-value {
    color: var(--text-primary);
    font-weight: 600;
}

.card-actions {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 10px;
    padding: 14px 16px;
    background: var(--darker-bg);
    border-top: 1px solid var(--border-color);
}

.btn-approve {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: white;
    justify-content: center;
}

.btn-approve:hover {
    box-shadow: 0 4px 16px rgba(16, 185, 129, 0.4);
}

.btn-reject {
    background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
    color: white;
    justify-content: center;
}

.btn-reject:hover {
    box-shadow: 0 4px 16px rgba(239, 68, 68, 0.4);
}

/* EMPTY STATE */
.empty-state {
    text-align: center;
    padding: 60px 20px;
    background: var(--card-bg);
    border: 1px solid var(--border-color);
    border-radius: 14px;
}

.empty-icon {
    font-size: 64px;
    color: #10b981;
    margin-bottom: 16px;
    opacity: 0.5;
}

.empty-title {
    font-size: 20px;
    font-weight: 700;
    color: var(--text-primary);
    margin-bottom: 8px;
}

.empty-text {
    color: var(--text-secondary);
    font-size: 14px;
}

/* PAGINATION */
.pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 8px;
    margin-top: 24px;
    flex-wrap: wrap;
}

.page-btn {
    padding: 10px 14px;
    background: var(--card-bg);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    color: var(--text-primary);
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
    text-decoration: none;
}

.page-btn:hover {
    background: var(--darker-bg);
}

.page-btn.active {
    background: linear-gradient(135deg, var(--theme-color) 0%, #ec4899 100%);
    color: white;
    border-color: transparent;
}

/* Desktop Table View */
@media (min-width: 1024px) {
    .withdrawals-list { display: none; }
    .withdrawals-table-container { display: block; }
}

@media (max-width: 1023px) {
    .withdrawals-list { display: flex; }
    .withdrawals-table-container { display: none; }
}

.withdrawals-table-container {
    background: var(--card-bg);
    border: 1px solid var(--border-color);
    border-radius: 14px;
    overflow: hidden;
}

.table-wrapper { overflow-x: auto; }

.withdrawals-table {
    width: 100%;
    border-collapse: collapse;
}

.withdrawals-table th {
    padding: 14px 16px;
    text-align: left;
    font-size: 11px;
    font-weight: 700;
    color: var(--text-secondary);
    text-transform: uppercase;
    background: var(--darker-bg);
    border-bottom: 1px solid var(--border-color);
}

.withdrawals-table td {
    padding: 14px 16px;
    font-size: 14px;
    color: var(--text-primary);
    border-bottom: 1px solid var(--border-color);
}

.withdrawals-table tbody tr:hover {
    background: var(--darker-bg);
}

.table-actions {
    display: flex;
    gap: 8px;
}

.btn-sm {
    padding: 8px 14px;
    font-size: 12px;
}
</style>

<div class="page-wrapper">
    
    <?php $flash = getFlash(); if ($flash): ?>
        <div class="alert alert-<?php echo $flash['type']; ?>">
            <i class="fas fa-<?php echo $flash['type'] === 'success' ? 'check-circle' : 'exclamation-circle'; ?>"></i>
            <?php echo $flash['message']; ?>
        </div>
    <?php endif; ?>
    
    <!-- Header -->
    <div class="page-header">
        <div class="header-top">
            <h1 class="page-title">
                <i class="fas fa-clock"></i> Pending Withdrawals
            </h1>
            <div class="header-actions">
                <a href="withdrawal_history.php" class="btn btn-secondary">
                    <i class="fas fa-history"></i> View History
                </a>
                <a href="wallet_withdrawal_settings.php" class="btn btn-primary">
                    <i class="fas fa-cog"></i> Settings
                </a>
            </div>
        </div>
    </div>
    
    <!-- Stats -->
    <div class="stats-row">
        <div class="stat-card highlight">
            <div class="stat-icon"><i class="fas fa-hourglass-half"></i></div>
            <div class="stat-value"><?php echo number_format($stats['pending_count']); ?></div>
            <div class="stat-label">Pending Requests</div>
        </div>
        <div class="stat-card">
            <div class="stat-icon"><i class="fas fa-coins"></i></div>
            <div class="stat-value">Ksh <?php echo number_format($stats['pending_amount'], 0); ?></div>
            <div class="stat-label">Total Requested</div>
        </div>
        <div class="stat-card">
            <div class="stat-icon"><i class="fas fa-hand-holding-usd"></i></div>
            <div class="stat-value">Ksh <?php echo number_format($stats['pending_net'], 0); ?></div>
            <div class="stat-label">Net to Pay</div>
        </div>
    </div>
    
    <!-- Filters -->
    <div class="filters-card">
        <form method="GET" class="filters-form">
            <div class="filter-group search-group">
                <label class="filter-label">Search</label>
                <input type="text" name="search" class="filter-input" placeholder="Username, email, phone..." value="<?php echo htmlspecialchars($search); ?>">
            </div>
            <div class="filter-group">
                <label class="filter-label">Wallet Type</label>
                <select name="wallet_type" class="filter-input">
                    <option value="">All Wallets</option>
                    <?php while ($wt = $walletTypes->fetch_assoc()): ?>
                        <option value="<?php echo htmlspecialchars($wt['wallet_type']); ?>" <?php echo $wallet_type === $wt['wallet_type'] ? 'selected' : ''; ?>>
                            <?php echo ucfirst($wt['wallet_type']); ?>
                        </option>
                    <?php endwhile; ?>
                </select>
            </div>
            <div class="filter-buttons">
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-search"></i> Filter
                </button>
                <a href="pending_withdrawals.php" class="btn btn-secondary">
                    <i class="fas fa-redo"></i>
                </a>
            </div>
        </form>
    </div>
    
    <?php if ($withdrawals->num_rows > 0): ?>
        
        <!-- Mobile Card View -->
        <div class="withdrawals-list">
            <?php while ($w = $withdrawals->fetch_assoc()): 
                $currency = $w['currency_symbol'] ?? 'Ksh';
            ?>
            <div class="withdrawal-card">
                <div class="card-header">
                    <span class="card-id">#<?php echo $w['id']; ?></span>
                    <span class="card-time">
                        <i class="far fa-clock"></i>
                        <?php echo date('M j, g:i A', strtotime($w['requested_at'])); ?>
                    </span>
                </div>
                <div class="card-body">
                    <div class="user-info">
                        <div class="user-avatar">
                            <?php echo strtoupper(substr($w['username'], 0, 1)); ?>
                        </div>
                        <div class="user-details">
                            <div class="user-name"><?php echo htmlspecialchars($w['username']); ?></div>
                            <div class="user-email"><?php echo htmlspecialchars($w['email']); ?></div>
                        </div>
                    </div>
                    
                    <div class="amount-row">
                        <div class="amount-item">
                            <div class="amount-label">Amount</div>
                            <div class="amount-value"><?php echo $currency; ?> <?php echo number_format($w['amount'], 0); ?></div>
                        </div>
                        <div class="amount-item">
                            <div class="amount-label">Fee</div>
                            <div class="amount-value"><?php echo $currency; ?> <?php echo number_format($w['fee'], 0); ?></div>
                        </div>
                        <div class="amount-item">
                            <div class="amount-label">Net</div>
                            <div class="amount-value net"><?php echo $currency; ?> <?php echo number_format($w['net_amount'], 0); ?></div>
                        </div>
                    </div>
                    
                    <div class="detail-row">
                        <span class="detail-label">Phone</span>
                        <span class="detail-value"><?php echo htmlspecialchars($w['phone_number']); ?></span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">Wallet</span>
                        <span class="detail-value"><?php echo ucfirst($w['wallet_type']); ?></span>
                    </div>
                </div>
                <div class="card-actions">
                    <a href="?action=approve&id=<?php echo $w['id']; ?>" class="btn btn-approve" onclick="return confirm('Approve withdrawal of <?php echo $currency; ?> <?php echo number_format($w['net_amount'], 2); ?> to <?php echo htmlspecialchars($w['username']); ?>?')">
                        <i class="fas fa-check"></i> Approve
                    </a>
                    <a href="?action=reject&id=<?php echo $w['id']; ?>" class="btn btn-reject" onclick="return confirm('Reject and refund <?php echo $currency; ?> <?php echo number_format($w['amount'], 2); ?> to <?php echo htmlspecialchars($w['username']); ?>?')">
                        <i class="fas fa-times"></i> Reject
                    </a>
                </div>
            </div>
            <?php endwhile; ?>
        </div>
        
        <!-- Desktop Table View -->
        <?php $withdrawals->data_seek(0); ?>
        <div class="withdrawals-table-container">
            <div class="table-wrapper">
                <table class="withdrawals-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>User</th>
                            <th>Amount</th>
                            <th>Fee</th>
                            <th>Net Amount</th>
                            <th>Phone</th>
                            <th>Wallet</th>
                            <th>Requested</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($w = $withdrawals->fetch_assoc()): 
                            $currency = $w['currency_symbol'] ?? 'Ksh';
                        ?>
                        <tr>
                            <td><strong>#<?php echo $w['id']; ?></strong></td>
                            <td>
                                <strong><?php echo htmlspecialchars($w['username']); ?></strong><br>
                                <small style="color: var(--text-secondary);"><?php echo htmlspecialchars($w['email']); ?></small>
                            </td>
                            <td><?php echo $currency; ?> <?php echo number_format($w['amount'], 2); ?></td>
                            <td><?php echo $currency; ?> <?php echo number_format($w['fee'], 2); ?></td>
                            <td><strong style="color: #10b981;"><?php echo $currency; ?> <?php echo number_format($w['net_amount'], 2); ?></strong></td>
                            <td><?php echo htmlspecialchars($w['phone_number']); ?></td>
                            <td><?php echo ucfirst($w['wallet_type']); ?></td>
                            <td><?php echo date('M j, g:i A', strtotime($w['requested_at'])); ?></td>
                            <td>
                                <div class="table-actions">
                                    <a href="?action=approve&id=<?php echo $w['id']; ?>" class="btn btn-approve btn-sm" onclick="return confirm('Approve this withdrawal?')">
                                        <i class="fas fa-check"></i> Approve
                                    </a>
                                    <a href="?action=reject&id=<?php echo $w['id']; ?>" class="btn btn-reject btn-sm" onclick="return confirm('Reject and refund?')">
                                        <i class="fas fa-times"></i> Reject
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
        
        <!-- Pagination -->
        <?php if ($totalPages > 1): ?>
        <div class="pagination">
            <?php if ($page > 1): ?>
                <a href="?page=<?php echo $page-1; ?>&search=<?php echo urlencode($search); ?>&wallet_type=<?php echo urlencode($wallet_type); ?>" class="page-btn">
                    <i class="fas fa-chevron-left"></i>
                </a>
            <?php endif; ?>
            
            <?php for ($i = max(1, $page-2); $i <= min($totalPages, $page+2); $i++): ?>
                <a href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&wallet_type=<?php echo urlencode($wallet_type); ?>" class="page-btn <?php echo $i === $page ? 'active' : ''; ?>">
                    <?php echo $i; ?>
                </a>
            <?php endfor; ?>
            
            <?php if ($page < $totalPages): ?>
                <a href="?page=<?php echo $page+1; ?>&search=<?php echo urlencode($search); ?>&wallet_type=<?php echo urlencode($wallet_type); ?>" class="page-btn">
                    <i class="fas fa-chevron-right"></i>
                </a>
            <?php endif; ?>
        </div>
        <?php endif; ?>
        
    <?php else: ?>
        <div class="empty-state">
            <div class="empty-icon"><i class="fas fa-check-circle"></i></div>
            <div class="empty-title">All Caught Up!</div>
            <div class="empty-text">No pending withdrawal requests at the moment.</div>
        </div>
    <?php endif; ?>
    
</div>

<?php include 'footer.php'; ?>