<?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 = 'My Club';
include 'includes/header.php';

$manager_id = $_SESSION['user_id'];

// --- Instantiate Models ---
$clubManagerModel = new ClubManager();
$teamModel = new Team();
$playerModel = new Player();
$fixtureModel = new Fixture();
$fineModel = new Fine();
$settingModel = new Setting();
$clubModel = new Club();
$userModel = new User();
$walletModel = new Wallet();

// --- 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;

// Fetch current user details for payment
// Robust email fetching logic
$currentUser = $userModel->findById($manager_id);
$user_email = '';
$user_name = 'Manager';

if ($currentUser) {
    // Check if object or array and extract email
    $user_email = is_object($currentUser) ? ($currentUser->email ?? '') : ($currentUser['email'] ?? '');
    
    // Extract name
    $fname = is_object($currentUser) ? ($currentUser->first_name ?? '') : ($currentUser['first_name'] ?? '');
    $lname = is_object($currentUser) ? ($currentUser->last_name ?? '') : ($currentUser['last_name'] ?? '');
    if ($fname || $lname) $user_name = trim("$fname $lname");
}

// Fallback 1: Session
if (empty($user_email)) $user_email = $_SESSION['user_email'] ?? '';
if ($user_name === 'Manager') $user_name = $_SESSION['user_name'] ?? 'Manager';

// Fallback 2: Direct DB Query (Emergency backup)
if (empty($user_email)) {
    $db = new Database();
    $db->query("SELECT email, first_name, last_name FROM users WHERE id = :id");
    $db->bind(':id', $manager_id);
    $directUser = $db->single();
    if ($directUser) {
        $user_email = $directUser->email ?? '';
        if ($user_name === 'Manager' && ($directUser->first_name || $directUser->last_name)) {
            $user_name = trim(($directUser->first_name ?? '') . ' ' . ($directUser->last_name ?? ''));
        }
    }
}

// Fetch all data related to the club
$club_teams = $teamModel->getAllByClub($club_id);
$total_players = $playerModel->countPlayersByClubId($club_id);
$next_fixtures = $fixtureModel->getUpcomingFixturesForClub($club_id, 3);
$recent_results = $fixtureModel->getRecentResultsForClub($club_id, 5);
$outstanding_fines = $fineModel->getUnpaidFinesForTeam($club_id);
$total_fines_amount = array_reduce($outstanding_fines, fn($sum, $fine) => $sum + $fine->amount, 0);
$total_membership_revenue = $clubModel->getMembershipRevenueByClub($club_id);

// Get Club Wallet
$club_wallet = $walletModel->getOrCreateWallet('club', $club_id);

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

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

// --- Registration Fee Logic ---
// Fetch League Settings for this Club
$db = new Database();
$db->query("SELECT l.reg_fee_total, l.reg_deposit_pct, l.reg_inst2_pct, l.reg_inst2_games, l.reg_inst3_pct, l.reg_inst3_games 
            FROM clubs c JOIN leagues l ON c.league_id = l.id WHERE c.id = :club_id");
$db->bind(':club_id', $club_id);
$league_settings = $db->single();

$reg_fee_total = (float)($league_settings->reg_fee_total ?? 0);
$reg_status = 'active'; // active, warning, suspended
$reg_message = '';
$reg_paid = 0;

if ($reg_fee_total > 0) {
    // Calculate amount paid specifically for registration
    // Assuming transactions with type 'registration_fee' count towards this
    // Since we don't have a specific query for this in context, we iterate the wallet transactions we have
    // Note: In a real scenario, you might want a dedicated query for total paid to avoid pagination limits
    $all_club_txns = $walletModel->getTransactions($club_wallet->id, 1000); 
    foreach ($all_club_txns as $txn) {
        if ($txn->type === 'registration_fee' && ($txn->status === 'success' || $txn->status === 'completed')) {
            $reg_paid += $txn->amount;
        }
    }

    // Get Games Played (Mocking logic as specific model method isn't in context)
    $db->query("SELECT MAX(played_count) as max_played FROM (
                    SELECT COUNT(*) as played_count 
                    FROM fixtures f 
                    JOIN teams t ON (f.home_team_id = t.id OR f.away_team_id = t.id)
                    WHERE t.club_id = :club_id AND f.status = 'finished'
                    GROUP BY t.id
                ) as counts");
    $db->bind(':club_id', $club_id);
    $games_res = $db->single();
    $games_played = (int)($games_res->max_played ?? 0);

    $deposit_due = $reg_fee_total * (($league_settings->reg_deposit_pct ?? 50) / 100);
    $inst2_due = $reg_fee_total * (($league_settings->reg_inst2_pct ?? 30) / 100);
    $inst2_games = (int)($league_settings->reg_inst2_games ?? 5);
    $inst3_due = $reg_fee_total * (($league_settings->reg_inst3_pct ?? 20) / 100);
    $inst3_games = (int)($league_settings->reg_inst3_games ?? 10);

    $amount_required = $deposit_due;
    if ($games_played >= $inst2_games) $amount_required += $inst2_due;
    if ($games_played >= $inst3_games) $amount_required += $inst3_due;

    if ($reg_paid < $amount_required) {
        $reg_status = 'suspended';
        $reg_message = "Outstanding Registration Fees! You have paid {$currency_symbol}{$reg_paid} of required {$currency_symbol}{$amount_required}.";
    }
}

// --- Determine Active Tab ---
$active_tab = $_GET['tab'] ?? 'overview';
$allowed_tabs = ['overview', 'matches', 'teams', 'finances', 'management', 'transactions'];
if (!in_array($active_tab, $allowed_tabs)) {
    $active_tab = 'overview';
}
?>

<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><?php echo htmlspecialchars($club->name); ?></h1>
                    <span class="manager-badge"><i class="fa-solid fa-user-tie"></i> Manager: <?php echo htmlspecialchars($_SESSION['user_name'] ?? 'You'); ?></span>
                </div>
            </div>
        </div>

        <div class="hero-stats-strip">
            <div class="stat-box"><span class="label">Teams</span><span class="value"><?php echo count($club_teams); ?></span></div>
            <div class="stat-box"><span class="label">Players</span><span class="value"><?php echo $total_players; ?></span></div>
            <div class="stat-box"><span class="label">Revenue</span><span class="value"><?php echo $currency_symbol . number_format($total_membership_revenue, 0); ?></span></div>
            <div class="stat-box"><span class="label">Wallet</span><span class="value"><?php echo $currency_symbol . number_format($club_wallet->balance ?? 0, 2); ?></span></div>
        </div>
        
        <div class="dashboard-nav-bar">
            <a href="?tab=overview" class="nav-tab <?php echo $active_tab === 'overview' ? 'active' : ''; ?>">Overview</a>
            <a href="?tab=matches" class="nav-tab <?php echo $active_tab === 'matches' ? 'active' : ''; ?>">Matches</a>
            <a href="?tab=teams" class="nav-tab <?php echo $active_tab === 'teams' ? 'active' : ''; ?>">Teams</a>
            <a href="?tab=finances" class="nav-tab <?php echo $active_tab === 'finances' ? 'active' : ''; ?>">Finances</a>
            <a href="?tab=transactions" class="nav-tab <?php echo $active_tab === 'transactions' ? 'active' : ''; ?>">Transactions</a>
            <a href="?tab=management" class="nav-tab <?php echo $active_tab === 'management' ? 'active' : ''; ?>">Management</a>
        </div>
    </div>
</div>

<div class="page-content">
    <div id="overview" class="tab-content <?php echo $active_tab === 'overview' ? 'active' : ''; ?>">
        <?php if ($reg_fee_total > 0): ?>
        <div class="dashboard-section" style="border-left: 5px solid <?php echo $reg_status === 'suspended' ? '#e74c3c' : '#2ecc71'; ?>;">
            <h2 class="dashboard-title">Registration Status</h2>
            <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px;">
                <div style="flex: 1; min-width: 300px;">
                    <div style="font-size: 1.1rem; font-weight: bold; color: <?php echo $reg_status === 'suspended' ? '#e74c3c' : '#2ecc71'; ?>">
                        <?php echo $reg_status === 'suspended' ? '<i class="fa-solid fa-triangle-exclamation"></i> Action Required' : '<i class="fa-solid fa-check-circle"></i> Active'; ?>
                    </div>
                    <p style="margin: 5px 0; color: #666;"><?php echo $reg_message ?: "You are up to date with your registration payments."; ?></p>
                    <?php 
                    $percent_paid = ($reg_fee_total > 0) ? ($reg_paid / $reg_fee_total) * 100 : 0;
                    $percent_paid = min(100, max(0, $percent_paid));
                    ?>
                    <div style="margin-top: 10px;">
                        <div style="display: flex; justify-content: space-between; font-size: 0.85rem; margin-bottom: 5px; color: #555;">
                            <span>Paid: <strong><?php echo $currency_symbol . number_format($reg_paid, 2); ?></strong></span>
                            <span>Total: <strong><?php echo $currency_symbol . number_format($reg_fee_total, 2); ?></strong></span>
                        </div>
                        <div style="width: 100%; background-color: #e0e0e0; border-radius: 10px; height: 10px; overflow: hidden;">
                            <div style="width: <?php echo $percent_paid; ?>%; background-color: <?php echo $reg_status === 'suspended' ? '#e74c3c' : '#2ecc71'; ?>; height: 100%; border-radius: 10px;"></div>
                        </div>
                    </div>
                </div>
                <a href="?tab=finances" class="btn-sm">Manage Payments</a>
            </div>
        </div>
        <?php endif; ?>
        <div class="dashboard-section">
        <h2 class="dashboard-title">Club Overview</h2>
        <div class="stats-card-grid">
            <div class="stat-card">
                <div class="stat-icon-wrapper" style="background: rgba(52, 152, 219, 0.1); color: #3498db;">
                    <i class="fa-solid fa-shield-halved"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-value"><?php echo count($club_teams); ?></div>
                    <div class="stat-label">Teams</div>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon-wrapper" style="background: rgba(155, 89, 182, 0.1); color: #9b59b6;">
                    <i class="fa-solid fa-users"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-value"><?php echo $total_players; ?></div>
                    <div class="stat-label">Total Players</div>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon-wrapper" style="background: rgba(231, 76, 60, 0.1); color: #e74c3c;">
                    <i class="fa-solid fa-file-invoice-dollar"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-value"><?php echo count($outstanding_fines); ?></div>
                    <div class="stat-label">Outstanding Fines</div>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon-wrapper" style="background: rgba(243, 156, 18, 0.1); color: #f39c12;">
                    <i class="fa-solid fa-coins"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-value"><?php echo $currency_symbol . number_format($total_fines_amount, 2); ?></div>
                    <div class="stat-label">Total Fines Value</div>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon-wrapper" style="background: rgba(46, 204, 113, 0.1); color: #2ecc71;">
                    <i class="fa-solid fa-money-bill-trend-up"></i>
                </div>
                <div class="stat-content">
                    <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>
        </div>
    </div>
            <div class="dashboard-section">
                <h2 class="dashboard-title">Recent Results</h2>
                <?php if (!empty($recent_results)): ?>
                    <div class="fixture-list mini-list">
                        <?php foreach ($recent_results as $result): ?>
                            <a href="fixture.php?id=<?php echo $result->id; ?>" class="fixture-item">
                                <div class="team home-team"><?php echo htmlspecialchars($result->home_team_name); ?></div>
                                <div class="score-box"><?php echo $result->home_team_score; ?> - <?php echo $result->away_team_score; ?></div>
                                <div class="team away-team"><?php echo htmlspecialchars($result->away_team_name); ?></div>
                            </a>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <p class="no-data-msg">No recent results available for the club.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div id="matches" class="tab-content <?php echo $active_tab === 'matches' ? 'active' : ''; ?>">
            <div class="dashboard-section">
                <h2 class="dashboard-title">Upcoming Matches</h2>
                <?php if (!empty($next_fixtures)): ?>
                    <div class="fixture-list">
                        <?php foreach($next_fixtures as $fixture): ?>
                        <a href="fixture.php?id=<?php echo $fixture->id; ?>" class="fixture-item">
                            <div class="team home-team"><?php echo htmlspecialchars($fixture->home_team_name); ?></div>
                            <div class="score-box time-box">
                                <span class="time"><?php echo date('H:i', strtotime($fixture->match_datetime)); ?></span>
                                <span class="date"><?php echo date('d M Y', strtotime($fixture->match_datetime)); ?></span>
                            </div>
                            <div class="team away-team"><?php echo htmlspecialchars($fixture->away_team_name); ?></div>
                        </a>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <p class="no-data-msg">No upcoming matches scheduled for the club.</p>
                <?php endif; ?>
            </div>
    </div>

    <div id="finances" class="tab-content <?php echo $active_tab === 'finances' ? 'active' : ''; ?>">
            <div class="dashboard-section">
                <h2 class="dashboard-title">Wallet Actions</h2>
                <div class="quick-actions-list" style="grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));">
                    <button class="action-item" onclick="openTeamTransferModal()">
                        <i class="fa-solid fa-money-bill-transfer"></i> <span>Transfer Funds to Team</span>
                    </button>
                    <button class="action-item" onclick="openWithdrawModal()">
                        <i class="fa-solid fa-building-columns"></i> <span>Withdraw Funds</span>
                    </button>
                    <button class="action-item" onclick="openTopUpModal()">
                        <i class="fa-solid fa-circle-plus"></i> <span>Top Up Wallet</span>
                    </button>
                </div>
            </div>
            <div class="dashboard-section">
                <div class="section-header">
                    <h2 class="dashboard-title">Outstanding Payments</h2>
                    <a href="club_finances.php" class="btn-sm">View Full History</a>
                </div>
                <div class="wallet-balance-info" style="margin-bottom: 15px; padding: 15px; background: #f8f9fa; border-radius: 8px; border-left: 4px solid var(--primary-color);">
                    <div style="font-size: 1.2rem; margin-bottom: 5px;">Club Wallet Balance: <strong><?php echo $currency_symbol . number_format($club_wallet->balance ?? 0, 2); ?></strong></div>
                    <small style="color: #666;">Includes net revenue from memberships (after commissions) and manual top-ups.</small>
                </div>
                <?php 
                $reg_remaining = $reg_fee_total - $reg_paid;
                if ($reg_fee_total > 0 && $reg_remaining > 0.01): 
                ?>
                <div class="dashboard-section" style="border: 1px solid #e0e0e0; background: #fff;">
                    <h3 style="margin-top: 0; color: #2c3e50;">Pay Registration Fee</h3>
                    <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; border-left: 4px solid var(--primary-color);">
                        <p style="margin: 5px 0;">Total Fee: <strong><?php echo $currency_symbol . number_format($reg_fee_total, 2); ?></strong></p>
                        <p style="margin: 5px 0;">Paid So Far: <strong><?php echo $currency_symbol . number_format($reg_paid, 2); ?></strong></p>
                        <p style="margin: 5px 0 15px 0;">Remaining: <strong style="color: #e74c3c;"><?php echo $currency_symbol . number_format($reg_remaining, 2); ?></strong></p>
                        
                        <form action="process_registration_payment.php" method="POST" style="display: flex; gap: 10px; align-items: flex-end; flex-wrap: wrap;">
                            <div class="form-group" style="margin-bottom: 0; flex: 1; min-width: 200px;">
                                <label for="reg_amount" style="font-size: 0.9rem;">Amount to Pay</label>
                                <input type="number" name="amount" id="reg_amount" class="form-control" value="<?php echo $reg_remaining; ?>" max="<?php echo $reg_remaining; ?>" min="1" step="0.01">
                            </div>
                            <button type="submit" class="btn">Pay with Wallet</button>
                        </form>
                    </div>
                </div>
                <?php endif; ?>
                <?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="my_club.php?tab=finances">
                        <div class="table-wrapper">
                            <table class="styled-table">
                                <thead>
                                    <tr>
                                        <th><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>
                                            <td><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>
    </div>

    <div id="teams" class="tab-content <?php echo $active_tab === 'teams' ? 'active' : ''; ?>">
            <div class="dashboard-section">
                <h2 class="dashboard-title">Club Teams</h2>
                <div class="table-wrapper">
                    <table class="styled-table">
                        <thead><tr><th>Team Name</th><th>Manager</th></tr></thead>
                        <tbody>
                            <?php foreach ($club_teams as $team): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($team->name); ?></td>
                                    <td><?php echo htmlspecialchars($team->manager_name ?? 'Not Assigned'); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

    <div id="transactions" class="tab-content <?php echo $active_tab === 'transactions' ? 'active' : ''; ?>">
        <div class="dashboard-section">
            <div class="section-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                <h2 class="dashboard-title" style="margin-bottom: 0;">Club & Team Transactions</h2>
                <button id="download-transactions-pdf" class="btn-sm" style="background-color: #e74c3c; color: white; border: none; cursor: pointer;"><i class="fa-solid fa-file-pdf"></i> Download PDF</button>
            </div>
            <?php
                // Fetch Club Transactions
                $club_transactions = $walletModel->getTransactions($club_wallet->id, 50);
                foreach ($club_transactions as $t) {
                    $t->source = 'Club Wallet';
                }

                // Fetch Team Transactions
                $all_transactions = $club_transactions;
                foreach ($club_teams as $team) {
                    $team_wallet = $walletModel->getOrCreateWallet('team', $team->id);
                    $team_txns = $walletModel->getTransactions($team_wallet->id, 20);
                    foreach ($team_txns as $t) {
                        $t->source = 'Team: ' . $team->name;
                        $all_transactions[] = $t;
                    }
                }

                // Sort by date descending
                usort($all_transactions, function($a, $b) {
                    return strtotime($b->created_at) - strtotime($a->created_at);
                });
                
                // Limit to recent 100 for display
                $all_transactions = array_slice($all_transactions, 0, 100);
            ?>
            <div class="table-wrapper" id="transactions-table-container">
                <?php if (!empty($all_transactions)): ?>
                    <table class="styled-table">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Source</th>
                                <th>Type</th>
                                <th>Description</th>
                                <th>Amount</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($all_transactions as $t): ?>
                                <tr>
                                    <td><?php echo date('d M Y, H:i', strtotime($t->created_at)); ?></td>
                                    <td><span class="badge" style="background: #eee; color: #333;"><?php echo htmlspecialchars($t->source); ?></span></td>
                                    <td><span class="badge badge-<?php echo $t->type; ?>"><?php echo ucfirst(str_replace('_', ' ', $t->type)); ?></span></td>
                                    <td><?php echo htmlspecialchars($t->description); ?></td>
                                    <td class="<?php echo in_array($t->type, ['deposit', 'transfer_in']) ? 'text-success' : 'text-danger'; ?>">
                                        <?php echo (in_array($t->type, ['deposit', 'transfer_in']) ? '+' : '-') . $currency_symbol . number_format($t->amount, 2); ?>
                                    </td>
                                    <td><?php echo ucfirst($t->status); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php else: ?>
                    <p class="no-data-msg">No transactions found.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div id="management" class="tab-content <?php echo $active_tab === 'management' ? 'active' : ''; ?>">
        <div class="dashboard-section">
            <h2 class="dashboard-title">Management Menu</h2>
            <div class="quick-actions-list">
                <a href="staff_members.php" class="action-item"><i class="fa-solid fa-users-cog"></i> <span>Staff Members</span></a>
                <a href="club_finances.php" class="action-item"><i class="fa-solid fa-file-invoice-dollar"></i> <span>Club Finances</span></a>
                <a href="teams.php" class="action-item"><i class="fa-solid fa-shield-halved"></i> <span>Manage Teams</span></a>
                <a href="club_members.php" class="action-item"><i class="fa-solid fa-id-card"></i> <span>Club Members</span></a>
                <a href="club_membership_packages.php" class="action-item"><i class="fa-solid fa-star"></i> <span>Membership Packages</span></a>
                <a href="club_transfers.php" class="action-item"><i class="fa-solid fa-right-left"></i> <span>Transfers</span></a>
            </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>

<!-- 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>

<!-- Payment Success Modal -->
<div id="paymentSuccessModal" class="modal">
    <div class="modal-content" style="max-width: 400px; text-align: center;">
        <div class="modal-body" style="padding: 40px 20px;">
            <div style="width: 70px; height: 70px; background: #d4edda; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 20px auto;">
                <i class="fa-solid fa-check" style="font-size: 35px; color: #28a745;"></i>
            </div>
            <h3 style="color: #2c3e50; margin-bottom: 10px;">Payment Successful!</h3>
            <p style="margin-bottom: 25px; color: #7f8c8d;">Your transaction has been verified.</p>
            <button class="btn btn-block" id="view-receipt-btn">View Receipt</button>
        </div>
    </div>
</div>

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

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

/* --- Tab System Fixes --- */
.tab-content { display: none; animation: fadeIn 0.3s ease; }
.tab-content.active { display: block; }
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }

/* --- Hero & Navigation Layout --- */
.team-dashboard-hero { background: linear-gradient(135deg, var(--primary-color, #3498db), var(--secondary-color, #2c3e50)); color: #fff; 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 20px; }
.hero-header-row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 20px; }
.team-identity { display: flex; align-items: center; gap: 20px; }
.hero-team-logo { width: 80px; height: 80px; object-fit: contain; background: #fff; border-radius: 50%; padding: 5px; box-shadow: 0 4px 10px rgba(0,0,0,0.1); }
.team-details h1 { margin: 0; font-size: 2.2rem; line-height: 1.2; }
.manager-badge { display: inline-block; background: rgba(255,255,255,0.2); padding: 5px 12px; border-radius: 20px; font-size: 0.85rem; margin-top: 5px; backdrop-filter: blur(5px); }

.hero-stats-strip { display: flex; gap: 10px; margin-bottom: 20px; overflow-x: auto; margin-top: 25px; }
.stat-box { background: rgba(255,255,255,0.1); padding: 10px 15px; border-radius: 8px; flex: 1; min-width: 100px; text-align: center; display: flex; flex-direction: column; border: none; }
.stat-box .label { font-size: 0.75rem; opacity: 0.8; text-transform: uppercase; letter-spacing: 0.5px; }
.stat-box .value { font-size: 1.3rem; font-weight: bold; margin-top: 2px; }

.dashboard-nav-bar { display: flex; gap: 5px; background: rgba(0,0,0,0.2); overflow-x: auto; white-space: nowrap; padding: 5px; border-radius: 30px; margin-top: 30px; border-bottom: none; }
.nav-tab { flex: 1; text-align: center; padding: 8px 20px; color: rgba(255,255,255,0.7); text-decoration: none; border-radius: 25px; font-size: 0.9rem; transition: all 0.2s; white-space: nowrap; border-bottom: none; font-weight: normal; }
.nav-tab:hover { color: white; background: rgba(255,255,255,0.1); border-radius: 25px; }
.nav-tab.active { background: #fff; color: var(--primary-color, #3498db); font-weight: bold; border-radius: 25px; border-bottom: none; }

/* --- Dashboard Grid & Cards --- */
.stats-card-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 25px; }
.stat-card { background: #fff; padding: 25px; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.05); border: 1px solid rgba(0,0,0,0.05); display: flex; align-items: center; gap: 20px; text-align: left; transition: transform 0.3s ease, box-shadow 0.3s ease; position: relative; overflow: hidden; }
.stat-card:hover { transform: translateY(-5px); box-shadow: 0 8px 25px rgba(0,0,0,0.1); }
.stat-icon-wrapper { width: 60px; height: 60px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 1.5rem; flex-shrink: 0; }
.stat-content { flex: 1; }
.stat-card .stat-value { font-size: 1.8rem; font-weight: 800; color: #2c3e50; margin-bottom: 2px; line-height: 1.2; }
.stat-card .stat-label { color: #95a5a6; font-size: 0.85rem; text-transform: uppercase; letter-spacing: 0.5px; font-weight: 600; }

/* --- Lists & Actions --- */
.fixture-list { display: flex; flex-direction: column; gap: 12px; }
.fixture-item { display: flex; justify-content: space-between; align-items: center; background: #fff; padding: 15px 20px; border-radius: 8px; border: 1px solid #eee; text-decoration: none; color: inherit; transition: all 0.2s; }
.fixture-item:hover { transform: translateX(5px); border-left: 4px solid var(--primary-color, #3498db); box-shadow: 0 4px 10px rgba(0,0,0,0.05); }
.fixture-item .team { flex: 1; font-weight: 600; font-size: 1.05rem; }
.fixture-item .home-team { text-align: right; }
.fixture-item .away-team { text-align: left; }
.fixture-item .score-box, .fixture-item .time-box { margin: 0 25px; background: #f8f9fa; padding: 8px 15px; border-radius: 8px; font-weight: bold; min-width: 100px; text-align: center; display: flex; flex-direction: column; justify-content: center; border: 1px solid #e9ecef; }
.fixture-item .time-box .time { font-size: 1.1rem; color: #2c3e50; }
.fixture-item .time-box .date { font-size: 0.75rem; color: #7f8c8d; font-weight: normal; margin-top: 2px; }

.quick-actions-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 15px; }
.action-item { display: flex; flex-direction: column; align-items: center; justify-content: center; background: #fff; padding: 25px 15px; border-radius: 8px; border: 1px solid #eee; text-decoration: none; color: #34495e; transition: all 0.2s; gap: 12px; text-align: center; cursor: pointer; height: 100%; }
.action-item:hover { border-color: var(--primary-color, #3498db); color: var(--primary-color, #3498db); transform: translateY(-3px); box-shadow: 0 5px 15px rgba(0,0,0,0.05); }
.action-item i { font-size: 1.8rem; margin-bottom: 5px; color: var(--primary-color, #3498db); }
.action-item span { font-weight: 500; }

/* --- Tables --- */
.table-wrapper { overflow-x: auto; border-radius: 8px; border: 1px solid #eee; margin-bottom: 20px; }
.styled-table { width: 100%; border-collapse: collapse; margin: 0; font-size: 0.95em; min-width: 600px; background: #fff; }
.styled-table thead tr { background-color: var(--primary-color, #3498db); color: #ffffff; text-align: left; }
.styled-table th, .styled-table td { padding: 15px; }
.styled-table tbody tr { border-bottom: 1px solid #dddddd; }
.styled-table tbody tr:nth-of-type(even) { background-color: #f9f9f9; }
.styled-table tbody tr:hover { background-color: #f1f1f1; }

.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');
    const downloadPdfBtn = document.getElementById('download-transactions-pdf');
    
    // Withdraw Modal
    const withdrawModal = document.getElementById('withdrawModal');

    // Top Up Modal
    const topUpModal = document.getElementById('topUpModal');

    // Team Transfer Modal
    const teamTransferModal = document.getElementById('teamTransferModal');

    // 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;

    // Success Modal Elements
    const successModal = document.getElementById('paymentSuccessModal');
    const viewReceiptBtn = document.getElementById('view-receipt-btn');

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

    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>';
        if (type === 'info') icon = '<i class="fa-solid fa-info-circle" 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);
    }

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

    // --- Withdraw Modal Logic ---
    window.openWithdrawModal = function() {
        if(withdrawModal) withdrawModal.classList.add('show');
    }
    window.closeWithdrawModal = function() {
        if(withdrawModal) withdrawModal.classList.remove('show');
    }

    // --- Top Up Modal Logic ---
    window.openTopUpModal = function() {
        if(topUpModal) topUpModal.classList.add('show');
    }
    window.closeTopUpModal = function() {
        if(topUpModal) topUpModal.classList.remove('show');
    }

    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));

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

    // --- Payment Modal Logic ---
    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();
    });

    if (confirmPaymentBtn) {
        confirmPaymentBtn.addEventListener('click', function() {
            if (!paymentData) return;
            closePaymentModal();
            
            const { type, totalAmount, publicKey, userEmail, originalBtnText, metaData } = paymentData;
            
            const txRef = (type === 'fines' ? 'club_fine_' : '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: <?php echo json_encode($user_name); ?>,
                    },
                    meta: metaData,
                    customizations: {
                        title: <?php echo json_encode($club->name ?? 'Pay Club Fines'); ?>,
                        description: "Payment for selected fines",
                        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: type === 'fines' ? 'club_manager' : '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() {
                        // Restore button state when modal is closed
                        if (!paymentSubmitted) {
                            showToast('Payment cancelled by user.', 'info');
                        }
                    }
                });
            } catch (error) {
                console.error("Flutterwave Initialization Error:", error);
                alert("Failed to initialize payment gateway.");
            }
        });
    }

    // --- PDF Download Logic ---
    if (downloadPdfBtn) {
        downloadPdfBtn.addEventListener('click', function() {
            const element = document.getElementById('transactions-table-container');
            const opt = {
                margin: 10,
                filename: 'Club_Transactions_Report.pdf',
                image: { type: 'jpeg', quality: 0.98 },
                html2canvas: { scale: 2 },
                jsPDF: { unit: 'mm', format: 'a4', orientation: 'landscape' }
            };
            html2pdf().set(opt).from(element).save();
        });
    }

    // --- Flutterwave Payment Integration ---
    if (payButton) {
        payButton.addEventListener('click', function(e) {
            e.preventDefault(); // Prevent form submission

            if (typeof FlutterwaveCheckout === 'undefined') {
                alert("Payment gateway failed to load. Please check your internet connection or disable ad blockers.");
                return;
            }

            let selectedFines = [];
            let totalAmount = 0;
            
            fineCheckboxes.forEach(checkbox => {
                if (checkbox.checked) {
                    selectedFines.push(checkbox.value);
                    totalAmount += parseFloat(checkbox.dataset.amount);
                }
            });

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

            const publicKey = "<?php echo $settings['flutterwave_public_key'] ?? ''; ?>";
            if (!publicKey) {
                alert("System Error: Payment gateway is not configured (Missing Public Key).");
                return;
            }

            const userEmail = <?php echo json_encode($user_email); ?>;
            console.log("Payment Email:", userEmail); // Debugging
            if (!userEmail) {
                alert("Your email address is missing. Please update your profile before making a payment.");
                return;
            }

            // Prepare data for modal confirmation
            paymentData = {
                type: 'fines',
                totalAmount: totalAmount,
                publicKey: publicKey,
                userEmail: userEmail,
                metaData: {
                    fine_ids: selectedFines.join(','),
                    payment_context: 'club_manager'
                },
                originalBtnText: payButton.innerHTML
            };

            // Clear any previous onclick handler from wallet to prevent double submission
            if (confirmPaymentBtn) confirmPaymentBtn.onclick = null;

            // Show Confirmation Modal
            paymentText.textContent = `Are you sure you want to pay ${selectedFines.length} fines for a total of <?php echo $currency_symbol; ?>${totalAmount.toFixed(2)}?`;
            paymentModal.classList.add('show');
        });
    }

    // --- 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: 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: Selected Fines', selectedFines);
            console.log('Wallet Payment: 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: Confirmed');
                const form = document.getElementById('fines-payment-form');
                console.log('Wallet Payment: Form found', form);
                
                // Append hidden input to simulate button click for backend validation
                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: Hidden input set');

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

    // --- Top Up Button 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) {
                alert("Please enter a valid amount.");
                return;
            }

            const publicKey = "<?php echo $settings['flutterwave_public_key'] ?? ''; ?>";
            const userEmail = <?php echo json_encode($user_email); ?>;

            if (!publicKey || !userEmail) {
                alert("Configuration error or missing email.");
                return;
            }

            closeTopUpModal();

            paymentData = {
                type: 'topup',
                totalAmount: amount,
                publicKey: publicKey,
                userEmail: userEmail,
                metaData: {
                    payment_context: 'club_wallet_deposit'
                },
                originalBtnText: '' // Not used for topup
            };

            confirmPaymentBtn.click(); // Trigger payment flow immediately
        });
    }

    // --- Chart.js Implementation ---
    const chartData = <?php echo json_encode($chart_data ?? []); ?>;
    if (Array.isArray(chartData) && 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>

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