<style>
    .transactions-hero {
        background: linear-gradient(135deg, #0ea5e9, #2563eb);
        border-radius: 20px;
        color: #fff;
        padding: 32px 36px;
        box-shadow: 0 20px 40px rgba(37, 99, 235, 0.25);
        margin-bottom: 28px;
        position: relative;
        overflow: hidden;
    }
    .transactions-hero::after {
        content: "";
        position: absolute;
        inset: 0;
        background: radial-gradient(circle at top right, rgba(255,255,255,0.4), transparent 55%);
        opacity: 0.4;
    }
    .transactions-hero h1 {
        font-size: 1.875rem;
        font-weight: 700;
        margin-bottom: 4px;
    }
    .transactions-hero p {
        margin: 0;
        font-size: 1rem;
        opacity: 0.86;
    }
    .transactions-stats .card {
        border: none;
        border-radius: 18px;
        box-shadow: 0 12px 24px rgba(15, 23, 42, 0.06);
        transition: transform 0.25s ease, box-shadow 0.25s ease;
    }
    .transactions-stats .card:hover {
        transform: translateY(-4px);
        box-shadow: 0 18px 32px rgba(15, 23, 42, 0.12);
    }
    .transactions-stats .metric-label {
        font-size: 0.875rem;
        text-transform: uppercase;
        letter-spacing: 0.08em;
        color: #64748b;
        margin-bottom: 6px;
    }
    .transactions-stats .metric-value {
        font-size: 1.75rem;
        font-weight: 700;
        color: #0f172a;
    }
    .transactions-stats .metric-subtext {
        font-size: 0.875rem;
        color: #94a3b8;
        margin-top: 4px;
    }
    .filter-card {
        border: none;
        border-radius: 18px;
        box-shadow: 0 10px 24px rgba(15, 23, 42, 0.05);
        margin-bottom: 28px;
    }
    .filter-card .form-label {
        font-weight: 600;
        color: #0f172a;
    }
    .filter-card .form-select,
    .filter-card .form-control {
        border-radius: 14px;
        border-color: #e2e8f0;
        padding: 10px 14px;
        box-shadow: none;
    }
    .filter-card .form-select:focus,
    .filter-card .form-control:focus {
        border-color: #2563eb;
        box-shadow: 0 0 0 0.2rem rgba(37, 99, 235, 0.15);
    }
    .table-card {
        border: none;
        border-radius: 18px;
        box-shadow: 0 16px 32px rgba(15, 23, 42, 0.08);
    }
    .table thead th {
        text-transform: uppercase;
        letter-spacing: 0.05em;
        font-size: 0.75rem;
        border-bottom: 1px solid #e2e8f0;
        color: #475569;
        background-color: #f8fafc;
    }
    .table tbody td {
        vertical-align: middle;
        color: #1e293b;
    }
    .badge {
        padding: 0.5rem 0.85rem;
        border-radius: 999px;
        font-weight: 600;
    }
    .dropdown-toggle-btn {
        border: 1px solid #e2e8f0;
        border-radius: 12px;
        padding: 8px 14px;
        font-weight: 600;
        color: #0f172a;
        display: inline-flex;
        align-items: center;
        gap: 6px;
        background-color: #fff;
    }
    .dropdown-toggle-btn:hover {
        background-color: #eff6ff;
        color: #1d4ed8;
    }
    .empty-state {
        padding: 48px 0;
        text-align: center;
        color: #64748b;
        font-size: 1rem;
    }
    .latest-pill {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 6px 12px;
        border-radius: 999px;
        background: rgba(255,255,255,0.25);
        color: rgba(255,255,255,0.95);
        font-size: 0.875rem;
        font-weight: 600;
    }
    @media (max-width: 767.98px) {
        .transactions-hero {
            padding: 24px;
        }
        .transactions-hero h1 {
            font-size: 1.5rem;
        }
        .transactions-stats .metric-value {
            font-size: 1.5rem;
        }
        .dropdown-toggle-btn {
            width: 100%;
            justify-content: center;
        }
    }
</style>

<!--start main wrapper-->
<main class="main-wrapper">
    <div class="main-content">
        <section class="transactions-hero">
            <div class="d-flex flex-column flex-lg-row align-items-lg-center justify-content-between position-relative">
                <div>
                    <h1>Withdrawal Transactions</h1>
                    <p>Monitor, approve, or reject payout requests with confidence.</p>
                </div>
                <div class="mt-3 mt-lg-0 latest-pill">
                    <i class="bi bi-clock-history"></i>
                    <span>
                        Last request:
                        <?php if (!empty($withdrawalStats['latestRequest'])): ?>
                            <?= date('d M Y, h:i A', $withdrawalStats['latestRequest'] / 1000); ?>
                        <?php else: ?>
                            No data yet
                        <?php endif; ?>
                    </span>
                </div>
            </div>
        </section>

        <div class="transactions-stats">
            <div class="row g-3">
                <div class="col-md-3">
                    <div class="card h-100">
                        <div class="card-body">
                            <div class="metric-label">Total Requests</div>
                            <div class="metric-value"><?= number_format($withdrawalStats['total']); ?></div>
                            <div class="metric-subtext">Across all statuses</div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card h-100">
                        <div class="card-body">
                            <div class="metric-label">Pending</div>
                            <div class="metric-value text-warning"><?= number_format($withdrawalStats['pending']); ?></div>
                            <div class="metric-subtext">Awaiting your action</div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card h-100">
                        <div class="card-body">
                            <div class="metric-label">Approved</div>
                            <div class="metric-value text-success"><?= number_format($withdrawalStats['approved']); ?></div>
                            <div class="metric-subtext">Completed payouts</div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card h-100">
                        <div class="card-body">
                            <div class="metric-label">Total Volume</div>
                            <div class="metric-value"><?= '$' . number_format($withdrawalStats['totalAmount'], 2); ?></div>
                            <div class="metric-subtext">
                                Avg. <?= '$' . number_format($withdrawalStats['averageAmount'], 2); ?> per request
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="card filter-card">
            <div class="card-body">
                <div class="row g-3 align-items-end">
                    <div class="col-md-4">
                        <label for="statusFilter" class="form-label">Status</label>
                        <select id="statusFilter" class="form-select">
                            <option value="All" selected>All statuses</option>
                            <option value="pending">Pending</option>
                            <option value="approved">Approved</option>
                            <option value="rejected">Rejected</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label for="dateFilter" class="form-label">Submitted On</label>
                        <input type="date" id="dateFilter" class="form-control" placeholder="Select date">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label d-block">Notifications</label>
                        <div class="form-check form-switch ps-0 d-flex align-items-center gap-2">
                            <input class="form-check-input ms-0" type="checkbox" role="switch" id="sendNotifications" checked>
                            <label class="form-check-label fw-semibold" for="sendNotifications">Send approval alerts</label>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="card table-card">
            <div class="card-body p-0">
                <div class="d-flex align-items-center justify-content-between px-4 py-3 border-bottom">
                    <div>
                        <h5 class="mb-0 fw-semibold text-dark">Withdrawal Queue</h5>
                        <small class="text-muted">Review the latest payout activity from your creators.</small>
                    </div>
                    <div class="dropdown">
                        <button class="dropdown-toggle-btn" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="bi bi-funnel"></i> Quick Filters
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><button class="dropdown-item quick-filter" data-filter="pending">Pending only</button></li>
                            <li><button class="dropdown-item quick-filter" data-filter="approved">Approved only</button></li>
                            <li><button class="dropdown-item quick-filter" data-filter="rejected">Rejected only</button></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><button class="dropdown-item quick-filter" data-filter="All">Reset filters</button></li>
                        </ul>
                    </div>
                </div>
                <div class="table-responsive">
                    <table class="table table-hover mb-0" id="withdrawalsTable">
                        <thead>
                            <tr>
                                <th scope="col">Transaction ID</th>
                                <th scope="col">User</th>
                                <th scope="col">Current Earning</th>
                                <th scope="col">Email</th>
                                <th scope="col">Account Info</th>
                                <th scope="col">Status</th>
                                <th scope="col">Amount</th>
                                <th scope="col">Requested</th>
                                <th scope="col">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($withdrawals)): ?>
                                <?php foreach ($withdrawals as $id => $withdrawal): ?>
                                    <?php
                                        $status = isset($withdrawal['status']) ? strtolower($withdrawal['status']) : 'pending';
                                        $badgeClass = 'bg-warning';
                                        if ($status === 'approved') $badgeClass = 'bg-success';
                                        if ($status === 'rejected') $badgeClass = 'bg-danger';
                                    ?>
                                    <tr data-id="<?= $id; ?>" data-status="<?= $status; ?>">
                                        <td class="fw-semibold text-primary"><?= $id; ?></td>
                                        <td><?= !empty($withdrawal['userName']) ? htmlspecialchars($withdrawal['userName']) : 'N/A'; ?></td>
                                        <td><?= !empty($withdrawal['currentEarning']) ? '$' . number_format((float)$withdrawal['currentEarning'], 2) : 'N/A'; ?></td>
                                        <td><?= !empty($withdrawal['userEmail']) ? htmlspecialchars($withdrawal['userEmail']) : (!empty($withdrawal['email']) ? htmlspecialchars($withdrawal['email']) : 'N/A'); ?></td>
                                        <td>
                                            
                                          <?php if($withdrawal['type'] == 'ach'): ?>
                                            Type: <b>ACH</b><br>
                                            Routing Number: <?= !empty($withdrawal['routeNumber']) ? htmlspecialchars($withdrawal['routeNumber']) : 'N/A'; ?><br>
                                                Account Number: <?= !empty($withdrawal['accountNumber']) ? htmlspecialchars($withdrawal['accountNumber']) : 'N/A'; ?><br>
                                                Account Email: <?= !empty($withdrawal['email']) ? htmlspecialchars($withdrawal['email']) : 'N/A'; ?>
                                            <?php elseif($withdrawal['type'] == 'paypal' || $withdrawal['type'] == 'payoneer'): ?>
                                               Type:<b> <?= !empty($withdrawal['type']) ? ucfirst($withdrawal['type']) : 'N/A'; ?></b><br>
                                                Email: <?= !empty($withdrawal['email']) ? htmlspecialchars($withdrawal['email']) : 'N/A'; ?>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="badge <?= $badgeClass; ?>">
                                                <?= ucfirst($status); ?>
                                            </span>
                                        </td>
                                        <td><?= '$' . number_format(isset($withdrawal['amount']) ? (float)$withdrawal['amount'] : 0, 2); ?></td>
                                        <td>
                                            <?php if (!empty($withdrawal['createdAtMs'])): ?>
                                                <?= date('d M Y, h:i A', $withdrawal['createdAtMs'] / 1000); ?>
                                            <?php else: ?>
                                                N/A
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($status === 'pending'): ?>
                                                <div class="dropdown">
                                                    <button class="btn btn-light border rounded-3 px-3 py-2" type="button" id="dropdownMenuButton<?= $id; ?>" data-bs-toggle="dropdown" aria-expanded="false">
                                                        <i class="bi bi-three-dots"></i>
                                                    </button>
                                                    <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="dropdownMenuButton<?= $id; ?>">
                                                        <li>
                                                            <a class="dropdown-item approve-btn" href="javascript:void(0)" data-id="<?= $id; ?>" data-amount="<?= isset($withdrawal['amount']) ? (float)$withdrawal['amount'] : 0; ?>">
                                                                <i class="bi bi-check-circle text-success me-2"></i>Approve
                                                            </a>
                                                        </li>
                                                        <li>
                                                            <a class="dropdown-item reject-btn" href="javascript:void(0)" data-id="<?= $id; ?>" data-amount="<?= isset($withdrawal['amount']) ? (float)$withdrawal['amount'] : 0; ?>">
                                                                <i class="bi bi-x-circle text-danger me-2"></i>Reject
                                                            </a>
                                                        </li>
                                                    </ul>
                                                </div>
                                            <?php else: ?>
                                                <span class="text-muted fw-semibold">Processed</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="9">
                                        <div class="empty-state">
                                            <i class="bi bi-inbox-fill fs-2 mb-3 d-block text-primary"></i>
                                            No withdrawal requests found
                                        </div>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</main>
<!--end main wrapper-->

<!-- Reject Reason Modal -->
<div class="modal fade" id="rejectModal" tabindex="-1" aria-labelledby="rejectModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 rounded-4 shadow-lg">
            <div class="modal-header border-0">
                <div>
                    <h5 class="modal-title fw-bold">Reject Withdrawal</h5>
                    <p class="text-muted mb-0">Share a short note so the creator understands why it was declined.</p>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label for="rejectReason" class="form-label fw-semibold">Rejection reason (optional)</label>
                    <textarea class="form-control rounded-4" id="rejectReason" rows="3" placeholder="Add a helpful message..."></textarea>
                </div>
            </div>
            <div class="modal-footer border-0 d-flex justify-content-between">
                <button type="button" class="btn btn-light border rounded-4 px-4" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger rounded-4 px-4" id="confirmReject">Reject withdrawal</button>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function () {
        let currentWithdrawalId = null;
        const currencyFormatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });

        const badgePalette = {
            approved: 'bg-success',
            rejected: 'bg-danger',
            pending: 'bg-warning',
        };

        $('.quick-filter').on('click', function () {
            const status = $(this).data('filter');
            $('#statusFilter').val(status);
            filterWithdrawals();
        });

        $('#statusFilter, #dateFilter').on('change', function () {
            filterWithdrawals();
        });

        function filterWithdrawals() {
            const status = $('#statusFilter').val();
            const date = $('#dateFilter').val();

            Swal.fire({
                title: 'Refreshing data',
                html: '<p class="mb-0 text-muted">Pulling the latest withdrawal requests…</p>',
                allowOutsideClick: false,
                allowEscapeKey: false,
                showConfirmButton: false,
                didOpen: () => Swal.showLoading(),
            });

            $.ajax({
                url: '<?= base_url('transaction/getWithdrawalsByStatus'); ?>',
                type: 'POST',
                data: { status: status, date: date },
                dataType: 'json',
                success: function (response) {
                    Swal.close();
                    if (response.status) {
                        updateTable(response.data || []);
                    } else {
                        Swal.fire({
                            icon: 'info',
                            title: 'No results',
                            text: response.message || 'No withdrawals matched your filters.',
                            confirmButtonColor: '#2563eb',
                        });
                        updateTable([]);
                    }
                },
                error: function () {
                    Swal.fire({
                        icon: 'error',
                        title: 'Something went wrong',
                        text: 'We could not refresh the withdrawals. Please try again.',
                        confirmButtonColor: '#dc2626',
                    });
                },
            });
        }

        function updateTable(withdrawals) {
            const tbody = $('#withdrawalsTable tbody');
            tbody.empty();

            if (!withdrawals || withdrawals.length === 0) {
                tbody.append(`
                    <tr>
                        <td colspan="9">
                            <div class="empty-state">
                                <i class="bi bi-inbox-fill fs-2 mb-3 d-block text-primary"></i>
                                No withdrawal requests found
                            </div>
                        </td>
                    </tr>
                `);
                return;
            }

            withdrawals.forEach(function (withdrawal) {
                const status = (withdrawal.status || 'pending').toLowerCase();
                const badgeClass = badgePalette[status] || 'bg-secondary';
                const dateValue = withdrawal.createdAtMs ? new Date(withdrawal.createdAtMs) : null;
                const formattedDate = dateValue ? dateValue.toLocaleString() : 'N/A';
                const formattedAmount = currencyFormatter.format(parseFloat(withdrawal.amount || 0));
                const currentEarning = currencyFormatter.format(parseFloat(withdrawal.currentEarning || 0));

                let actionsHtml = '<span class="text-muted fw-semibold">Processed</span>';
                if (status === 'pending') {
                    actionsHtml = `
                        <div class="dropdown">
                            <button class="btn btn-light border rounded-3 px-3 py-2" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                                <i class="bi bi-three-dots"></i>
                            </button>
                            <ul class="dropdown-menu dropdown-menu-end">
                                <li>
                                    <a class="dropdown-item approve-btn" href="javascript:void(0)" data-id="${withdrawal.id}" data-amount="${withdrawal.amount}">
                                        <i class="bi bi-check-circle text-success me-2"></i>Approve
                                    </a>
                                </li>
                                <li>
                                    <a class="dropdown-item reject-btn" href="javascript:void(0)" data-id="${withdrawal.id}" data-amount="${withdrawal.amount}">
                                        <i class="bi bi-x-circle text-danger me-2"></i>Reject
                                    </a>
                                </li>
                            </ul>
                        </div>
                    `;
                }

                const row = `
                    <tr data-id="${withdrawal.id || ''}" data-status="${status}">
                        <td class="fw-semibold text-primary">${withdrawal.id || 'N/A'}</td>
                        <td>${withdrawal.userName || 'N/A'}</td>
                        <td>${currentEarning}</td>
                        <td>${withdrawal.userEmail || withdrawal.email || 'N/A'}</td>
                        <td>${withdrawal.accountNumber || 'N/A'}</td>
                        <td><span class="badge ${badgeClass}">${status.charAt(0).toUpperCase() + status.slice(1)}</span></td>
                        <td>${formattedAmount}</td>
                        <td>${formattedDate}</td>
                        <td>${actionsHtml}</td>
                    </tr>
                `;

                tbody.append(row);
            });
        }

        $(document).on('click', '.approve-btn', function () {
            const withdrawalId = $(this).data('id');
            const amount = $(this).data('amount');

            Swal.fire({
                title: 'Approve withdrawal?',
                text: `Approve this payout of ${currencyFormatter.format(parseFloat(amount || 0))}?`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#16a34a',
                cancelButtonColor: '#64748b',
                confirmButtonText: 'Yes, approve it',
            }).then((result) => {
                if (result.isConfirmed) {
                    Swal.fire({
                        title: 'Processing request',
                        html: '<p class="mb-0 text-muted">Notifying the creator and marking the request as paid…</p>',
                        allowOutsideClick: false,
                        allowEscapeKey: false,
                        showConfirmButton: false,
                        didOpen: () => Swal.showLoading(),
                    });

                    $.ajax({
                        url: '<?= base_url('transaction/approveWithdrawal'); ?>',
                        type: 'POST',
                        data: { withdrawalId: withdrawalId },
                        dataType: 'json',
                        success: function (response) {
                            if (response.status) {
                                Swal.fire({
                                    icon: 'success',
                                    title: 'Withdrawal approved',
                                    text: response.message || 'The creator has been notified.',
                                    confirmButtonColor: '#16a34a',
                                }).then(() => location.reload());
                            } else {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Action failed',
                                    text: response.message || 'Unable to approve this withdrawal.',
                                    confirmButtonColor: '#dc2626',
                                });
                            }
                        },
                        error: function () {
                            Swal.fire({
                                icon: 'error',
                                title: 'Network error',
                                text: 'Please try again in a moment.',
                                confirmButtonColor: '#dc2626',
                            });
                        },
                    });
                }
            });
        });

        $(document).on('click', '.reject-btn', function () {
            currentWithdrawalId = $(this).data('id');
            $('#rejectReason').val('');
            $('#rejectModal').modal('show');
        });

        $('#confirmReject').on('click', function () {
            if (!currentWithdrawalId) {
                return;
            }

            const reason = $('#rejectReason').val();
            $('#rejectModal').modal('hide');

            Swal.fire({
                title: 'Processing rejection',
                html: '<p class="mb-0 text-muted">Updating the creator and saving your reason…</p>',
                allowOutsideClick: false,
                allowEscapeKey: false,
                showConfirmButton: false,
                didOpen: () => Swal.showLoading(),
            });

            $.ajax({
                url: '<?= base_url('transaction/rejectWithdrawal'); ?>',
                type: 'POST',
                data: { withdrawalId: currentWithdrawalId, reason: reason },
                dataType: 'json',
                success: function (response) {
                    if (response.status) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Withdrawal rejected',
                            text: response.message || 'The creator has been informed.',
                            confirmButtonColor: '#dc2626',
                        }).then(() => location.reload());
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Action failed',
                            text: response.message || 'Unable to reject this withdrawal.',
                            confirmButtonColor: '#dc2626',
                        });
                    }
                },
                error: function () {
                    Swal.fire({
                        icon: 'error',
                        title: 'Network error',
                        text: 'Please try again in a moment.',
                        confirmButtonColor: '#dc2626',
                    });
                },
            });
        });
    });
</script>
