<?php
session_start();
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: admin_login.php");
    exit();
}
require_once 'db.php';

// Handle withdrawal status updates
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    $withdrawal_id = intval($_POST['withdrawal_id']);
    $action = $_POST['action'];
    
    if ($action == 'approve') {
        // Update withdrawal status to processed
        $update_query = "UPDATE withdrawals SET status = 'processed' WHERE id = ?";
        $stmt = mysqli_prepare($conn, $update_query);
        mysqli_stmt_bind_param($stmt, "i", $withdrawal_id);
        
        if (mysqli_stmt_execute($stmt)) {
            $success = "Withdrawal approved successfully!";
        } else {
            $error = "Failed to approve withdrawal!";
        }
        mysqli_stmt_close($stmt);
        
    } elseif ($action == 'reject') {
        // Get withdrawal details first
        $withdrawal_query = "SELECT user_id, amount FROM withdrawals WHERE id = ?";
        $stmt = mysqli_prepare($conn, $withdrawal_query);
        mysqli_stmt_bind_param($stmt, "i", $withdrawal_id);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        $withdrawal = mysqli_fetch_assoc($result);
        mysqli_stmt_close($stmt);
        
        if ($withdrawal) {
            // Update withdrawal status to rejected
            $update_query = "UPDATE withdrawals SET status = 'rejected' WHERE id = ?";
            $stmt = mysqli_prepare($conn, $update_query);
            mysqli_stmt_bind_param($stmt, "i", $withdrawal_id);
            
            if (mysqli_stmt_execute($stmt)) {
                $success = "Withdrawal rejected successfully!";
            } else {
                $error = "Failed to reject withdrawal!";
            }
            mysqli_stmt_close($stmt);
        }
    }
}

// Get filter status
$filter = isset($_GET['filter']) ? $_GET['filter'] : 'all';

// Build query based on filter
$where_clause = "";
if ($filter == 'processing') {
    $where_clause = "WHERE w.status = 'processing'";
} elseif ($filter == 'processed') {
    $where_clause = "WHERE w.status = 'processed'";
} elseif ($filter == 'rejected') {
    $where_clause = "WHERE w.status = 'rejected'";
}

// Get all withdrawals with user information
$query = "SELECT w.*, u.phone_number, u.email 
          FROM withdrawals w 
          JOIN users u ON w.user_id = u.id 
          $where_clause
          ORDER BY w.created_at DESC";
$withdrawals_result = mysqli_query($conn, $query);

// Get counts for each status
$count_query = "SELECT 
                COUNT(*) as total,
                SUM(CASE WHEN status = 'processing' THEN 1 ELSE 0 END) as processing,
                SUM(CASE WHEN status = 'processed' THEN 1 ELSE 0 END) as processed,
                SUM(CASE WHEN status = 'rejected' THEN 1 ELSE 0 END) as rejected
                FROM withdrawals";
$count_result = mysqli_query($conn, $count_query);
$counts = mysqli_fetch_assoc($count_result);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Withdrawals - Admin</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            background-color: #000;
            color: #fff;
            font-family: Arial, sans-serif;
            font-size: 13px;
        }
        .header {
            background: #111;
            padding: 12px 15px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.5);
            position: sticky;
            top: 0;
            z-index: 100;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .header-left {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        .header h1 {
            color: #fff;
            font-size: 18px;
        }
        .back-btn {
            color: #FFD700;
            text-decoration: none;
            font-size: 20px;
        }
        .logout-btn {
            background: #f87171;
            color: #fff;
            padding: 8px 15px;
            border-radius: 5px;
            text-decoration: none;
            font-size: 12px;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        .container {
            padding: 12px;
            max-width: 1200px;
            margin: 0 auto;
        }
        .alert {
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 12px;
            font-size: 12px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .alert-success {
            background: #1a4d1a;
            border: 1px solid #2d7a2d;
            color: #4ade80;
        }
        .alert-error {
            background: #4d1a1a;
            border: 1px solid #7a2d2d;
            color: #f87171;
        }
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 10px;
            margin-bottom: 15px;
        }
        .stat-card {
            background: #111;
            padding: 15px;
            border-radius: 8px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            border: 2px solid transparent;
        }
        .stat-card:hover {
            transform: translateY(-2px);
        }
        .stat-card.active {
            border-color: #FFD700;
        }
        .stat-number {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 5px;
        }
        .stat-label {
            color: #888;
            font-size: 11px;
        }
        .stat-card.all .stat-number { color: #FFD700; }
        .stat-card.processing .stat-number { color: #FFA500; }
        .stat-card.processed .stat-number { color: #4ade80; }
        .stat-card.rejected .stat-number { color: #f87171; }
        
        .withdrawals-list {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }
        .withdrawal-card {
            background: #111;
            border-radius: 10px;
            padding: 15px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.5);
            border-left: 4px solid #333;
        }
        .withdrawal-card.processing {
            border-left-color: #FFA500;
        }
        .withdrawal-card.processed {
            border-left-color: #4ade80;
        }
        .withdrawal-card.rejected {
            border-left-color: #f87171;
        }
        .withdrawal-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 12px;
        }
        .withdrawal-amount {
            font-size: 20px;
            font-weight: bold;
            color: #FFD700;
        }
        .withdrawal-status {
            padding: 5px 10px;
            border-radius: 5px;
            font-size: 10px;
            font-weight: bold;
            text-transform: uppercase;
        }
        .status-processing {
            background: #FFA500;
            color: #000;
        }
        .status-processed {
            background: #4ade80;
            color: #000;
        }
        .status-rejected {
            background: #f87171;
            color: #fff;
        }
        .withdrawal-info {
            display: grid;
            gap: 8px;
            margin-bottom: 12px;
        }
        .info-row {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 12px;
        }
        .info-label {
            color: #888;
            min-width: 80px;
        }
        .info-value {
            color: #fff;
        }
        .action-buttons {
            display: flex;
            gap: 10px;
            margin-top: 12px;
        }
        .btn {
            flex: 1;
            padding: 10px;
            border: none;
            border-radius: 5px;
            font-weight: bold;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 5px;
            font-size: 12px;
            transition: all 0.3s;
        }
        .btn-approve {
            background: #4ade80;
            color: #000;
        }
        .btn-approve:hover {
            background: #22c55e;
        }
        .btn-reject {
            background: #f87171;
            color: #fff;
        }
        .btn-reject:hover {
            background: #ef4444;
        }
        .btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        .no-withdrawals {
            text-align: center;
            padding: 40px;
            color: #666;
        }
        .no-withdrawals i {
            font-size: 50px;
            margin-bottom: 15px;
            opacity: 0.3;
        }

        @media (max-width: 768px) {
            .withdrawal-header {
                flex-direction: column;
                gap: 10px;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="header-left">
            <a href="admin_dashboard.php" class="back-btn"><i class="fas fa-arrow-left"></i></a>
            <h1><i class="fas fa-hand-holding-usd"></i> Manage Withdrawals</h1>
        </div>
        <a href="admin_logout.php" class="logout-btn">
            <i class="fas fa-sign-out-alt"></i> Logout
        </a>
    </div>

    <div class="container">
        <?php if (isset($success)): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i>
                <span><?php echo $success; ?></span>
            </div>
        <?php endif; ?>
        
        <?php if (isset($error)): ?>
            <div class="alert alert-error">
                <i class="fas fa-exclamation-circle"></i>
                <span><?php echo $error; ?></span>
            </div>
        <?php endif; ?>

        <!-- Statistics -->
        <div class="stats-grid">
            <a href="?filter=all" style="text-decoration: none;">
                <div class="stat-card all <?php echo $filter == 'all' ? 'active' : ''; ?>">
                    <div class="stat-number"><?php echo $counts['total']; ?></div>
                    <div class="stat-label">Total Withdrawals</div>
                </div>
            </a>
            <a href="?filter=processing" style="text-decoration: none;">
                <div class="stat-card processing <?php echo $filter == 'processing' ? 'active' : ''; ?>">
                    <div class="stat-number"><?php echo $counts['processing']; ?></div>
                    <div class="stat-label">Processing</div>
                </div>
            </a>
            <a href="?filter=processed" style="text-decoration: none;">
                <div class="stat-card processed <?php echo $filter == 'processed' ? 'active' : ''; ?>">
                    <div class="stat-number"><?php echo $counts['processed']; ?></div>
                    <div class="stat-label">Approved</div>
                </div>
            </a>
            <a href="?filter=rejected" style="text-decoration: none;">
                <div class="stat-card rejected <?php echo $filter == 'rejected' ? 'active' : ''; ?>">
                    <div class="stat-number"><?php echo $counts['rejected']; ?></div>
                    <div class="stat-label">Rejected</div>
                </div>
            </a>
        </div>

        <!-- Withdrawals List -->
        <div class="withdrawals-list">
            <?php if ($withdrawals_result && mysqli_num_rows($withdrawals_result) > 0): ?>
                <?php while ($withdrawal = mysqli_fetch_assoc($withdrawals_result)): ?>
                <div class="withdrawal-card <?php echo htmlspecialchars($withdrawal['status']); ?>">
                    <div class="withdrawal-header">
                        <div class="withdrawal-amount">
                            <i class="fas fa-dollar-sign"></i> <?php echo number_format($withdrawal['amount'], 2); ?>
                        </div>
                        <span class="withdrawal-status status-<?php echo htmlspecialchars($withdrawal['status']); ?>">
                            <?php echo htmlspecialchars($withdrawal['status']); ?>
                        </span>
                    </div>
                    
                    <div class="withdrawal-info">
                        <div class="info-row">
                            <span class="info-label"><i class="fas fa-user"></i> User:</span>
                            <span class="info-value"><?php echo htmlspecialchars($withdrawal['phone_number']); ?></span>
                        </div>
                        <div class="info-row">
                            <span class="info-label"><i class="fas fa-envelope"></i> Email:</span>
                            <span class="info-value"><?php echo htmlspecialchars($withdrawal['email']); ?></span>
                        </div>
                        <div class="info-row">
                            <span class="info-label"><i class="fas fa-clock"></i> Date:</span>
                            <span class="info-value"><?php echo date('M d, Y - h:i A', strtotime($withdrawal['created_at'])); ?></span>
                        </div>
                        <div class="info-row">
                            <span class="info-label"><i class="fas fa-hashtag"></i> ID:</span>
                            <span class="info-value">#<?php echo $withdrawal['id']; ?></span>
                        </div>
                    </div>

                    <?php if ($withdrawal['status'] == 'processing'): ?>
                    <div class="action-buttons">
                        <form method="POST" style="flex: 1;" onsubmit="return confirm('Are you sure you want to APPROVE this withdrawal? Make sure you have sent the payment to the user.');">
                            <input type="hidden" name="withdrawal_id" value="<?php echo $withdrawal['id']; ?>">
                            <input type="hidden" name="action" value="approve">
                            <button type="submit" class="btn btn-approve">
                                <i class="fas fa-check"></i> Approve
                            </button>
                        </form>
                        <form method="POST" style="flex: 1;" onsubmit="return confirm('Are you sure you want to REJECT this withdrawal?');">
                            <input type="hidden" name="withdrawal_id" value="<?php echo $withdrawal['id']; ?>">
                            <input type="hidden" name="action" value="reject">
                            <button type="submit" class="btn btn-reject">
                                <i class="fas fa-times"></i> Reject
                            </button>
                        </form>
                    </div>
                    <?php endif; ?>
                </div>
                <?php endwhile; ?>
            <?php else: ?>
                <div class="no-withdrawals">
                    <i class="fas fa-inbox"></i>
                    <p>No withdrawals found</p>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        // Auto-hide alerts
        setTimeout(function() {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(function(alert) {
                alert.style.transition = 'opacity 0.5s';
                alert.style.opacity = '0';
                setTimeout(function() {
                    alert.remove();
                }, 500);
            });
        }, 5000);
    </script>
</body>
</html>
<?php
mysqli_close($conn);
?>