<?php
$pageTitle = 'Withdrawal Requests';
ob_start();
?>

<div class="admin-card">
    <div class="flex justify-between items-center mb-6">
        <div>
            <h2 class="text-xl font-semibold mb-2">Withdrawal Requests</h2>
            <p class="text-gray-300">Manage user withdrawal requests and payouts.</p>
        </div>
        <a href="/admin/points-system" class="admin-button secondary">
            <i class="fas fa-cog mr-2"></i> Points Settings
        </a>
    </div>

    <!-- Filter Tabs -->
    <div class="mb-6">
        <div class="border-b border-gray-800">
            <nav class="-mb-px flex space-x-8">
                <a href="/admin/withdrawal-requests" class="<?= !isset($_GET['status']) ? 'border-primary text-primary' : 'border-transparent text-gray-400 hover:text-white hover:border-gray-300' ?> whitespace-nowrap py-2 px-1 border-b-2 font-medium text-sm">
                    All Requests
                </a>
                <a href="/admin/withdrawal-requests?status=pending" class="<?= ($_GET['status'] ?? '') === 'pending' ? 'border-primary text-primary' : 'border-transparent text-gray-400 hover:text-white hover:border-gray-300' ?> whitespace-nowrap py-2 px-1 border-b-2 font-medium text-sm">
                    Pending
                </a>
                <a href="/admin/withdrawal-requests?status=approved" class="<?= ($_GET['status'] ?? '') === 'approved' ? 'border-primary text-primary' : 'border-transparent text-gray-400 hover:text-white hover:border-gray-300' ?> whitespace-nowrap py-2 px-1 border-b-2 font-medium text-sm">
                    Approved
                </a>
                <a href="/admin/withdrawal-requests?status=rejected" class="<?= ($_GET['status'] ?? '') === 'rejected' ? 'border-primary text-primary' : 'border-transparent text-gray-400 hover:text-white hover:border-gray-300' ?> whitespace-nowrap py-2 px-1 border-b-2 font-medium text-sm">
                    Rejected
                </a>
            </nav>
        </div>
    </div>

    <!-- Search Bar -->
    <div class="mb-6">
        <form method="GET" class="flex gap-4">
            <?php if (isset($_GET['status'])): ?>
                <input type="hidden" name="status" value="<?php echo htmlspecialchars($_GET['status']); ?>">
            <?php endif; ?>
            <div class="flex-1">
                <input type="text" name="search" placeholder="Search by username, email, or payment method..." 
                       value="<?php echo htmlspecialchars($_GET['search'] ?? ''); ?>"
                       class="w-full px-4 py-2 bg-darker border border-gray-800 rounded-md text-white placeholder-gray-500 focus:border-primary focus:ring-1 focus:ring-primary transition-colors">
            </div>
            <button type="submit" class="admin-button">
                <i class="fas fa-search mr-2"></i>Search
            </button>
            <?php if (!empty($_GET['search'])): ?>
                <a href="?<?php echo isset($_GET['status']) ? 'status=' . urlencode($_GET['status']) : ''; ?>" 
                   class="admin-button secondary">
                    <i class="fas fa-times mr-2"></i>Clear
                </a>
            <?php endif; ?>
        </form>
    </div>

    <?php if (empty($withdrawalRequests)): ?>
        <div class="text-center py-12">
            <i class="fas fa-money-bill-wave text-4xl text-gray-600 mb-4"></i>
            <h3 class="text-lg font-medium text-gray-400 mb-2">No withdrawal requests found</h3>
            <p class="text-gray-500">Withdrawal requests will appear here when users submit them.</p>
        </div>
    <?php else: ?>
        <div class="overflow-x-auto">
            <table class="admin-table">
                <thead>
                    <tr>
                        <th>User</th>
                        <th>Amount</th>
                        <th>USD Value</th>
                        <th>Payment Method</th>
                        <th>Status</th>
                        <th>Date</th>
                        <th>Actions</th>
                        <th>Delete</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($withdrawalRequests as $request): ?>
                        <tr>
                            <td>
                                <div>
                                    <div class="font-medium"><?= htmlspecialchars($request['username']) ?></div>
                                    <div class="text-sm text-gray-400"><?= htmlspecialchars($request['email']) ?></div>
                                </div>
                            </td>
                            <td>
                                <span class="font-mono"><?= number_format($request['amount']) ?> points</span>
                            </td>
                            <td>
                                <span class="font-mono text-green-400">$<?= number_format($request['amount'] / ($settings['withdrawal_rate'] ?? 100), 2) ?></span>
                            </td>
                            <td>
                                <div>
                                    <div class="font-medium"><?= htmlspecialchars($request['payment_method']) ?></div>
                                    <div class="text-sm text-gray-400 max-w-xs truncate"><?= htmlspecialchars($request['payment_details']) ?></div>
                                </div>
                            </td>
                            <td>
                                <span class="status-badge status-<?= $request['status'] ?>">
                                    <?= ucfirst($request['status']) ?>
                                </span>
                            </td>
                            <td>
                                <div class="text-sm">
                                    <div><?= date('M j, Y', strtotime($request['created_at'])) ?></div>
                                    <div class="text-gray-400"><?= date('g:i A', strtotime($request['created_at'])) ?></div>
                                </div>
                            </td>
                            <td>
                                <?php if ($request['status'] === 'pending'): ?>
                                    <div class="flex gap-2">
                                        <button onclick="updateWithdrawalStatus(<?= $request['id'] ?>, 'approved')" 
                                                class="admin-button small success" title="Approve">
                                            <i class="fas fa-check"></i>
                                        </button>
                                        <button onclick="updateWithdrawalStatus(<?= $request['id'] ?>, 'rejected')" 
                                                class="admin-button small danger" title="Reject">
                                            <i class="fas fa-times"></i>
                                        </button>
                                        <button onclick="viewWithdrawalDetails(<?= $request['id'] ?>)" 
                                                class="admin-button small" title="View Details">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                    </div>
                                <?php else: ?>
                                    <button onclick="viewWithdrawalDetails(<?= $request['id'] ?>)" 
                                            class="admin-button small" title="View Details">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                <?php endif; ?>
                            </td>
                            <td>
                                <button onclick="deleteWithdrawalRequest(<?= $request['id'] ?>)" 
                                        class="admin-button small danger" title="Delete Request">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        <?php if (isset($pagination) && $pagination['total_pages'] > 1): ?>
            <div class="mt-6 flex justify-between items-center">
                <div class="text-sm text-gray-400">
                    Showing <?= $pagination['start'] ?> to <?= $pagination['end'] ?> of <?= $pagination['total'] ?> results
                </div>
                <div class="flex gap-2">
                    <?php if ($pagination['current_page'] > 1): ?>
                        <a href="?<?= http_build_query(array_merge($_GET, ['page' => $pagination['current_page'] - 1])) ?>" 
                           class="admin-button small secondary">
                            <i class="fas fa-chevron-left"></i>
                        </a>
                    <?php endif; ?>
                    
                    <?php for ($i = max(1, $pagination['current_page'] - 2); $i <= min($pagination['total_pages'], $pagination['current_page'] + 2); $i++): ?>
                        <a href="?<?= http_build_query(array_merge($_GET, ['page' => $i])) ?>" 
                           class="admin-button small <?= $i === $pagination['current_page'] ? '' : 'secondary' ?>">
                            <?= $i ?>
                        </a>
                    <?php endfor; ?>
                    
                    <?php if ($pagination['current_page'] < $pagination['total_pages']): ?>
                        <a href="?<?= http_build_query(array_merge($_GET, ['page' => $pagination['current_page'] + 1])) ?>" 
                           class="admin-button small secondary">
                            <i class="fas fa-chevron-right"></i>
                        </a>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>
    <?php endif; ?>
</div>

<!-- Withdrawal Details Modal -->
<div id="withdrawalModal" class="fixed inset-0 bg-black bg-opacity-75 hidden z-50">
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-dark rounded-lg border border-gray-800 max-w-2xl w-full max-h-[90vh] overflow-y-auto shadow-2xl">
            <div class="p-6">
                <div class="flex justify-between items-center mb-6">
                    <h3 class="text-xl font-semibold text-white">Withdrawal Request Details</h3>
                    <button onclick="closeWithdrawalModal()" class="text-gray-400 hover:text-white transition-colors p-2 hover:bg-gray-800 rounded-md">
                        <i class="fas fa-times text-lg"></i>
                    </button>
                </div>
                <div id="withdrawalDetails">
                    <!-- Details will be loaded here -->
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function updateWithdrawalStatus(requestId, status) {
    const action = status === 'approved' ? 'approve' : 'reject';
    const actionIcon = status === 'approved' ? 'fa-check' : 'fa-times';
    const actionColorClass = status === 'approved' ? 'success' : 'danger';
    const iconBgClass = status === 'approved' ? 'bg-green-600' : 'bg-red-600';
    const buttonClass = status === 'approved' ? 'admin-button success' : 'admin-button danger';
    
    // Create confirmation modal
    const modal = document.createElement('div');
    modal.className = 'fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-50';
    modal.innerHTML = `
        <div class="bg-dark rounded-lg border border-gray-800 p-6 max-w-md w-full mx-4 shadow-2xl">
            <div class="flex items-start mb-6">
                <div class="w-12 h-12 rounded-full ${iconBgClass} flex items-center justify-center mr-4 flex-shrink-0">
                    <i class="fas ${actionIcon} text-white text-lg"></i>
                </div>
                <div class="flex-1">
                    <h3 class="text-xl font-semibold text-white mb-2">${action.charAt(0).toUpperCase() + action.slice(1)} Withdrawal</h3>
                    <p class="text-gray-400 text-sm leading-relaxed">This action cannot be undone. Please review the request carefully before proceeding.</p>
                </div>
            </div>
            
            <div class="mb-6">
                <label class="block text-sm font-medium text-gray-300 mb-2">Admin Notes (optional)</label>
                <textarea id="adminNotesInput" placeholder="Enter notes about this ${action}al..." 
                          class="w-full px-4 py-3 bg-darker border border-gray-800 rounded-md text-white placeholder-gray-500 focus:border-primary focus:ring-1 focus:ring-primary transition-colors h-24 resize-none"></textarea>
                <p class="text-xs text-gray-500 mt-1">These notes will be visible to the user and other administrators.</p>
            </div>
            
            <div class="flex gap-3">
                <button onclick="confirmWithdrawalUpdate(${requestId}, '${status}', this)" 
                        class="flex-1 ${buttonClass} py-3 px-4 font-medium transition-all duration-200">
                    <i class="fas ${actionIcon} mr-2"></i>
                    ${action.charAt(0).toUpperCase() + action.slice(1)}
                </button>
                <button onclick="this.closest('.fixed').remove()" 
                        class="px-6 py-3 border border-gray-700 text-gray-300 rounded-md hover:bg-gray-800 hover:border-gray-600 transition-all duration-200 font-medium">
                    Cancel
                </button>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // Focus on textarea
    setTimeout(() => {
        document.getElementById('adminNotesInput').focus();
    }, 100);
}

function confirmWithdrawalUpdate(requestId, status, buttonElement) {
    const adminNotes = document.getElementById('adminNotesInput').value.trim();
    
    // Show loading state
    if (!buttonElement) {
        console.error('Button element not provided');
        return;
    }
    const originalText = buttonElement.innerHTML;
    buttonElement.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Processing...';
    buttonElement.disabled = true;
    
    fetch('/admin/withdrawal-requests/update', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            request_id: requestId,
            status: status,
            admin_notes: adminNotes
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Show success message
            showNotification('Withdrawal request updated successfully!', 'success');
            buttonElement.closest('.fixed').remove();
            
            // Reload page after short delay
            setTimeout(() => {
                location.reload();
            }, 1500);
        } else {
            showNotification('Error: ' + data.message, 'error');
            buttonElement.innerHTML = originalText;
            buttonElement.disabled = false;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('An error occurred while updating the withdrawal request.', 'error');
        buttonElement.innerHTML = originalText;
        buttonElement.disabled = false;
    });
}

function viewWithdrawalDetails(requestId) {
    fetch(`/admin/withdrawal-requests/details/${requestId}`)
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            document.getElementById('withdrawalDetails').innerHTML = data.html;
            document.getElementById('withdrawalModal').classList.remove('hidden');
        } else {
            alert('Error loading withdrawal details');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred while loading withdrawal details.');
    });
}

function closeWithdrawalModal() {
    document.getElementById('withdrawalModal').classList.add('hidden');
}

function deleteWithdrawalRequest(requestId) {
    // Create confirmation modal
    const modal = document.createElement('div');
    modal.className = 'fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-50';
    modal.innerHTML = `
        <div class="bg-dark rounded-lg border border-gray-800 p-6 max-w-md w-full mx-4 shadow-2xl">
            <div class="flex items-start mb-6">
                <div class="w-12 h-12 rounded-full bg-red-600 flex items-center justify-center mr-4 flex-shrink-0">
                    <i class="fas fa-trash text-white text-lg"></i>
                </div>
                <div class="flex-1">
                    <h3 class="text-xl font-semibold text-white mb-2">Delete Withdrawal Request</h3>
                    <p class="text-gray-400 text-sm leading-relaxed">This action cannot be undone. The withdrawal request will be permanently deleted from the system.</p>
                </div>
            </div>
            
            <div class="flex gap-3">
                <button onclick="confirmDeleteWithdrawal(${requestId}, this)" 
                        class="flex-1 admin-button danger py-3 px-4 font-medium transition-all duration-200">
                    <i class="fas fa-trash mr-2"></i>
                    Delete
                </button>
                <button onclick="this.closest('.fixed').remove()" 
                        class="px-6 py-3 border border-gray-700 text-gray-300 rounded-md hover:bg-gray-800 hover:border-gray-600 transition-all duration-200 font-medium">
                    Cancel
                </button>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
}

function confirmDeleteWithdrawal(requestId, buttonElement) {
    // Show loading state
    const originalText = buttonElement.innerHTML;
    buttonElement.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Deleting...';
    buttonElement.disabled = true;
    
    fetch('/admin/withdrawal-requests/delete', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            request_id: requestId
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('Withdrawal request deleted successfully!', 'success');
            buttonElement.closest('.fixed').remove();
            
            // Reload page after short delay
            setTimeout(() => {
                location.reload();
            }, 1500);
        } else {
            showNotification('Error: ' + data.message, 'error');
            buttonElement.innerHTML = originalText;
            buttonElement.disabled = false;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('An error occurred while deleting the withdrawal request.', 'error');
        buttonElement.innerHTML = originalText;
        buttonElement.disabled = false;
    });
}

// Close modal when clicking outside
document.getElementById('withdrawalModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeWithdrawalModal();
    }
});

// Notification system
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    const bgColor = type === 'success' ? 'bg-green-600' : type === 'error' ? 'bg-red-600' : 'bg-blue-600';
    const icon = type === 'success' ? 'fa-check-circle' : type === 'error' ? 'fa-exclamation-circle' : 'fa-info-circle';
    
    notification.className = `fixed top-4 right-4 ${bgColor} text-white px-6 py-3 rounded-lg shadow-lg z-50 transition-all duration-300 transform translate-x-full`;
    notification.innerHTML = `
        <div class="flex items-center">
            <i class="fas ${icon} mr-2"></i>
            <span>${message}</span>
        </div>
    `;
    
    document.body.appendChild(notification);
    
    // Slide in animation
    setTimeout(() => {
        notification.style.transform = 'translateX(0)';
    }, 10);
    
    // Auto remove after 4 seconds
    setTimeout(() => {
        notification.style.transform = 'translateX(full)';
        setTimeout(() => {
            if (notification.parentNode) {
                notification.remove();
            }
        }, 300);
    }, 4000);
}
</script>

<style>
.status-badge {
    @apply inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium;
}

.status-pending {
    @apply bg-yellow-100 text-yellow-800;
}

.status-approved {
    @apply bg-green-100 text-green-800;
}

.status-rejected {
    @apply bg-red-100 text-red-800;
}

.admin-button.small {
    @apply px-2 py-1 text-sm;
}

.admin-button.success {
    @apply bg-green-600 hover:bg-green-700;
}

.admin-button.danger {
    @apply bg-red-600 hover:bg-red-700;
}
</style>

<?php
$content = ob_get_clean();
include __DIR__ . '/layout.php';
?>