<?php
$page_title = "Withdrawals Management";
require_once 'header.php';

$db = Database::getInstance()->connect();

// Handle actions
if (isset($_GET['action']) && isset($_GET['id'])) {
    $action = $_GET['action'];
    $transaction_id = $_GET['id'];
    
    try {
        $db->beginTransaction();
        
        // Get transaction details
        $stmt = $db->prepare("SELECT * FROM transactions WHERE id = ? AND type = 'withdrawal'");
        $stmt->execute([$transaction_id]);
        $transaction = $stmt->fetch();
        
        if (!$transaction) {
            throw new Exception("Transaction not found");
        }
        
        $user_id = $transaction['user_id'];
        $amount = $transaction['amount'];
        $details = json_decode($transaction['details'] ?? '{}', true);
        $fee = $details['fee'] ?? 0;
        $net_amount = $details['net_amount'] ?? $amount;
        
        if ($action == 'approve') {
            // Check if user has enough balance (already deducted when requested)
            $user_stmt = $db->prepare("SELECT balance FROM users WHERE id = ?");
            $user_stmt->execute([$user_id]);
            $user = $user_stmt->fetch();
            
            // Update transaction status
            $update_stmt = $db->prepare("UPDATE transactions SET status = 'completed', admin_action_by = ? WHERE id = ?");
            $update_stmt->execute([$_SESSION['admin_id'], $transaction_id]);
            
            // Update user totals (balance already deducted when requested)
            $total_stmt = $db->prepare("UPDATE users SET total_withdrawal = total_withdrawal + ? WHERE id = ?");
            $total_stmt->execute([$amount, $user_id]);
            
            // Log action
            $log_stmt = $db->prepare("INSERT INTO activity_logs (admin_id, user_id, action, description, ip_address, user_agent, details, created_at) VALUES (?, ?, 'withdrawal_approve', 'Withdrawal approved', ?, ?, ?, NOW())");
            $log_stmt->execute([
                $_SESSION['admin_id'],
                $user_id,
                $_SERVER['REMOTE_ADDR'] ?? '',
                $_SERVER['HTTP_USER_AGENT'] ?? '',
                json_encode([
                    'transaction_id' => $transaction_id,
                    'amount' => $amount,
                    'fee' => $fee,
                    'net_amount' => $net_amount,
                    'reference' => $transaction['reference']
                ])
            ]);
            
            $message = "Withdrawal approved successfully!";
            $success = true;
            
        } elseif ($action == 'reject') {
            // Update transaction status
            $update_stmt = $db->prepare("UPDATE transactions SET status = 'rejected', admin_action_by = ? WHERE id = ?");
            $update_stmt->execute([$_SESSION['admin_id'], $transaction_id]);
            
            // Return balance to user (was deducted when requested)
            $return_stmt = $db->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
            $return_stmt->execute([$amount, $user_id]);
            
            // Log action
            $log_stmt = $db->prepare("INSERT INTO activity_logs (admin_id, user_id, action, details) VALUES (?, ?, 'withdrawal_reject', ?)");
            $log_stmt->execute([
                $_SESSION['admin_id'],
                $user_id,
                json_encode([
                    'transaction_id' => $transaction_id,
                    'amount' => $amount,
                    'reference' => $transaction['reference']
                ])
            ]);
            
            $message = "Withdrawal rejected successfully!";
            $success = true;
            
        } elseif ($action == 'delete') {
            // First check if we need to return balance
            if ($transaction['status'] == 'pending') {
                $return_stmt = $db->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
                $return_stmt->execute([$amount, $user_id]);
            }
            
            // Delete transaction
            $delete_stmt = $db->prepare("DELETE FROM transactions WHERE id = ?");
            $delete_stmt->execute([$transaction_id]);
            
            $message = "Withdrawal deleted successfully!";
            $success = true;
        }
        
        $db->commit();
        
        if ($success) {
            echo "<script>alert('$message'); window.location.href='withdrawals.php';</script>";
            exit();
        }
        
    } catch (Exception $e) {
        $db->rollBack();
        $error = "Action failed: " . $e->getMessage();
    }
}

// Get withdrawals
$status = $_GET['status'] ?? 'pending';
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$limit = 20;
$offset = ($page - 1) * $limit;

// Build query
$where = "WHERE t.type = 'withdrawal'";
$params = [];

if ($status != 'all') {
    $where .= " AND t.status = ?";
    $params[] = $status;
}

if (isset($_GET['user_id'])) {
    $where .= " AND t.user_id = ?";
    $params[] = $_GET['user_id'];
}

// Get total count
$count_sql = "SELECT COUNT(*) as total FROM transactions t $where";
$count_stmt = $db->prepare($count_sql);
$count_stmt->execute($params);
$total_withdrawals = $count_stmt->fetch()['total'];
$total_pages = ceil($total_withdrawals / $limit);

// Get withdrawals
$sql = "SELECT t.*, u.username, u.email, u.balance as user_balance 
        FROM transactions t 
        LEFT JOIN users u ON t.user_id = u.id 
        $where 
        ORDER BY t.created_at DESC 
        LIMIT $limit OFFSET $offset";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$withdrawals = $stmt->fetchAll();

// Get stats
$stats_sql = "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
    SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed,
    SUM(CASE WHEN status = 'rejected' THEN 1 ELSE 0 END) as rejected,
    SUM(CASE WHEN status = 'completed' THEN amount ELSE 0 END) as total_amount,
    SUM(CASE WHEN status = 'completed' THEN JSON_EXTRACT(details, '$.fee') ELSE 0 END) as total_fees
    FROM transactions 
    WHERE type = 'withdrawal'";

$stats_stmt = $db->query($stats_sql);
$stats = $stats_stmt->fetch();
?>

<div class="container-fluid">
    <!-- Stats Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Total Withdrawals</p>
                    <h3 class="text-2xl font-bold"><?php echo number_format((int)($stats['total'] ?? 0)); ?></h3>
                </div>
                <i class="fas fa-wallet text-red-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Pending Withdrawals</p>
                    <h3 class="text-2xl font-bold text-yellow-600"><?php echo number_format((int)($stats['pending'] ?? 0)); ?></h3>
                </div>
                <i class="fas fa-clock text-yellow-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Total Amount</p>
                    <h3 class="text-2xl font-bold text-red-600">$<?php echo number_format((float)($stats['total_amount'] ?? 0), 2); ?></h3>
                </div>
                <i class="fas fa-dollar-sign text-red-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Total Fees</p>
                    <h3 class="text-2xl font-bold">$<?php echo number_format((float)($stats['total_fees'] ?? 0), 2); ?></h3>
                </div>
                <i class="fas fa-percentage text-blue-500 text-2xl"></i>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="bg-white rounded-xl shadow p-6 mb-6">
        <div class="flex flex-wrap gap-4 items-center">
            <div class="flex space-x-2">
                <a href="?status=pending" class="px-4 py-2 rounded-lg <?php echo $status == 'pending' ? 'bg-yellow-100 text-yellow-800' : 'bg-gray-100'; ?>">
                    Pending (<?php echo $stats['pending']; ?>)
                </a>
                <a href="?status=completed" class="px-4 py-2 rounded-lg <?php echo $status == 'completed' ? 'bg-green-100 text-green-800' : 'bg-gray-100'; ?>">
                    Completed (<?php echo $stats['completed']; ?>)
                </a>
                <a href="?status=rejected" class="px-4 py-2 rounded-lg <?php echo $status == 'rejected' ? 'bg-red-100 text-red-800' : 'bg-gray-100'; ?>">
                    Rejected (<?php echo $stats['rejected']; ?>)
                </a>
                <a href="?status=all" class="px-4 py-2 rounded-lg <?php echo $status == 'all' ? 'bg-purple-100 text-purple-800' : 'bg-gray-100'; ?>">
                    All Withdrawals
                </a>
            </div>
            
            <div class="flex-1">
                <form method="GET" class="flex">
                    <input type="text" name="user_id" value="<?php echo $_GET['user_id'] ?? ''; ?>"
                           class="flex-1 px-4 py-2 border border-gray-300 rounded-l-lg focus:ring-2 focus:ring-purple-500"
                           placeholder="Filter by User ID">
                    <button type="submit" class="bg-gray-800 text-white px-4 py-2 rounded-r-lg hover:bg-gray-900">
                        <i class="fas fa-search"></i>
                    </button>
                </form>
            </div>
            
            <div>
                <button onclick="exportWithdrawals()" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700">
                    <i class="fas fa-download mr-2"></i>Export
                </button>
            </div>
        </div>
    </div>

    <!-- Withdrawals Table -->
    <div class="bg-white rounded-xl shadow overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="p-4 text-left">Reference</th>
                        <th class="p-4 text-left">User</th>
                        <th class="p-4 text-left">Amount Details</th>
                        <th class="p-4 text-left">Method</th>
                        <th class="p-4 text-left">Status</th>
                        <th class="p-4 text-left">Date</th>
                        <th class="p-4 text-left">Wallet/Account</th>
                        <th class="p-4 text-left">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    <?php if (count($withdrawals) > 0): ?>
                        <?php foreach ($withdrawals as $withdrawal): 
                            $details = json_decode($withdrawal['details'] ?? '{}', true);
                            $fee = $details['fee'] ?? 0;
                            $net_amount = $details['net_amount'] ?? ($withdrawal['amount'] - $fee);
                        ?>
                        <tr class="hover:bg-gray-50">
                            <!-- Reference -->
                            <td class="p-4">
                                <p class="font-mono text-sm"><?php echo $withdrawal['reference']; ?></p>
                                <p class="text-xs text-gray-500">ID: <?php echo $withdrawal['id']; ?></p>
                            </td>
                            
                            <!-- User -->
                            <td class="p-4">
                                <p class="font-medium"><?php echo htmlspecialchars($withdrawal['username']); ?></p>
                                <p class="text-sm text-gray-500"><?php echo htmlspecialchars($withdrawal['email']); ?></p>
                                <p class="text-xs text-gray-500">Balance: $<?php echo number_format($withdrawal['user_balance'], 2); ?></p>
                            </td>
                            
                            <!-- Amount Details -->
                            <td class="p-4">
                                <p class="font-bold text-red-600">-$<?php echo number_format($withdrawal['amount'], 2); ?></p>
                                <?php if ($fee > 0): ?>
                                <p class="text-xs text-gray-500">Fee: $<?php echo number_format($fee, 2); ?></p>
                                <?php endif; ?>
                                <p class="text-xs text-gray-500">Net: $<?php echo number_format($net_amount, 2); ?></p>
                            </td>
                            
                            <!-- Method -->
                            <td class="p-4">
                                <p class="capitalize"><?php echo $withdrawal['method'] ?: 'N/A'; ?></p>
                                <?php if ($withdrawal['method'] == 'crypto' && isset($details['network'])): ?>
                                <p class="text-xs bg-blue-100 text-blue-800 inline-block px-2 py-1 rounded mt-1">
                                    <i class="fab fa-bitcoin mr-1"></i><?php echo $details['network']; ?>
                                </p>
                                <?php endif; ?>
                            </td>
                            
                            <!-- Status -->
                            <td class="p-4">
                                <span class="px-3 py-1 rounded-full text-xs font-semibold <?php
                                    echo $withdrawal['status'] == 'completed' ? 'bg-green-100 text-green-800' :
                                        ($withdrawal['status'] == 'pending' ? 'bg-yellow-100 text-yellow-800' :
                                        'bg-red-100 text-red-800');
                                ?>">
                                    <?php echo ucfirst($withdrawal['status']); ?>
                                </span>
                            </td>
                            
                            <!-- Date -->
                            <td class="p-4">
                                <p><?php echo date('M d, Y', strtotime($withdrawal['created_at'])); ?></p>
                                <p class="text-sm text-gray-500"><?php echo date('H:i', strtotime($withdrawal['created_at'])); ?></p>
                            </td>
                            
                            <!-- Wallet/Account -->
                            <td class="p-4">
                                <?php if (isset($details['wallet_address'])): ?>
                                <p class="text-sm font-mono truncate max-w-xs"><?php echo $details['wallet_address']; ?></p>
                                <?php else: ?>
                                <span class="text-gray-500 text-sm">Not specified</span>
                                <?php endif; ?>
                            </td>
                            
                            <!-- Actions -->
                            <td class="p-4">
                                <div class="flex flex-col space-y-2">
                                    <?php if ($withdrawal['status'] == 'pending'): ?>
                                    <a href="?action=approve&id=<?php echo $withdrawal['id']; ?>" 
                                       onclick="return confirm('Approve this withdrawal of $<?php echo number_format($net_amount, 2); ?>?')"
                                       class="text-green-600 hover:text-green-800 text-sm font-medium">
                                        <i class="fas fa-check mr-1"></i> Approve
                                    </a>
                                    <a href="?action=reject&id=<?php echo $withdrawal['id']; ?>" 
                                       onclick="return confirm('Reject this withdrawal? The amount will be returned to user balance.')"
                                       class="text-red-600 hover:text-red-800 text-sm font-medium">
                                        <i class="fas fa-times mr-1"></i> Reject
                                    </a>
                                    <?php endif; ?>
                                    
                                    <a href="transaction-view.php?id=<?php echo $withdrawal['id']; ?>" 
                                       class="text-blue-600 hover:text-blue-800 text-sm font-medium">
                                        <i class="fas fa-eye mr-1"></i> View Details
                                    </a>
                                    
                                    <a href="?action=delete&id=<?php echo $withdrawal['id']; ?>" 
                                       onclick="return confirm('Delete this withdrawal record?')"
                                       class="text-red-600 hover:text-red-800 text-sm font-medium">
                                        <i class="fas fa-trash mr-1"></i> Delete
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="8" class="p-8 text-center text-gray-500">
                                <i class="fas fa-wallet text-4xl mb-4 text-gray-300"></i>
                                <p class="text-lg">No withdrawals found</p>
                                <?php if ($status != 'all'): ?>
                                <p class="text-sm mt-2">Try viewing <a href="?status=all" class="text-purple-600">all withdrawals</a></p>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <div class="border-t border-gray-100 p-4">
            <div class="flex items-center justify-between">
                <div class="text-sm text-gray-600">
                    Showing <?php echo ($offset + 1); ?> to <?php echo min($offset + $limit, $total_withdrawals); ?> of <?php echo number_format($total_withdrawals); ?> withdrawals
                </div>
                <div class="flex space-x-2">
                    <?php if ($page > 1): ?>
                    <a href="?page=<?php echo $page - 1; ?>&status=<?php echo $status; ?><?php echo isset($_GET['user_id']) ? '&user_id=' . $_GET['user_id'] : ''; ?>"
                       class="px-3 py-2 bg-gray-100 rounded-lg hover:bg-gray-200">
                        <i class="fas fa-chevron-left"></i> Previous
                    </a>
                    <?php endif; ?>
                    
                    <?php
                    $start = max(1, $page - 2);
                    $end = min($total_pages, $start + 4);
                    
                    for ($i = $start; $i <= $end; $i++):
                    ?>
                    <a href="?page=<?php echo $i; ?>&status=<?php echo $status; ?><?php echo isset($_GET['user_id']) ? '&user_id=' . $_GET['user_id'] : ''; ?>"
                       class="px-3 py-2 rounded-lg <?php echo $i == $page ? 'bg-purple-600 text-white' : 'bg-gray-100 hover:bg-gray-200'; ?>">
                        <?php echo $i; ?>
                    </a>
                    <?php endfor; ?>
                    
                    <?php if ($page < $total_pages): ?>
                    <a href="?page=<?php echo $page + 1; ?>&status=<?php echo $status; ?><?php echo isset($_GET['user_id']) ? '&user_id=' . $_GET['user_id'] : ''; ?>"
                       class="px-3 py-2 bg-gray-100 rounded-lg hover:bg-gray-200">
                        Next <i class="fas fa-chevron-right"></i>
                    </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
    
    <!-- Quick Actions -->
    <div class="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
        <!-- Manual Withdrawal -->
        <div class="bg-white rounded-xl shadow p-6">
            <h4 class="text-lg font-bold mb-4">Manual Withdrawal</h4>
            <form id="manualWithdrawalForm" class="space-y-4">
                <div>
                    <label class="block text-gray-700 text-sm mb-1">User ID</label>
                    <input type="number" id="manual_w_user_id" required
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                </div>
                <div>
                    <label class="block text-gray-700 text-sm mb-1">Amount ($)</label>
                    <input type="number" step="0.01" id="manual_w_amount" required
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                </div>
                <div>
                    <label class="block text-gray-700 text-sm mb-1">Method</label>
                    <select id="manual_w_method" onchange="toggleCryptoNetwork()" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                        <option value="bank">Bank Transfer</option>
                        <option value="crypto">Cryptocurrency</option>
                        <option value="paypal">PayPal</option>
                    </select>
                </div>
                <div id="cryptoNetworkField" class="hidden">
                    <label class="block text-gray-700 text-sm mb-1">Cryptocurrency</label>
                    <select id="manual_w_network" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                        <option value="BTC">Bitcoin</option>
                        <option value="ETH">Ethereum (ERC20)</option>
                        <option value="BCH">Bitcoin Cash</option>
                        <option value="DOGE">Dogecoin</option>
                    </select>
                </div>
                <div>
                    <label class="block text-gray-700 text-sm mb-1">Wallet/Account</label>
                    <input type="text" id="manual_w_wallet" required
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                </div>
                <button type="button" onclick="processManualWithdrawal()"
                        class="w-full bg-red-600 text-white py-2 rounded-lg hover:bg-red-700">
                    <i class="fas fa-minus-circle mr-2"></i>Process Manual Withdrawal
                </button>
            </form>
        </div>
        
        <!-- Statistics -->
        <div class="bg-white rounded-xl shadow p-6">
            <h4 class="text-lg font-bold mb-4">Today's Statistics</h4>
            <?php
            $today = date('Y-m-d');
            $today_sql = "SELECT 
                COUNT(*) as count,
                SUM(CASE WHEN status = 'completed' THEN amount ELSE 0 END) as total,
                SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending
                FROM transactions 
                WHERE type = 'withdrawal' 
                AND DATE(created_at) = ?";
            
            $today_stmt = $db->prepare($today_sql);
            $today_stmt->execute([$today]);
            $today_stats = $today_stmt->fetch();
            ?>
            <div class="space-y-3">
                <div class="flex justify-between">
                    <span>Today's Withdrawals:</span>
                    <span class="font-bold"><?php echo $today_stats['count']; ?></span>
                </div>
                <div class="flex justify-between">
                    <span>Today's Amount:</span>
                    <span class="font-bold text-red-600">$<?php echo number_format($today_stats['total'] ?? 0, 2); ?></span>
                </div>
                <div class="flex justify-between">
                    <span>Pending Today:</span>
                    <span class="font-bold text-yellow-600"><?php echo $today_stats['pending']; ?></span>
                </div>
                <div class="pt-4">
                    <button onclick="bulkApproveWithdrawals()" class="w-full bg-green-600 text-white py-2 rounded-lg hover:bg-green-700">
                        <i class="fas fa-check-double mr-2"></i>Approve All Pending
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function toggleCryptoNetwork() {
    const method = document.getElementById('manual_w_method').value;
    const cryptoField = document.getElementById('cryptoNetworkField');
    if (method === 'crypto') {
        cryptoField.classList.remove('hidden');
    } else {
        cryptoField.classList.add('hidden');
    }
}

function exportWithdrawals() {
    const params = new URLSearchParams(window.location.search);
    window.open(`../api/export-withdrawals.php?${params.toString()}`, '_blank');
}

function processManualWithdrawal() {
    const userId = document.getElementById('manual_w_user_id').value;
    const amount = document.getElementById('manual_w_amount').value;
    const method = document.getElementById('manual_w_method').value;
    const wallet = document.getElementById('manual_w_wallet').value;
    
    if (!userId || !amount || amount <= 0 || !wallet) {
        showNotification('Please fill all fields with valid values', 'error');
        return;
    }
    
    let description = `Manual withdrawal of $${amount} via ${method}`;
    let data = {
        action: 'manual_withdrawal',
        user_id: userId,
        amount: amount,
        method: method,
        wallet: wallet
    };
    
    // Add network if crypto method
    if (method === 'crypto') {
        const network = document.getElementById('manual_w_network').value;
        data.network = network;
        description += ` (${network})`;
    }
    
    if (confirm(description + ' for user ID ' + userId + '?')) {
        $.ajax({
            url: '../api/admin-actions.php',
            method: 'POST',
            data: data,
            success: function(response) {
                const result = typeof response === 'string' ? JSON.parse(response) : response;
                showNotification(result.message, result.success ? 'success' : 'error');
                if (result.success) {
                    document.getElementById('manualWithdrawalForm').reset();
                    location.reload();
                }
            }
        });
    }
}

function bulkApproveWithdrawals() {
    if (confirm('Approve ALL pending withdrawals? This action cannot be undone.')) {
        $.ajax({
            url: '../api/admin-actions.php',
            method: 'POST',
            data: {
                action: 'bulk_approve_withdrawals',
                status: '<?php echo htmlspecialchars($status); ?>',
                user_id: '<?php echo htmlspecialchars($_GET['user_id'] ?? ''); ?>'
            },
            success: function(response) {
                const result = typeof response === 'string' ? JSON.parse(response) : response;
                showNotification(result.message, result.success ? 'success' : 'error');
                if (result.success) location.reload();
            }
        });
    }
}

// Quick approve/reject
function quickWithdrawalAction(transactionId, action) {
    if (confirm(`${action.charAt(0).toUpperCase() + action.slice(1)} this withdrawal?`)) {
        window.location.href = `?action=${action}&id=${transactionId}`;
    }
}
</script>

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