<?php
$pageTitle = 'Withdrawal Requests';
include_once 'includes/header.php';

// --- Permission Check ---
requirePermission('withdrawals:view');

$db = new Database();
$settingModel = new Setting();
$settings = $settingModel->getAll();
$currency_symbol = ($settings['system_currency'] ?? 'USD') === 'ZMW' ? 'K' : '$';

$current_admin_role = $_SESSION['user_role'] ?? $_SESSION['admin_user_role'] ?? '';

// Fetch pending withdrawals based on the current admin's role
$query = "
    SELECT 
        wt.id, wt.amount, wt.description, wt.status, wt.created_at,
        w.entity_type, 
        w.entity_id,
        u.first_name, u.last_name, u.email as user_email,
        c.name as club_name
    FROM wallet_transactions wt
    JOIN wallets w ON wt.wallet_id = w.id
    LEFT JOIN users u ON (w.entity_type = 'user' AND w.entity_id = u.id)
    LEFT JOIN clubs c ON (w.entity_type = 'club' AND w.entity_id = c.id)
    WHERE wt.type = 'withdrawal'
";

if (in_array($current_admin_role, ['finance_manager', 'admin', 'super_admin'])) {
    // Finance Managers, Admins, and Super Admins can see all withdrawal history.
    // Actionable items are determined by the UI logic below.
    // No additional filter needed
} else {
    // Fallback for safety - show nothing if role is unexpected
    $query .= " AND 1=0";
}

$query .= " ORDER BY wt.created_at DESC";

$db->query($query);
$pending_withdrawals = $db->resultSet();

// --- Fetch Board/Manual Withdrawal Requests (Super Admin Only) ---
$board_requests = [];
if ($current_admin_role === 'super_admin') {
    $db->query("SELECT wr.*, u.first_name, u.last_name, w.entity_type 
                FROM withdrawal_requests wr 
                JOIN wallets w ON wr.wallet_id = w.id
                LEFT JOIN users u ON wr.requested_by = u.id 
                WHERE wr.status = 'pending' 
                ORDER BY wr.created_at ASC");
    $board_requests = $db->resultSet();
}

// --- Accurate Count for UI ---
// The main query fetches all relevant records for the role (including history for admins).
// This new logic filters that list to get an accurate count for the "Pending Your Approval" badge.
$actionable_count = 0;
if (in_array($current_admin_role, ['finance_manager', 'admin', 'super_admin'])) {
    $actionable_count = count(array_filter($pending_withdrawals, fn($req) => in_array($req->status, ['pending', 'pending_finance']) || empty($req->status)));
    $actionable_count += count($board_requests);
}

include_once 'includes/sidebar.php';
?>

<h1>Withdrawal Requests</h1>
<p>Review and process pending withdrawal requests.</p>

<?php if (isset($_SESSION['flash_message'])): ?>
    <?php 
    $msg = $_SESSION['flash_message'];
    $type = is_array($msg) ? ($msg['type'] ?? 'success') : 'success';
    $text = is_array($msg) ? ($msg['text'] ?? '') : $msg;
    unset($_SESSION['flash_message']);
    ?>
    <div class="message <?php echo $type; ?>">
        <?php echo $text; ?>
    </div>
<?php endif; ?>

<div class="dashboard-section">
    <?php if (!empty($board_requests)): ?>
    <h2 class="dashboard-title">Board / Manual Requests</h2>
    <div class="table-wrapper" style="margin-bottom: 30px;">
        <table class="styled-table">
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Source</th>
                    <th>Requested By</th>
                    <th>Amount</th>
                    <th>Details</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($board_requests as $req): ?>
                    <tr>
                        <td><?php echo date('d M Y', strtotime($req->created_at)); ?></td>
                        <td>
                            <span class="badge" style="background: #eee; padding: 2px 6px; border-radius: 4px; text-transform: uppercase; font-size: 0.8rem;">
                                <?php echo htmlspecialchars($req->entity_type); ?> Wallet
                            </span>
                        </td>
                        <td><?php echo htmlspecialchars($req->first_name . ' ' . $req->last_name); ?></td>
                        <td><strong><?php echo $currency_symbol . number_format($req->amount, 2); ?></strong></td>
                        <td><?php echo htmlspecialchars($req->details); ?></td>
                        <td>
                            <form action="approve_withdrawal.php" method="POST" style="display:inline;" onsubmit="return confirm('Approve this withdrawal? Funds will be deducted.');">
                                <input type="hidden" name="request_id" value="<?php echo $req->id; ?>">
                                <input type="hidden" name="action" value="approve">
                                <button type="submit" class="btn-sm btn-success">Approve</button>
                            </form>
                            <form action="approve_withdrawal.php" method="POST" style="display:inline;" onsubmit="return confirm('Reject this request?');">
                                <input type="hidden" name="request_id" value="<?php echo $req->id; ?>">
                                <input type="hidden" name="action" value="reject">
                                <button type="submit" class="btn-sm btn-danger">Reject</button>
                            </form>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>

    <h2 class="dashboard-title">Requests Pending Your Action (<?php echo $actionable_count; ?>)</h2>
    <div class="table-wrapper">
        <?php if (empty($pending_withdrawals)): ?>
            <p class="no-data-msg">There are no withdrawal requests pending your action.</p>
        <?php else: ?>
            <table class="styled-table">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>From</th>
                        <th>Amount</th>
                        <th>Details</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($pending_withdrawals as $request): ?>
                        <tr>
                            <td><?php echo date('d M Y, H:i', strtotime($request->created_at)); ?></td>
                            <td>
                                <?php 
                                if ($request->entity_type === 'user') {
                                    echo htmlspecialchars($request->first_name . ' ' . $request->last_name);
                                } elseif ($request->entity_type === 'club') {
                                    echo htmlspecialchars($request->club_name);
                                }
                                ?>
                                <br><small><?php echo htmlspecialchars($request->user_email); ?></small>
                            </td>
                            <td><strong><?php echo $currency_symbol; ?> <?php echo number_format($request->amount, 2); ?></strong></td>
                            <td><?php echo nl2br(htmlspecialchars($request->description)); ?></td>
                            <td>
                                <?php 
                                    $display_status = $request->status ?: 'Pending';
                                    if (in_array($request->status, ['pending', 'pending_finance']) || empty($request->status)) {
                                        $display_status = 'Pending Approval';
                                    }
                                ?>
                                <span class="status-badge status-<?php echo strtolower($request->status ?: 'pending'); ?>"><?php echo ucwords(str_replace('_', ' ', $display_status)); ?></span>
                            </td>
                            <td>
                                <?php if (in_array($current_admin_role, ['finance_manager', 'admin', 'super_admin']) && (in_array($request->status, ['pending', 'pending_finance']) || empty($request->status))): ?>
                                <form action="withdrawal_process.php" method="POST" style="display:inline;">
                                    <input type="hidden" name="transaction_id" value="<?php echo $request->id; ?>">
                                    <button type="submit" name="action" value="approve" class="btn-sm btn-success">Approve</button>
                                    <button type="button" class="btn-sm btn-danger" onclick="showRejectModal(<?php echo $request->id; ?>)">Reject</button>
                                </form>
                                <?php else: ?>
                                    <span class="text-muted" style="font-size: 0.85rem; color: #777;">View Only</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
</div>

<!-- Reject Modal -->
<div id="rejectModal" class="modal">
    <div class="modal-content" style="max-width: 450px; padding: 0;">
        <div class="modal-header">
            <h3>Reason for Rejection</h3>
            <button class="modal-close-btn" onclick="closeRejectModal()">&times;</button>
        </div>
        <form action="withdrawal_process.php" method="POST">
            <div class="modal-body">
                <p>Please provide a reason for rejecting this withdrawal request. This note will be visible to the user.</p>
                <input type="hidden" name="action" value="reject">
                <input type="hidden" name="transaction_id" id="reject_transaction_id">
                <div class="form-group">
                    <label for="rejection_note">Rejection Note (optional)</label>
                    <textarea name="note" id="rejection_note" rows="3" placeholder="e.g., Invalid bank details provided."></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeRejectModal()">Cancel</button>
                <button type="submit" class="btn btn-danger">Confirm Rejection</button>
            </div>
        </form>
    </div>
</div>

<script>
const rejectModal = document.getElementById('rejectModal');
function showRejectModal(id) {
    document.getElementById('reject_transaction_id').value = id;
    rejectModal.classList.add('show');
}
function closeRejectModal() {
    rejectModal.classList.remove('show');
}
window.onclick = (e) => { if (e.target === rejectModal) closeRejectModal(); };
</script>

<style>
.modal {
    display: none;
    position: fixed;
    z-index: 2000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgba(0,0,0,0.6);
    align-items: center;
    justify-content: center;
}
.modal.show {
    display: flex;
}
.modal-header {
    padding: 15px 20px;
    border-bottom: 1px solid #eee;
}
.modal-body {
    padding: 20px;
}
.modal-body p {
    font-size: 0.9rem;
    color: #666;
    margin-top: 0;
}
.modal-footer {
    padding: 15px 20px;
    background-color: #f9f9f9;
    border-top: 1px solid #eee;
    border-radius: 0 0 8px 8px;
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}
.status-completed { background: #d4edda; color: #155724; }
.status-rejected, .status-failed { background: #f8d7da; color: #721c24; }
.status-pending, .status-pending_finance { background: #fff3cd; color: #856404; }
</style>

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