<?php
require_once 'admin_init.php';
require_once 'includes/header.php';
$conn = $conn_header;

if(isset($_POST['action'])) {
    $request_id = $_POST['request_id'];
    $new_status = $_POST['action'] === 'approve' ? 'approved' : 'rejected';
    
    $stmt = $conn->prepare("UPDATE withdrawals SET status = ? WHERE id = ?");
    $stmt->bind_param('si', $new_status, $request_id);
    $stmt->execute();
    header("Location: withdrawals.php");
    exit();
}

$withdrawals = $conn->query("SELECT w.*, u.first_name FROM withdrawals w JOIN users u ON w.user_id = u.chat_id ORDER BY w.requested_at DESC");
?>
<style>
    table { width: 100%; border-collapse: collapse; background: #fff; border-radius: 8px; overflow: hidden; }
    th, td { padding: 15px; border-bottom: 1px solid #ddd; }
    th { background: #f8f9fa; }
    .status { padding: 5px 10px; border-radius: 20px; color: #fff; font-size: 0.8em; }
    .pending { background: #ffc107; }
    .approved { background: #28a745; }
    .rejected { background: #dc3545; }
    .action-btn { padding: 5px 10px; border: none; border-radius: 5px; cursor: pointer; color: #fff; }
</style>
<h2>Withdrawal Requests</h2>
<table>
    <thead><tr><th>ID</th><th>User</th><th>Amount</th><th>Method</th><th>Account</th><th>Date</th><th>Status</th><th>Actions</th></tr></thead>
    <tbody>
        <?php while($row = $withdrawals->fetch_assoc()): ?>
            <tr>
                <td><?php echo $row['id']; ?></td>
                <td><?php echo htmlspecialchars($row['first_name']); ?> (ID: <?php echo $row['user_id']; ?>)</td>
                <td><?php echo number_format($row['amount'], 2); ?> BDT</td>
                <td><?php echo htmlspecialchars($row['method']); ?></td>
                <td><?php echo htmlspecialchars($row['account_number']); ?></td>
                <td><?php echo date("d M, Y h:i A", strtotime($row['requested_at'])); ?></td>
                <td><span class="status <?php echo $row['status']; ?>"><?php echo ucfirst($row['status']); ?></span></td>
                <td>
                    <?php if($row['status'] === 'pending'): ?>
                        <form method="POST" style="display:inline;">
                            <input type="hidden" name="request_id" value="<?php echo $row['id']; ?>">
                            <button type="submit" name="action" value="approve" class="action-btn" style="background:#28a745;">Approve</button>
                            <button type="submit" name="action" value="reject" class="action-btn" style="background:#dc3545;">Reject</button>
                        </form>
                    <?php endif; ?>
                </td>
            </tr>
        <?php endwhile; ?>
    </tbody>
</table>

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