<?php
require_once '../core/bootstrap.php';

// --- Authentication and Role Check ---
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'club_manager') {
    header('Location: login.php');
    exit();
}

$pageTitle = 'Club Finances';
include 'includes/header.php';

$manager_id = $_SESSION['user_id'];

// --- Instantiate Models ---
$clubManagerModel = new ClubManager();
$fineModel = new Fine();
$settingModel = new Setting();
$clubModel = new Club(); // Added for revenue
$paymentModel = new Payment();
$walletModel = new Wallet();
$teamModel = new Team();

// --- Fetch Data ---
// Get the club managed by the logged-in user
$club = $clubManagerModel->getClubByManagerId($manager_id);

if (!$club) {
    echo "<div class='page-content'><p class='no-data-msg'>You are not currently assigned as a manager to any club.</p></div>";
    include 'includes/footer.php';
    exit();
}

$club_id = $club->id;
$club_wallet = $walletModel->getOrCreateWallet('club', $club_id);
$all_fines = $fineModel->getAllFinesForTeam($club_id);
$club_teams = $teamModel->getAllByClub($club_id);

// --- Calculate Financial Summary ---
$total_fines_issued = 0;
$total_fines_paid = 0;
$total_fines_outstanding = 0;
$outstanding_fines = [];
$paid_fines = [];

foreach ($all_fines as $fine) {
    $total_fines_issued += $fine->amount;
    if ($fine->status === 'paid') {
        $total_fines_paid += $fine->amount;
        $paid_fines[] = $fine;
    } else {
        $total_fines_outstanding += $fine->amount;
        $outstanding_fines[] = $fine;
    }
}

$total_membership_revenue = $clubModel->getMembershipRevenueByClub($club_id); // Fetch revenue
$chart_data = $clubModel->getFinancialsOverTime($club_id);

// Calculate Commissions Paid (Gross Revenue - Net Revenue in Wallet)
$net_membership_revenue = $walletModel->getNetRevenueFromMemberships($club_wallet->id);
$total_commissions_paid = max(0, $total_membership_revenue - $net_membership_revenue);

// Fetch Payment Transactions
$transactions = $paymentModel->getByUserId($manager_id);

// --- Get Currency Symbol from Settings ---
$settings = $settingModel->getAll();
$currency_symbol = '$';
if (($settings['system_currency'] ?? 'USD') === 'ZMW') {
    $currency_symbol = 'K';
} elseif (($settings['system_currency'] ?? 'USD') === 'EUR') {
    $currency_symbol = '€';
}
$currency_code = $settings['system_currency'] ?? 'USD';

$primary_color = $settings['primary_color'] ?? '#3498db';
$secondary_color = $settings['secondary_color'] ?? '#2c3e50';

?>

<div class="team-dashboard-hero">
    <div class="hero-content-wrapper">
        <div class="hero-header-row">
            <div class="team-identity">
                <img src="<?php echo htmlspecialchars($club->logo); ?>" alt="<?php echo htmlspecialchars($club->name); ?>" class="hero-team-logo">
                <div class="team-details">
                    <h1>Club Finances</h1>
                    <span class="manager-badge"><?php echo htmlspecialchars($club->name); ?></span>
                </div>
            </div>
            <div class="hero-actions">
                <a href="my_club.php?tab=finances" class="btn btn-hero-secondary"><i class="fa-solid fa-arrow-left"></i> Back</a>
            </div>
        </div>
    </div>
</div>

<div class="page-content">
    <!-- Wallet Section -->
    <div class="dashboard-section">
        <div class="wallet-overview-card">
            <div class="wallet-details">
                <span class="label">Club Wallet Balance</span>
                <span class="balance"><?php echo $currency_symbol . number_format($club_wallet->balance, 2); ?></span>
                <span class="sub-text"><i class="fa-solid fa-check-circle"></i> Available for withdrawals, transfers, and payments</span>
            </div>
            <div class="wallet-buttons">
                <button class="btn btn-outline" onclick="openTeamTransferModal()"><i class="fa-solid fa-money-bill-transfer"></i> Transfer to Team</button>
                <button class="btn btn-outline" onclick="openWithdrawModal()"><i class="fa-solid fa-building-columns"></i> Withdraw</button>
                <button class="btn" onclick="openTopUpModal()"><i class="fa-solid fa-circle-plus"></i> Top Up</button>
            </div>
        </div>
    </div>

    <!-- Financial Summary Cards -->
    <div class="dashboard-section">
        <h2 class="dashboard-title">Financial Overview</h2>
        <div class="stats-card-grid">
            <div class="stat-card">
                <div class="stat-value" style="color: #2ecc71;"><?php echo $currency_symbol . number_format($total_membership_revenue, 2); ?></div>
                <div class="stat-label">Membership Revenue</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" style="color: #e67e22;"><?php echo $currency_symbol . number_format($total_commissions_paid, 2); ?></div>
                <div class="stat-label">Commissions Paid</div>
            </div>
            <div class="stat-card">
                <div class="stat-value"><?php echo $currency_symbol . number_format($total_fines_issued, 2); ?></div>
                <div class="stat-label">Total Fines Issued</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" style="color: #2ecc71;"><?php echo $currency_symbol . number_format($total_fines_paid, 2); ?></div>
                <div class="stat-label">Total Paid</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" style="color: #e74c3c;"><?php echo $currency_symbol . number_format($total_fines_outstanding, 2); ?></div>
                <div class="stat-label">Total Outstanding</div>
            </div>
        </div>
    </div>

    <!-- Chart Section -->
    <div class="dashboard-section">
        <h2 class="dashboard-title">Monthly Financials (Revenue vs Fines)</h2>
        <div class="chart-wrapper" style="max-width: 800px; margin: auto; position: relative;">
            <canvas id="financialsChart"></canvas>
        </div>
    </div>

    <!-- Outstanding Fines Payment Section -->
    <div class="dashboard-section">
        <h2 class="dashboard-title">Outstanding Payments</h2>
        <?php if (!empty($outstanding_fines)): ?>
            <form action="club_create_payment_session.php" method="POST" id="fines-payment-form">
                <input type="hidden" name="club_id" value="<?php echo $club_id; ?>">
                <input type="hidden" name="redirect_to" value="club_finances.php">
                <div class="table-wrapper">
                    <table class="styled-table">
                        <thead>
                            <tr>
                                <th style="width: 40px; text-align: center;">
                                    <input type="checkbox" id="select-all-fines">
                                </th>
                                <th>Entity</th>
                                <th>Reason</th>
                                <th>Amount</th>
                                <th>Date Issued</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($outstanding_fines as $fine): ?>
                                <tr onclick="toggleRowCheckbox(event, this)">
                                    <td style="text-align: center;">
                                        <input type="checkbox" name="fine_ids[]" value="<?php echo $fine->id; ?>" class="fine-checkbox" data-amount="<?php echo $fine->amount; ?>">
                                    </td>
                                    <td>
                                        <?php
                                        if ($fine->entity_type === 'player') {
                                            echo htmlspecialchars($fine->first_name . ' ' . $fine->last_name);
                                        } elseif ($fine->entity_type === 'club') {
                                            echo htmlspecialchars($fine->club_name_fined);
                                        }
                                        ?>
                                    </td>
                                    <td><?php echo htmlspecialchars($fine->reason); ?></td>
                                    <td><?php echo $currency_symbol; ?><?php echo number_format($fine->amount, 2); ?></td>
                                    <td><?php echo date('d M Y', strtotime($fine->issued_date)); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <div class="payment-summary">
                    <div class="total-amount">Total Selected: <span id="total-selected-amount"><?php echo $currency_symbol; ?>0.00</span></div>
                    <input type="hidden" name="wallet_type" value="club">
                    <button type="submit" formaction="pay_fines_via_wallet.php" id="pay-wallet-btn" class="btn" disabled>Pay with Wallet</button>
                </div>
            </form>
        <?php else: ?>
            <p class="no-data-msg">There are no outstanding fines for your club.</p>
        <?php endif; ?>
    </div>

    <!-- Payment Transactions Table -->
    <div class="dashboard-section">
        <h2 class="dashboard-title">Payment Transactions</h2>
        <div class="table-wrapper">
            <?php if (!empty($transactions)): ?>
                <table class="styled-table">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Reference</th>
                            <th>Amount</th>
                            <th>Method</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($transactions as $txn): ?>
                            <tr>
                                <td><?php echo date('d M Y, H:i', strtotime($txn->created_at)); ?></td>
                                <td><?php echo htmlspecialchars($txn->transaction_ref); ?></td>
                                <td><?php echo $currency_symbol . number_format($txn->amount, 2); ?></td>
                                <td><?php echo ucfirst($txn->payment_gateway); ?></td>
                                <td><a href="receipt.php?ref=<?php echo $txn->transaction_ref; ?>&context=club_manager" class="btn-sm">View Receipt</a></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <p class="no-data-msg">No payment transactions found.</p>
            <?php endif; ?>
        </div>
    </div>

    <!-- Paid Fines History Table -->
    <div class="dashboard-section">
        <h2 class="dashboard-title">Fine History (Paid)</h2>
        <div class="table-wrapper">
            <?php if (!empty($paid_fines)): ?>
                <table class="styled-table">
                    <thead>
                        <tr>
                            <th>Entity</th>
                            <th>Reason</th>
                            <th>Amount</th>
                            <th>Date Issued</th>
                            <th>Date Paid</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($paid_fines as $fine): ?>
                            <tr>
                                <td>
                                    <?php
                                    if ($fine->entity_type === 'player') {
                                        echo htmlspecialchars($fine->first_name . ' ' . $fine->last_name);
                                    } elseif ($fine->entity_type === 'club') {
                                        echo htmlspecialchars($fine->club_name_fined);
                                    }
                                    ?>
                                </td>
                                <td><?php echo htmlspecialchars($fine->reason); ?></td>
                                <td><?php echo $currency_symbol; ?><?php echo number_format($fine->amount, 2); ?></td>
                                <td><?php echo date('d M Y', strtotime($fine->issued_date)); ?></td>
                                <td><?php echo $fine->paid_date ? date('d M Y', strtotime($fine->paid_date)) : 'N/A'; ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <p class="no-data-msg">No fines have been paid yet.</p>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Payment Confirmation Modal -->
<div id="paymentConfirmationModal" class="modal">
    <div class="modal-content" style="max-width: 400px;">
        <div class="modal-header">
            <h3>Confirm Payment</h3>
            <button class="modal-close-btn" onclick="closePaymentModal()">&times;</button>
        </div>
        <div class="modal-body">
            <p id="payment-confirmation-text" style="font-size: 1.1rem; margin-bottom: 20px;"></p>
            <div class="modal-actions" style="display: flex; gap: 10px; justify-content: flex-end;">
                <button class="btn btn-secondary" onclick="closePaymentModal()">Cancel</button>
                <button class="btn" id="confirm-payment-btn">Proceed to Pay</button>
            </div>
        </div>
    </div>
</div>

<!-- Team Transfer Modal -->
<div id="teamTransferModal" class="modal">
    <div class="modal-content" style="max-width: 450px;">
        <div class="modal-header">
            <h3>Transfer from Club Wallet</h3>
            <button class="modal-close-btn" onclick="closeTeamTransferModal()">&times;</button>
        </div>
        <form action="club_wallet_transfer_process.php" method="POST">
            <div class="form-group">
                <label for="team_id">Recipient Team</label>
                <select name="team_id" id="team_id" required class="form-control">
                    <option value="">-- Select a Team --</option>
                    <?php foreach ($club_teams as $team): ?>
                        <option value="<?php echo $team->id; ?>"><?php echo htmlspecialchars($team->name); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label for="transfer_amount">Amount (<?php echo $currency_symbol; ?>)</label>
                <input type="number" name="amount" id="transfer_amount" step="0.01" min="1" required class="form-control">
            </div>
            <div class="form-group">
                <label for="description">Description (Optional)</label>
                <input type="text" name="description" id="description" class="form-control" placeholder="e.g., Budget allocation">
            </div>
            <button type="submit" class="btn btn-block">Confirm Transfer</button>
        </form>
    </div>
</div>

<!-- Withdrawal Modal -->
<div id="withdrawModal" class="modal">
    <div class="modal-content" style="max-width: 450px;">
        <div class="modal-header">
            <h3>Withdraw Funds</h3>
            <button class="modal-close-btn" onclick="closeWithdrawModal()">&times;</button>
        </div>
        <form action="club_withdrawal_process.php" method="POST">
            <div class="form-group">
                <label for="withdraw_amount">Amount (<?php echo $currency_symbol; ?>)</label>
                <input type="number" name="amount" id="withdraw_amount" step="0.01" min="1" required class="form-control">
            </div>
            <div class="form-group">
                <label for="withdraw_details">Bank/Payment Details</label>
                <textarea name="details" id="withdraw_details" required class="form-control" rows="3" placeholder="Bank Name, Account Number, etc."></textarea>
            </div>
            <button type="submit" class="btn btn-block">Request Withdrawal</button>
        </form>
    </div>
</div>

<!-- Top Up Modal -->
<div id="topUpModal" class="modal">
    <div class="modal-content" style="max-width: 400px;">
        <div class="modal-header">
            <h3>Top Up Club Wallet</h3>
            <button class="modal-close-btn" onclick="closeTopUpModal()">&times;</button>
        </div>
        <div class="form-group">
            <label for="topup_amount">Amount (<?php echo $currency_symbol; ?>)</label>
            <input type="number" id="topup_amount" class="form-control" min="1" step="0.01" placeholder="Enter amount">
        </div>
        <button type="button" id="confirm-topup-btn" class="btn btn-block">Proceed to Payment</button>
    </div>
</div>

<!-- Toast Container -->
<div id="toast-container"></div>

<style>
/* Ensure modal is hidden by default */
.modal { display: none; }

.wallet-overview-card {
    background: #fff;
    border-radius: 12px;
    padding: 25px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 4px 15px rgba(0,0,0,0.05);
    border: 1px solid #eee;
    flex-wrap: wrap;
    gap: 20px;
}
.wallet-details {
    display: flex;
    flex-direction: column;
}
.wallet-details .label {
    font-size: 0.9rem;
    color: #7f8c8d;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-bottom: 5px;
}
.wallet-details .balance {
    font-size: 2.5rem;
    font-weight: 800;
    color: var(--primary-color);
    line-height: 1.1;
}
.wallet-details .sub-text {
    font-size: 0.85rem;
    color: #27ae60;
    margin-top: 8px;
    display: flex;
    align-items: center;
    gap: 5px;
}
.wallet-buttons {
    display: flex;
    gap: 10px;
}
.btn-outline {
    background: transparent;
    border: 1px solid var(--primary-color);
    color: var(--primary-color);
}
.btn-outline:hover {
    background: var(--primary-color);
    color: white;
}

/* Toast Notifications */
#toast-container { position: fixed; top: 20px; right: 20px; z-index: 9999; }
.toast {
    background: white;
    padding: 15px 20px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    animation: slideIn 0.3s ease-out forwards;
    border-left: 4px solid #333;
    min-width: 250px;
}
.toast.hide { animation: slideOut 0.3s ease-in forwards; }
.toast-success { border-left-color: #27ae60; }
.toast-error { border-left-color: #e74c3c; }
.toast-info { border-left-color: #3498db; }

@keyframes slideIn { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
@keyframes slideOut { from { transform: translateX(0); opacity: 1; } to { transform: translateX(100%); opacity: 0; } }
</style>

<!-- Include Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const selectAllCheckbox = document.getElementById('select-all-fines');
    const fineCheckboxes = document.querySelectorAll('.fine-checkbox');
    const payWalletButton = document.getElementById('pay-wallet-btn');
    const totalAmountSpan = document.getElementById('total-selected-amount');
    
    // Modals
    const teamTransferModal = document.getElementById('teamTransferModal');
    const withdrawModal = document.getElementById('withdrawModal');
    const topUpModal = document.getElementById('topUpModal');
    
    // Payment Modal Elements
    const paymentModal = document.getElementById('paymentConfirmationModal');
    const paymentText = document.getElementById('payment-confirmation-text');
    const confirmPaymentBtn = document.getElementById('confirm-payment-btn');
    let paymentData = null;

    // User Data for Top Up
    const userEmail = <?php echo json_encode($user_email ?? ''); ?>;
    const userName = <?php echo json_encode($user_name ?? ''); ?>;

    // Wallet Data
    const clubWalletBalance = <?php echo floatval($club_wallet->balance ?? 0); ?>;
    const currencySymbol = '<?php echo $currency_symbol; ?>';

    // --- Toast Notification Logic ---
    function showToast(message, type = 'success') {
        const container = document.getElementById('toast-container');
        if (!container) return;
        
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`;
        
        let icon = '';
        if (type === 'success') icon = '<i class="fa-solid fa-check-circle" style="margin-right: 10px;"></i>';
        if (type === 'error') icon = '<i class="fa-solid fa-circle-exclamation" style="margin-right: 10px;"></i>';
        
        toast.innerHTML = icon + message;
        container.appendChild(toast);
        
        setTimeout(() => {
            toast.classList.add('hide');
            toast.addEventListener('transitionend', () => toast.remove());
        }, 3000);
    }

    // Check for URL status params
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.has('error')) {
        showToast(urlParams.get('error'), 'error');
        window.history.replaceState({}, document.title, window.location.pathname + window.location.hash);
    }
    if (urlParams.get('status') === 'success' && urlParams.has('msg')) {
        showToast(urlParams.get('msg'), 'success');
        window.history.replaceState({}, document.title, window.location.pathname + window.location.hash);
    }

    function updateTotal() {
        let total = 0;
        let selectedCount = 0;
        fineCheckboxes.forEach(checkbox => {
            if (checkbox.checked) {
                total += parseFloat(checkbox.dataset.amount);
                selectedCount++;
            }
        });
        totalAmountSpan.textContent = '<?php echo $currency_symbol; ?>' + total.toFixed(2);
        if(payWalletButton) payWalletButton.disabled = selectedCount === 0;
    }

    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', function() {
            fineCheckboxes.forEach(checkbox => checkbox.checked = this.checked);
            updateTotal();
        });
    }

    fineCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', updateTotal);
        // Prevent row click from triggering twice
        checkbox.addEventListener('click', function(e) {
            e.stopPropagation();
        });
    });

    // Row click handler
    window.toggleRowCheckbox = function(e, row) {
        // Don't toggle if clicking directly on the checkbox (handled by click listener above)
        if (e.target.type === 'checkbox') return;
        
        const checkbox = row.querySelector('.fine-checkbox');
        checkbox.checked = !checkbox.checked;
        updateTotal();
    };

    if (fineCheckboxes.length > 0) {
        updateTotal();
    }

    // --- Payment Modal Logic ---
    window.openTeamTransferModal = function() { if(teamTransferModal) teamTransferModal.classList.add('show'); }
    window.closeTeamTransferModal = function() { if(teamTransferModal) teamTransferModal.classList.remove('show'); }

    window.openWithdrawModal = function() { if(withdrawModal) withdrawModal.classList.add('show'); }
    window.closeWithdrawModal = function() { if(withdrawModal) withdrawModal.classList.remove('show'); }

    window.openTopUpModal = function() { if(topUpModal) topUpModal.classList.add('show'); }
    window.closeTopUpModal = function() { if(topUpModal) topUpModal.classList.remove('show'); }

    window.closePaymentModal = function() {
        if(paymentModal) paymentModal.classList.remove('show');
    };

    window.addEventListener('click', (e) => { 
        if (e.target === paymentModal) closePaymentModal();
        if (e.target === teamTransferModal) closeTeamTransferModal();
        if (e.target === withdrawModal) closeWithdrawModal();
        if (e.target === topUpModal) closeTopUpModal();
    });

    // --- Wallet Payment Logic ---
    if (payWalletButton) {
        payWalletButton.addEventListener('click', function(e) {
            // The button is type="submit" with formaction, so it will submit the form.
            // We just need to confirm first.
            e.preventDefault();
            console.log('Wallet Payment (Finances): Initiated');

            let selectedFines = [];
            let totalAmount = 0;
            
            fineCheckboxes.forEach(checkbox => {
                if (checkbox.checked) {
                    selectedFines.push(checkbox.value);
                    totalAmount += parseFloat(checkbox.dataset.amount);
                }
            });
            console.log('Wallet Payment (Finances): Selected Fines', selectedFines);
            console.log('Wallet Payment (Finances): Total Amount', totalAmount);

            if (selectedFines.length === 0) return;

            // Check Balance
            if (clubWalletBalance < totalAmount) {
                // Insufficient Funds
                const needed = totalAmount - clubWalletBalance;
                showToast(`Insufficient funds. You need ${currencySymbol}${needed.toFixed(2)} more.`, 'error');
                openTopUpModal();
                return;
            }

            // Show Confirmation Modal for Wallet
            paymentText.textContent = `Pay ${selectedFines.length} fines (${'<?php echo $currency_symbol; ?>' + totalAmount.toFixed(2)}) using Club Wallet?`;
            paymentModal.classList.add('show');
            
            // Clear paymentData to prevent interference from Flutterwave handler
            paymentData = null;

            // Override confirm button behavior for wallet
            confirmPaymentBtn.onclick = function() {
                console.log('Wallet Payment (Finances): Confirmed');
                const form = document.getElementById('fines-payment-form');
                console.log('Wallet Payment (Finances): Form found', form);
                
                // Append hidden input to simulate button click
                let hiddenInput = form.querySelector('input[name="pay_via_wallet"]');
                if (!hiddenInput) {
                    hiddenInput = document.createElement('input');
                    hiddenInput.type = 'hidden';
                    hiddenInput.name = 'pay_via_wallet';
                    form.appendChild(hiddenInput);
                }
                hiddenInput.value = '1';
                console.log('Wallet Payment (Finances): Hidden input set');

                // Ensure we submit to the wallet processor
                form.action = 'pay_fines_via_wallet.php'; 
                console.log('Wallet Payment (Finances): Submitting to', form.action);
                form.submit();
                closePaymentModal();
            };
        });
    }

    if (confirmPaymentBtn) {
        confirmPaymentBtn.addEventListener('click', function() {
            if (!paymentData) return;
            closePaymentModal();
            
            const { type, totalAmount, publicKey, userEmail, originalBtnText, metaData } = paymentData;
            
            const txRef = 'club_topup_' + Date.now();

            let paymentSubmitted = false;

            try {
                FlutterwaveCheckout({
                    public_key: publicKey,
                    tx_ref: txRef,
                    amount: totalAmount,
                    currency: "<?php echo $currency_code; ?>",
                    payment_options: "card,mobilemoney,ussd",
                    customer: {
                        email: userEmail,
                        name: userName,
                    },
                    meta: metaData,
                    customizations: {
                        title: <?php echo json_encode($club->name ?? 'Club Top Up'); ?>,
                        description: "Wallet Top Up",
                        logo: <?php echo json_encode($club->logo ?? ''); ?>,
                    },
                    callback: function(data) {
                        paymentSubmitted = true;
                        // Send transaction details to backend for verification (reusing existing endpoint logic)
                        fetch('flutterwave_verify.php', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'Accept': 'application/json'
                            },
                            body: JSON.stringify({
                                transaction_id: data.transaction_id,
                                tx_ref: data.tx_ref,
                                payment_context: 'club_wallet_deposit'
                            })
                        })
                        .then(response => response.json())
                        .then(result => {
                            if (result.status === 'success') {
                            showToast('Payment processed successfully!', 'success');
                            if (successModal && viewReceiptBtn) {
                                viewReceiptBtn.onclick = () => window.location.href = result.redirect_url;
                                successModal.classList.add('show');
                            } else {
                                window.location.href = result.redirect_url;
                            }
                            } else {
                                showToast(result.message || 'Payment verification failed.', 'error');
                            }
                        })
                        .catch(error => {
                            console.error('Verification Error:', error);
                            showToast('An error occurred while verifying the payment.', 'error');
                        });
                    },
                    onclose: function() {
                        if (!paymentSubmitted) {
                            showToast('Payment cancelled by user.', 'info');
                        }
                    }
                });
            } catch (error) {
                console.error("Flutterwave Initialization Error:", error);
                alert("Failed to initialize payment gateway.");
            }
        });
    }

    // --- Top Up Logic ---
    const confirmTopUpBtn = document.getElementById('confirm-topup-btn');
    if (confirmTopUpBtn) {
        confirmTopUpBtn.addEventListener('click', function() {
            const amountInput = document.getElementById('topup_amount');
            const amount = parseFloat(amountInput.value);

            if (!amount || amount <= 0) {
                showToast("Please enter a valid amount.", "error");
                return;
            }

            const publicKey = "<?php echo $settings['flutterwave_public_key'] ?? ''; ?>";
            if (!publicKey) {
                showToast("Payment gateway not configured.", "error");
                return;
            }

            closeTopUpModal();

            paymentData = {
                type: 'topup',
                totalAmount: amount,
                publicKey: publicKey,
                userEmail: userEmail,
                metaData: {
                    payment_context: 'club_wallet_deposit',
                    club_id: <?php echo $club_id; ?>
                }
            };

            // Show confirmation modal before processing top-up
            paymentText.textContent = `Top up club wallet with ${currencySymbol}${amount.toFixed(2)}?`;
            paymentModal.classList.add('show');
        });
    }

    function processTopUp(data) {
        const txRef = 'club_topup_' + Date.now();
        
        FlutterwaveCheckout({
            public_key: data.publicKey,
            tx_ref: txRef,
            amount: data.totalAmount,
            currency: "<?php echo $currency_code; ?>",
            payment_options: "card,mobilemoney,ussd",
            customer: {
                email: data.userEmail,
                name: userName,
            },
            meta: data.metaData,
            customizations: {
                title: <?php echo json_encode($club->name ?? 'Club Top Up'); ?>,
                description: "Wallet Top Up",
                logo: <?php echo json_encode($club->logo ?? ''); ?>,
            },
            callback: function(response) {
                // Verify transaction on backend
                fetch('flutterwave_verify.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
                    body: JSON.stringify({
                        transaction_id: response.transaction_id,
                        tx_ref: response.tx_ref,
                        payment_context: 'club_wallet_deposit'
                    })
                })
                .then(res => res.json())
                .then(result => {
                    if (result.status === 'success') {
                        showToast('Wallet topped up successfully!', 'success');
                        setTimeout(() => window.location.reload(), 2000);
                    } else {
                        showToast(result.message || 'Verification failed.', 'error');
                    }
                });
            },
            onclose: function() { /* Do nothing */ }
        });
    }

    // --- Chart.js Implementation ---
    const chartData = <?php echo json_encode($chart_data); ?>;
    if (chartData.length > 0) {
        const labels = chartData.map(d => d.month);
        const revenueData = chartData.map(d => d.revenue);
        const finesData = chartData.map(d => d.fines);

        const ctx = document.getElementById('financialsChart').getContext('2d');
        new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [
                    {
                        label: 'Membership Revenue',
                        data: revenueData,
                        backgroundColor: 'rgba(46, 204, 113, 0.7)', // green
                        borderColor: 'rgba(46, 204, 113, 1)',
                        borderWidth: 1
                    },
                    {
                        label: 'Fines Issued',
                        data: finesData,
                        backgroundColor: 'rgba(231, 76, 60, 0.7)', // red
                        borderColor: 'rgba(231, 76, 60, 1)',
                        borderWidth: 1
                    }
                ]
            },
            options: {
                responsive: true,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return '<?php echo $currency_symbol; ?>' + value;
                            }
                        }
                    }
                },
                plugins: {
                    legend: { position: 'top' },
                    tooltip: {
                        callbacks: { label: (context) => `${context.dataset.label}: ${new Intl.NumberFormat('en-US', { style: 'currency', currency: '<?php echo $currency_code; ?>' }).format(context.parsed.y)}` }
                    }
                }
            }
        });
    }
});
</script>

<style>
:root {
    --hero-gradient: linear-gradient(135deg, <?php echo $primary_color; ?> 0%, <?php echo $secondary_color; ?> 100%);
}

/* Transparent Header Override */
header {
    background: transparent !important;
    box-shadow: none !important;
    position: absolute !important;
    width: 100%;
    top: 0;
    z-index: 1000;
}

.team-dashboard-hero {
    background: var(--hero-gradient);
    color: white;
    padding: 6rem 20px 3rem 20px;
    border-radius: 0 0 30px 30px;
    margin-bottom: 2rem;
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    margin-top: 0;
}

.hero-content-wrapper {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0;
}

.hero-header-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.team-identity {
    display: flex;
    align-items: center;
    gap: 1.5rem;
}

.hero-team-logo {
    width: 80px;
    height: 80px;
    object-fit: contain;
    background: white;
    border-radius: 50%;
    padding: 5px;
    box-shadow: 0 4px 10px rgba(0,0,0,0.1);
}

.team-details h1 {
    margin: 0 0 5px 0;
    font-size: 2rem;
    font-weight: 700;
}

.manager-badge {
    background: rgba(255,255,255,0.2);
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.9rem;
    backdrop-filter: blur(5px);
}

.hero-actions {
    display: flex;
    gap: 10px;
}

.btn-hero-secondary {
    background: rgba(255,255,255,0.2);
    color: white;
    border: 1px solid rgba(255,255,255,0.3);
}
.btn-hero-secondary:hover { background: rgba(255,255,255,0.3); }

.btn-hero-primary {
    background: white;
    color: var(--primary-color);
    border: none;
}
.btn-hero-primary:hover { background: #f0f0f0; }

@media (max-width: 768px) {
    .hero-header-row {
        flex-direction: column;
        text-align: center;
        gap: 1.5rem;
    }
    .team-identity {
        flex-direction: column;
    }
}
</style>

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