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

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

$pageTitle = 'My Team';
include 'includes/header.php';

$manager_id = $_SESSION['user_id'];

// --- Instantiate Models and Fetch Data ---
$teamModel = new Team();
$playerModel = new Player();
$fixtureModel = new Fixture();
$leagueModel = new League();
$statModel = new Stat();
$fineModel = new Fine();
$settingModel = new Setting();
$userModel = new User();
$walletModel = new Wallet();

// Get the manager's team
$team = $teamModel->getTeamByManagerId($manager_id);

$team_players = [];
$next_fixture = null;
$team_stats = null;
$unavailable_count = 0;
$outstanding_fines = [];

// 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 ?? ''));
        }
    }
}

// --- 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 = '€';
} // Add other currencies as needed
$primary_color = $settings['primary_color'] ?? '#3498db';
$secondary_color = $settings['secondary_color'] ?? '#2c3e50';

// --- Check Transfer Window Status ---
$transfer_window_start = $settings['transfer_window_start'] ?? null;
$transfer_window_end = $settings['transfer_window_end'] ?? null;
$registration_period_open = !empty($settings['registration_period_open']);
$today = date('Y-m-d');
$is_transfer_window_open = ($today >= $transfer_window_start && $today <= $transfer_window_end);
$can_add_players = $registration_period_open || $is_transfer_window_open; // Registration or Transfer window
$can_remove_players = $registration_period_open || $is_transfer_window_open; // Registration or Transfer window

if ($team && $registration_period_open) {
    // If in registration period, enforce roster status lock. Only 'draft' or 'rejected' can be edited.
    if (isset($team->roster_status) && !in_array($team->roster_status, ['draft', 'rejected'])) {
        $can_add_players = false;
        $can_remove_players = false;
    }
}

if ($team) {
    // Fetch league table to find team position
    $league_table = $leagueModel->getTable($team->league_id);
    $team_rank = 'N/A';
    foreach ($league_table as $index => $table_row) {
        if ($table_row->team_id == $team->id) {
            $team_rank = $index + 1; // Team rank is 1-based index
            $team_stats = $table_row;
            break;
        }
    }

    // Fetch player and fine data
    $top_scorer = $statModel->getTopScorers($team->league_id, 1, $team->id)[0] ?? null;
    $top_assist = $statModel->getTopAssists($team->league_id, 1, $team->id)[0] ?? null;
    $top_clean_sheets = $statModel->getMostCleanSheets($team->league_id, 1, $team->id)[0] ?? null;
    
    try {
        $injured_players = $playerModel->getInjuredPlayersByTeamId($team->id);
    } catch (PDOException $e) {
        // Gracefully handle if 'injuries' table doesn't exist yet
        $injured_players = [];
    }
    try {
        $suspended_players = $playerModel->getSuspendedPlayersByTeamId($team->id);
    } catch (PDOException $e) {
        // Gracefully handle if 'suspensions' table doesn't exist yet
        $suspended_players = [];
    }

    // Fetch outstanding fines and identify fined players
    if (isset($team->club_id)) {
        $outstanding_fines = $fineModel->getUnpaidFinesForTeam($team->club_id);
    }
    // Collect player IDs (players.id) from outstanding fines, ensuring only player fines are considered
    $fined_player_ids = array_filter(array_unique(array_map(fn($fine) => ($fine->entity_type === 'player' && isset($fine->player_id)) ? $fine->player_id : null, $outstanding_fines)));

    // Calculate unavailable players including those with fines
    $unavailable_count = count($injured_players) + count($suspended_players) + count($fined_player_ids);

    // Check for players returning soon (next 7 days)
    $returning_soon = [];
    $today_ts = time();
    foreach ($injured_players as $p) {
        if (!empty($p->expected_return_date)) {
            $return_ts = strtotime($p->expected_return_date);
            $days_diff = ceil(($return_ts - $today_ts) / (60 * 60 * 24));
            if ($days_diff >= 0 && $days_diff <= 7) {
                $returning_soon[] = $p;
            }
        }
    }

    $team_players = $playerModel->getPlayersByTeamId($team->id);

    // Create lookup arrays for player statuses for the roster table
    $injured_player_ids = array_map(fn($p) => $p->id, $injured_players);
    $suspended_player_ids = array_map(fn($p) => $p->id, $suspended_players);

    // Get the next upcoming fixture for the team
    $next_fixture = $fixtureModel->getUpcomingFixturesForTeam($team->id)[0] ?? null;
    
    // Get Team Wallet
    $team_wallet = $walletModel->getOrCreateWallet('team', $team->id);

    // Check Referee Fee Status for Next Match
    $referee_fee_paid = false;
    if ($next_fixture) {
        if ($next_fixture->home_team_id == $team->id) {
            $referee_fee_paid = (bool)$next_fixture->home_team_paid_referee;
        } elseif ($next_fixture->away_team_id == $team->id) {
            $referee_fee_paid = (bool)$next_fixture->away_team_paid_referee;
        }
    }
}

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

<?php if ($team): ?>
<div class="team-dashboard-hero">
    <div class="hero-content-wrapper">
        <div class="hero-header-row">
            <div class="team-identity">
                <img src="<?php echo htmlspecialchars($team->club_logo); ?>" alt="<?php echo htmlspecialchars($team->club_name); ?>" class="hero-team-logo">
                <div class="team-details">
                    <h1><?php echo htmlspecialchars($team->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">League Rank</span>
                <span class="value">#<?php echo $team_rank; ?></span>
            </div>
            <div class="stat-box">
                <span class="label">Points</span>
                <span class="value"><?php echo $team_stats->points ?? 0; ?></span>
            </div>
            <div class="stat-box">
                <span class="label">Played</span>
                <span class="value"><?php echo $team_stats->played ?? 0; ?></span>
            </div>
            <div class="stat-box">
                <span class="label">Goal Diff</span>
                <span class="value"><?php echo $team_stats->goal_difference ?? 0; ?></span>
            </div>
            <div class="stat-box">
                <span class="label">Wallet</span>
                <span class="value"><?php echo $currency_symbol . number_format($team_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=squad" class="nav-tab <?php echo $active_tab === 'squad' ? 'active' : ''; ?>">Squad</a>
            <a href="?tab=matches" class="nav-tab <?php echo $active_tab === 'matches' ? 'active' : ''; ?>">Matches</a>
            <a href="?tab=fines" class="nav-tab <?php echo $active_tab === 'fines' ? 'active' : ''; ?>">Fines</a>
            <a href="?tab=transactions" class="nav-tab <?php echo $active_tab === 'transactions' ? 'active' : ''; ?>">Transactions</a>
        </div>
    </div>
</div>
<?php endif; ?>

<div class="page-content">
    <?php if ($team): ?>

    <div id="overview" class="tab-content <?php echo $active_tab === 'overview' ? 'active' : ''; ?>">

        <div class="dashboard-section">
            <h2 class="dashboard-title"><?php echo htmlspecialchars($team->club_name); ?> Stats</h2>
            <div class="stats-card-grid">
                <div class="stat-card">
                    <div class="stat-value"><?php echo $team_rank; ?></div>
                    <div class="stat-label">League Position</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value"><?php echo $team_stats->goals_for ?? 0; ?></div>
                    <div class="stat-label">Goals Scored</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value"><?php echo $team_stats->goals_against ?? 0; ?></div>
                    <div class="stat-label">Goals Conceded</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value"><?php echo count($team_players); ?></div>
                    <div class="stat-label">Total Players</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value" style="color: <?php echo $unavailable_count > 0 ? '#e74c3c' : 'inherit'; ?>;">
                        <?php echo $unavailable_count; ?>
                    </div>
                    <div class="stat-label">Unavailable</div>
                </div>
            </div>
        </div>

        <div class="dashboard-split-row">
            <div class="split-col-left">
                <div class="dashboard-section h-100">
                    <h2 class="dashboard-title">Next Match</h2>
                    <?php if ($next_fixture): ?>
                        <div class="next-match-card">
                            <div class="match-teams">
                                <div class="match-team"><img src="<?php echo htmlspecialchars($next_fixture->home_team_logo); ?>" alt=""><span><?php echo htmlspecialchars($next_fixture->home_team_name); ?></span></div>
                                <div class="match-vs">VS</div>
                                <div class="match-team"><img src="<?php echo htmlspecialchars($next_fixture->away_team_logo); ?>" alt=""><span><?php echo htmlspecialchars($next_fixture->away_team_name); ?></span></div>
                            </div>
                            <div class="match-meta">
                                <span class="match-date"><i class="fa-regular fa-calendar"></i> <?php echo date('D, d M', strtotime($next_fixture->match_datetime)); ?></span>
                                <span class="match-time"><i class="fa-regular fa-clock"></i> <?php echo date('H:i', strtotime($next_fixture->match_datetime)); ?></span>
                            </div>
                            <a href="submit_lineup.php?fixture_id=<?php echo $next_fixture->id; ?>" class="btn btn-block btn-primary mt-3">Submit Lineup</a>
                            
                            <!-- Referee Fee Payment -->
                            <?php if (!$referee_fee_paid): ?>
                                <button type="button" onclick="openPayRefereeFeeModal(<?php echo $next_fixture->id; ?>, '<?php echo htmlspecialchars($next_fixture->home_team_name . ' vs ' . $next_fixture->away_team_name, ENT_QUOTES); ?>')" class="btn btn-block btn-warning mt-2" style="background-color: #f39c12; border-color: #e67e22; color: white;">
                                    <i class="fa-solid fa-whistle"></i> Pay Referee Fee
                                </button>
                            <?php else: ?>
                                <button class="btn btn-block btn-success mt-2" disabled style="opacity: 0.8; cursor: default;"><i class="fa-solid fa-check"></i> Referee Fee Paid</button>
                            <?php endif; ?>
                        </div>
                    <?php else: ?>
                        <p class="no-data-msg">No upcoming matches scheduled.</p>
                    <?php endif; ?>
                </div>
            </div>
            <div class="split-col-right">
        <div class="dashboard-section">
            <h2 class="dashboard-title">Team Highlights</h2>
            <div class="team-highlights-grid">
                <div class="highlight-card">
                    <div class="highlight-header">
                        <span class="highlight-title">Top Scorer</span>
                        <i class="fa-solid fa-futbol"></i>
                    </div>
                    <div class="highlight-body">
                        <?php if ($top_scorer): ?>
                            <div class="player-img-container">
                                <img src="<?php echo htmlspecialchars($top_scorer->profile_picture ?? '/smart_football/public/assets/images/default_avatar.png'); ?>" alt="Player">
                            </div>
                            <div class="player-info">
                                <span class="player-name"><?php echo htmlspecialchars($top_scorer->first_name . ' ' . $top_scorer->last_name); ?></span>
                                <span class="stat-big"><?php echo $top_scorer->goals; ?> <small>Goals</small></span>
                            </div>
                        <?php else: ?>
                            <div class="no-stat">No goals yet</div>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="highlight-card">
                    <div class="highlight-header">
                        <span class="highlight-title">Top Assists</span>
                        <i class="fa-solid fa-hands-helping"></i>
                    </div>
                    <div class="highlight-body">
                        <?php if ($top_assist): ?>
                            <div class="player-img-container">
                                <img src="<?php echo htmlspecialchars($top_assist->profile_picture ?? '/smart_football/public/assets/images/default_avatar.png'); ?>" alt="Player">
                            </div>
                            <div class="player-info">
                                <span class="player-name"><?php echo htmlspecialchars($top_assist->first_name . ' ' . $top_assist->last_name); ?></span>
                                <span class="stat-big"><?php echo $top_assist->assists; ?> <small>Assists</small></span>
                            </div>
                        <?php else: ?>
                            <div class="no-stat">No assists yet</div>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="highlight-card">
                    <div class="highlight-header">
                        <span class="highlight-title">Clean Sheets</span>
                        <i class="fa-solid fa-shield-alt"></i>
                    </div>
                    <div class="highlight-body">
                        <?php if ($top_clean_sheets): ?>
                            <div class="player-img-container">
                                <img src="<?php echo htmlspecialchars($top_clean_sheets->profile_picture ?? '/smart_football/public/assets/images/default_avatar.png'); ?>" alt="Player">
                            </div>
                            <div class="player-info">
                                <span class="player-name"><?php echo htmlspecialchars($top_clean_sheets->first_name . ' ' . $top_clean_sheets->last_name); ?></span>
                                <span class="stat-big"><?php echo $top_clean_sheets->clean_sheets; ?> <small>Clean Sheets</small></span>
                            </div>
                        <?php else: ?>
                            <div class="no-stat">No clean sheets yet</div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
            </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 
            $upcoming_matches = $fixtureModel->getUpcomingFixturesForTeam($team->id);
            if (!empty($upcoming_matches)): ?>
                <div class="fixture-list">
                    <?php foreach($upcoming_matches as $fixture): ?>
                    <a href="fixture.php?id=<?php echo $fixture->id; ?>" class="fixture-item">
                        <div class="team home-team">
                            <span class="team-name"><?php echo htmlspecialchars($fixture->home_team_name); ?></span>
                            <img src="<?php echo htmlspecialchars($fixture->home_team_logo); ?>" alt="" class="team-logo">
                        </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', strtotime($fixture->match_datetime)); ?></span>
                        </div>
                        <div class="team away-team">
                            <img src="<?php echo htmlspecialchars($fixture->away_team_logo); ?>" alt="" class="team-logo">
                            <span class="team-name"><?php echo htmlspecialchars($fixture->away_team_name); ?></span>
                        </div>
                    </a>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <p class="no-data-msg">No upcoming matches scheduled for the team.</p>
            <?php endif; ?>
        </div>
    </div>

    <div id="fines" class="tab-content <?php echo $active_tab === 'fines' ? 'active' : ''; ?>">
        <div class="dashboard-section">
            <div class="section-header">
                <h2 class="dashboard-title">Outstanding Payments</h2>
                <a href="fine_history.php" class="btn-sm">View Full History</a>
            </div>
            <div class="wallet-balance-info" style="margin-bottom: 15px; padding: 10px; background: #f8f9fa; border-radius: 8px;">Team Wallet Balance: <strong><?php echo $currency_symbol . number_format($team_wallet->balance ?? 0, 2); ?></strong></div>
            <?php if (!empty($outstanding_fines)): ?>
                <form action="create_payment_session.php" method="POST" id="fines-payment-form">
                    <input type="hidden" name="team_id" value="<?php echo $team->id; ?>">
                    <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 
                                $total_payable = 0;
                                foreach ($outstanding_fines as $fine): 
                                    $total_payable += $fine->amount;
                                ?>
                                    <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
                                            // Display the name of the fined entity (player or club)
                                            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="team">
                        <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 team.</p>
            <?php endif; ?>
        </div>
    </div>

    <div id="transactions" class="tab-content <?php echo $active_tab === 'transactions' ? 'active' : ''; ?>">
        <div class="dashboard-section">
            <h2 class="dashboard-title">Transaction History</h2>
            <?php
                // Fetch transactions for team wallet
                $transactions = $walletModel->getTransactions($team_wallet->id, 50);
            ?>
            <div class="table-wrapper">
                <?php if (!empty($transactions)): ?>
                    <table class="styled-table">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Type</th>
                                <th>Description</th>
                                <th>Amount</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($transactions as $t): ?>
                                <tr>
                                    <td><?php echo date('d M Y, H:i', strtotime($t->created_at)); ?></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="squad" class="tab-content <?php echo $active_tab === 'squad' ? 'active' : ''; ?>">
        <?php if (!empty($returning_soon)): ?>
            <div class="dashboard-section" style="background-color: #d4edda; border: 1px solid #c3e6cb;">
                <h2 class="dashboard-title" style="color: #155724; margin-bottom: 10px;"><i class="fa-solid fa-user-doctor"></i> Returning Soon</h2>
                <ul style="list-style: none; padding: 0; margin: 0;">
                    <?php foreach ($returning_soon as $p): ?>
                        <li style="color: #155724; padding: 5px 0; border-bottom: 1px solid rgba(0,0,0,0.05);">
                            <strong><?php echo htmlspecialchars($p->first_name . ' ' . $p->last_name); ?></strong> is expected back on <strong><?php echo date('D, d M', strtotime($p->expected_return_date)); ?></strong>.
                        </li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php endif; ?>
        <div class="dashboard-section">
            <div class="section-header">
                <h2 class="dashboard-title">Team Roster <?php if($registration_period_open): ?><small class="status-badge status-<?php echo $team->roster_status ?? 'draft'; ?>" style="font-size: 0.6em; vertical-align: middle;"><?php echo ucfirst(str_replace('_', ' ', $team->roster_status ?? 'Draft')); ?></small><?php endif; ?></h2>
                <div style="display: flex; align-items: center; gap: 10px;">
                    <?php if ($registration_period_open && ($team->roster_status === 'draft' || $team->roster_status === 'rejected')): ?>
                        <button class="btn-sm" onclick="openSubmitRosterModal()" style="background-color: #27ae60; color: white; border: none; cursor: pointer; font-weight: 600;"><i class="fa-solid fa-paper-plane"></i> Submit Squad</button>
                    <?php endif; ?>
                    <?php if ($registration_period_open && ($team->roster_status ?? '') === 'pending_approval'): ?>
                        <button class="btn-sm" disabled style="background-color: #95a5a6; color: white; border: none; cursor: not-allowed;" title="Roster is locked for editing while pending approval."><i class="fa-solid fa-lock"></i> Pending Approval</button>
                    <?php endif; ?>
                    <?php if ($can_add_players): ?>
                        <button class="btn-sm" onclick="openAddPlayerModal()" style="background-color: var(--primary-color); color: white; border: none; cursor: pointer;">+ Add Player</button>
                    <?php endif; ?>
                    <div class="roster-filter-controls">
                        <button class="filter-btn active" data-filter="all">All</button>
                        <button class="filter-btn" data-filter="available">Available</button>
                        <button class="filter-btn" data-filter="injured">Injured</button>
                        <button class="filter-btn" data-filter="suspended">Suspended</button>
                        <button class="filter-btn" data-filter="fine">Fine</button>
                    </div>
                </div>
            </div>
            <div class="table-wrapper">
                <table class="styled-table">
                    <thead><tr><th>#</th><th>Name</th><th>Position</th><th>Status</th><th>Actions</th></tr></thead>
                    <tbody id="roster-tbody">
                        <?php foreach ($team_players as $player): ?>
                            <?php
                                $status_text = 'available';
                                $status_badge_class = 'status-available';
                                $status_badge_text = 'Available';
                                if (in_array($player->id, $injured_player_ids)) {
                                    $status_text = 'injured';
                                    $status_badge_class = 'status-injured';
                                    $status_badge_text = 'Injured';
                                } elseif (in_array($player->id, $suspended_player_ids)) {
                                    $status_text = 'suspended';
                                    $status_badge_class = 'status-suspended';
                                    $status_badge_text = 'Suspended';
                                } elseif (in_array($player->id, $fined_player_ids)) {
                                    $status_text = 'fine';
                                    $status_badge_class = 'status-fine';
                                    $status_badge_text = 'Fine';
                                }
                            ?>
                            <tr data-status="<?php echo $status_text; ?>">
                                <td><?php echo htmlspecialchars($player->squad_number); ?></td>
                                <td>
                                    <div class="player-cell">
                                        <img src="<?php echo htmlspecialchars($player->profile_picture ?? '/smart_football/public/assets/images/default_avatar.png'); ?>" alt="Player" class="player-avatar-xs">
                                        <span><?php echo htmlspecialchars($player->first_name . ' ' . $player->last_name); ?></span>
                                    </div>
                                </td>
                                <td><?php echo htmlspecialchars($player->position); ?></td>
                                <td><span class="status-badge <?php echo $status_badge_class; ?>"><?php echo $status_badge_text; ?></span></td>
                                <td>
                                    <button class="btn-sm btn-edit" onclick='openEditPlayerModal(<?php echo json_encode($player, JSON_HEX_APOS | JSON_HEX_QUOT); ?>)'>Edit</button>
                                    <?php if ($can_remove_players): ?>
                                        <button class="btn-sm btn-danger" onclick="openReleasePlayerModal(<?php echo $player->id; ?>, '<?php echo htmlspecialchars($player->first_name . ' ' . $player->last_name, ENT_QUOTES); ?>')" style="background-color: #e74c3c; color: white; border: none; padding: 5px 10px; border-radius: 4px; cursor: pointer;">Release</button>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <?php else: ?>
        <div class="matches-header">
            <div>
                <h1>My Team Dashboard</h1>
            </div>
        </div>
        <p class="no-data-msg">You are not currently assigned as a manager to any team.</p>
    <?php endif; ?>
</div>

<!-- Add Player Modal -->
<div id="addPlayerModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>Add Player to Team</h3>
            <button class="modal-close-btn" onclick="closeAddPlayerModal()">&times;</button>
        </div>
        <form action="add_player_process.php" method="POST">
            <input type="hidden" name="team_id" value="<?php echo $team->id ?? ''; ?>">
            <input type="hidden" name="user_id" id="selected_user_id_for_player">

            <div class="form-group">
                <label for="player_search">Search User (Free Agent)</label>
                <input type="text" id="player_search" placeholder="Type name or email..." autocomplete="off">
                <div id="player_search_results" class="search-results"></div>
            </div>

            <p>Selecting a user will change their role to 'Player' and add them to your team.</p>

            <button type="submit" class="btn btn-block" id="addPlayerBtn" disabled>Add Selected Player</button>
        </form>
    </div>
</div>

<!-- Release Player Confirmation Modal -->
<div id="releasePlayerModal" class="modal">
    <div class="modal-content" style="max-width: 450px;">
        <div class="modal-header">
            <h3>Release Player</h3>
            <button class="modal-close-btn" onclick="closeReleasePlayerModal()">&times;</button>
        </div>
        <div class="modal-body">
            <p style="font-size: 1rem; color: #555; margin-bottom: 20px;">Are you sure you want to release <strong id="releasePlayerName"></strong>? <br><br>They will become a free agent and removed from your squad immediately.</p>
            <form action="remove_player_process.php" method="POST">
                <input type="hidden" name="player_id" id="releasePlayerId">
                <div class="modal-actions" style="display: flex; gap: 10px; justify-content: flex-end;">
                    <button type="button" class="btn btn-secondary" onclick="closeReleasePlayerModal()">Cancel</button>
                    <button type="submit" class="btn btn-danger" style="background-color: #e74c3c;">Confirm Release</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Submit Roster Confirmation Modal -->
<div id="submitRosterModal" class="modal">
    <div class="modal-content" style="max-width: 450px;">
        <div class="modal-header">
            <h3>Submit Squad for Approval</h3>
            <button class="modal-close-btn" onclick="closeSubmitRosterModal()">&times;</button>
        </div>
        <div class="modal-body">
            <p style="font-size: 1rem; color: #555; margin-bottom: 20px;">Are you sure you want to submit your squad? <br><br><strong>Note:</strong> Once submitted, you cannot edit your squad (add or remove players) unless it is rejected by an administrator.</p>
            <form action="submit_roster_process.php" method="POST">
                <input type="hidden" name="team_id" value="<?php echo $team->id ?? ''; ?>">
                <div class="modal-actions" style="display: flex; gap: 10px; justify-content: flex-end;">
                    <button type="button" class="btn btn-secondary" onclick="closeSubmitRosterModal()">Cancel</button>
                    <button type="submit" class="btn">Submit Squad</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Player Modal -->
<div id="editPlayerModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>Edit Player Details</h3>
            <button class="modal-close-btn" onclick="closeEditPlayerModal()">&times;</button>
        </div>
        <form action="edit_player_process.php" method="POST">
            <input type="hidden" name="player_id" id="edit_player_id">
            <input type="hidden" name="redirect_to" id="edit_redirect_to" value="my_team.php?tab=squad">

            <div class="form-group">
                <label for="edit_squad_number">Squad Number</label>
                <input type="number" name="squad_number" id="edit_squad_number" min="1" max="99">
            </div>
            <div class="form-group">
                <label for="edit_position">Position</label>
                <select name="position" id="edit_position">
                    <option value="Goalkeeper">Goalkeeper</option>
                    <option value="Defender">Defender</option>
                    <option value="Midfielder">Midfielder</option>
                    <option value="Forward">Forward</option>
                </select>
            </div>
            <div class="form-group">
                <label for="edit_height_cm">Height (cm)</label>
                <input type="number" name="height_cm" id="edit_height_cm">
            </div>
            <div class="form-group">
                <label for="edit_weight_kg">Weight (kg)</label>
                <input type="number" name="weight_kg" id="edit_weight_kg">
            </div>
            <div class="form-group">
                <label for="edit_preferred_foot">Preferred Foot</label>
                <select name="preferred_foot" id="edit_preferred_foot">
                    <option value="Right">Right</option>
                    <option value="Left">Left</option>
                    <option value="Both">Both</option>
                </select>
            </div>
            <div class="form-group">
                <label for="edit_date_of_birth">Date of Birth</label>
                <input type="date" name="date_of_birth" id="edit_date_of_birth">
            </div>
            <div class="form-group">
                <label for="edit_nationality">Nationality</label>
                <input type="text" name="nationality" id="edit_nationality">
            </div>

            <button type="submit" class="btn btn-block">Save Changes</button>
        </form>
    </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>

<!-- Pay Referee Fee Modal -->
<div id="payRefereeFeeModal" class="modal">
    <div class="modal-content" style="max-width: 400px;">
        <div class="modal-header">
            <h3>Pay Referee Fee</h3>
            <button class="modal-close-btn" onclick="closePayRefereeFeeModal()">&times;</button>
        </div>
        <div class="modal-body">
            <p id="referee_fee_match_info"></p>
            <p>The referee fee for this match is <strong><?php echo $currency_symbol . number_format($settings['referee_fee'] ?? 50, 2); ?></strong>.</p>
            <p>This must be paid before the match can start.</p>
            <p>Wallet Balance: <strong><?php echo $currency_symbol . number_format($team_wallet->balance ?? 0, 2); ?></strong></p>
            
            <form action="pay_referee_fee_process.php" method="POST" id="referee-fee-form">
                <input type="hidden" name="fixture_id" id="referee_fee_fixture_id">
                <input type="hidden" name="team_id" value="<?php echo $team->id ?? ''; ?>">
                <input type="hidden" name="wallet_type" value="team">
                <input type="hidden" name="payment_method" value="wallet">
                
                <div id="referee-fee-actions">
                    <!-- Buttons injected via JS based on balance -->
                </div>
            </form>
        </div>
    </div>
</div>

<div id="toast-container"></div>

<style>
/* === Team Dashboard Styles === */
.tab-content {
    display: none;
}
.tab-content.active {
    display: block;
}

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

.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;
    margin-bottom: 20px;
}

.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-stats-strip {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
    overflow-x: auto;
}

.hero-stats-strip .stat-box {
    background: rgba(255,255,255,0.1);
    padding: 10px 15px;
    border-radius: 8px;
    flex: 1;
    min-width: 100px;
    text-align: center;
}

.hero-stats-strip .label {
    display: block;
    font-size: 0.75rem;
    opacity: 0.8;
    text-transform: uppercase;
    font-weight: normal;
}

.hero-stats-strip .value {
    font-size: 1.5rem;
    font-weight: 800;
}

.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;
}
.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;
}
.nav-tab:hover { color: white; background: rgba(255,255,255,0.1); }
.nav-tab.active { background: #fff; color: var(--primary-color, #3498db); font-weight: bold; }

/* Stats Grid */
.stats-card-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 1.5rem;
    margin-bottom: 2rem;
}

.stat-card {
    background: white;
    padding: 1.5rem;
    border-radius: 10px;
    text-align: center;
    box-shadow: 0 2px 5px rgba(0,0,0,0.05);
    border: 1px solid #eee;
    transition: transform 0.2s;
}

.stat-card:hover {
    transform: translateY(-3px);
}

.stat-value {
    font-size: 2rem;
    font-weight: 800;
    color: var(--primary-color, #3498db);
    line-height: 1.2;
}

.stat-label {
    font-size: 0.85rem;
    color: #7f8c8d;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

/* Split Layout */
.dashboard-split-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 2rem;
    margin-bottom: 2rem;
}

@media (max-width: 900px) {
    .dashboard-split-row {
        grid-template-columns: 1fr;
    }
}

.h-100 { height: 100%; }

/* Next Match Card */
.next-match-card {
    background: white;
    border-radius: 10px;
    padding: 2rem;
    text-align: center;
    border: 1px solid #eee;
}

.match-teams {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1.5rem;
}

.match-team {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    flex: 1;
}

.match-team img {
    width: 60px;
    height: 60px;
    object-fit: contain;
}

.match-team span {
    font-weight: 600;
    font-size: 0.9rem;
}

.match-vs {
    font-weight: 800;
    color: #ccc;
    font-size: 1.2rem;
}

.match-meta {
    display: flex;
    justify-content: center;
    gap: 1.5rem;
    color: #7f8c8d;
    font-size: 0.9rem;
    margin-bottom: 1rem;
}

/* Highlights */
.team-highlights-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 1rem;
}

.highlight-card {
    background: #f8f9fa;
    border-radius: 10px;
    padding: 1rem;
    border-left: 4px solid var(--primary-color, #3498db);
}

.highlight-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
    color: #7f8c8d;
    font-size: 0.85rem;
    text-transform: uppercase;
    font-weight: 600;
}

.highlight-body {
    display: flex;
    align-items: center;
    gap: 1rem;
}

.player-img-container img {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    object-fit: cover;
    border: 2px solid white;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.player-info {
    display: flex;
    flex-direction: column;
}

.player-name {
    font-weight: 700;
    font-size: 0.95rem;
}

.stat-big {
    font-size: 1.2rem;
    font-weight: 800;
    color: var(--primary-color, #3498db);
}

.stat-big small {
    font-size: 0.7rem;
    font-weight: normal;
    color: #7f8c8d;
}

/* Payment Summary */
.payment-summary {
    background: #fff;
    padding: 1.5rem;
    border-top: 1px solid #eee;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 1.5rem;
    margin-top: 1rem;
}

.total-amount {
    font-size: 1.2rem;
    font-weight: 600;
}

.total-amount span {
    color: #e74c3c;
    font-weight: 800;
}

/* Roster Filters */
.roster-filter-controls {
    display: flex;
    gap: 5px;
    background: #f1f3f5;
    padding: 4px;
    border-radius: 6px;
}

.filter-btn {
    border: none;
    background: none;
    padding: 6px 12px;
    border-radius: 4px;
    font-size: 0.85rem;
    cursor: pointer;
    color: #666;
    transition: all 0.2s;
}

.filter-btn:hover {
    background: rgba(0,0,0,0.05);
}

.filter-btn.active {
    background: white;
    color: var(--primary-color, #3498db);
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
    font-weight: 600;
}

/* Status Badges */
.status-badge {
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 0.75rem;
    font-weight: 600;
    text-transform: uppercase;
}

.status-available { background: #d4edda; color: #27ae60; }
.status-injured { background: #f8d7da; color: #c0392b; }
.status-suspended { background: #fff3cd; color: #856404; }
.status-fine { background: #e2e3e5; color: #383d41; }

/* Transaction Badges */
.badge { padding: 4px 10px; border-radius: 20px; font-size: 0.75rem; text-transform: uppercase; font-weight: 700; letter-spacing: 0.5px; }
.badge-deposit { background: #e8f5e9; color: #27ae60; }
.badge-withdrawal { background: #fdecea; color: #c0392b; }
.badge-payment { background: #f3f4f6; color: #7f8c8d; }
.badge-transfer_in { background: #e8f5e9; color: #27ae60; }
.badge-transfer_out { background: #fdecea; color: #c0392b; }
.text-success { color: #27ae60; font-weight: 700; }
.text-danger { color: #e74c3c; font-weight: 700; }

.player-cell {
    display: flex;
    align-items: center;
    gap: 10px;
}

.player-avatar-xs {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    object-fit: cover;
}

/* Modals */
.modal,
.modal-overlay {
    display: none;
    /* Hidden by default */
    position: fixed;
    z-index: 2000;
    /* High z-index to sit on top of everything */
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    /* Prevent body scroll */
    background-color: rgba(0, 0, 0, 0.5);
    /* Flexbox centering */
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;
    pointer-events: none;
}

.modal.show,
.modal-overlay[style*="display: flex"] {
    display: flex !important;
    opacity: 1;
    pointer-events: auto;
}

.modal-content {
    background-color: #fff;
    margin: auto;
    padding: 25px;
    border: none;
    width: 90%;
    max-width: 500px;
    border-radius: 12px;
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
    position: relative;
    max-height: 90vh;
    overflow-y: auto;
    transform: scale(0.95);
    transition: transform 0.3s ease;
}

.modal.show .modal-content,
.modal-overlay[style*="display: flex"] .modal-content {
    transform: scale(1);
}

.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #f0f0f0;
}

.modal-close-btn {
    background: none;
    border: none;
    font-size: 1.5rem;
    line-height: 1;
    color: #999;
    cursor: pointer;
    transition: color 0.2s;
    padding: 0;
}

.modal-close-btn:hover {
    color: #333;
}

.btn-block {
    width: 100%;
    display: block;
    margin-top: 10px;
}

.modal-player-item {
    display: flex;
    justify-content: space-between;
    padding: 10px;
    cursor: pointer;
    border-bottom: 1px solid #eee;
}

.modal-player-item:hover {
    background-color: #f0f4f8;
}

/* Search Results Dropdown */
.search-results {
    border: 1px solid #ddd;
    border-top: none;
    max-height: 200px;
    overflow-y: auto;
    background: #fff;
    position: absolute;
    width: 100%;
    z-index: 100;
    border-radius: 0 0 4px 4px;
    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    display: none; /* Hidden by default */
}
.search-results.show { display: block; }
.search-result-item {
    padding: 10px;
    cursor: pointer;
    border-bottom: 1px solid #eee;
    font-size: 0.9rem;
}
.search-result-item:hover {
    background-color: #f9f9f9;
    color: var(--primary-color, #3498db);
}
.search-result-item:last-child {
    border-bottom: none;
}
.form-group {
    position: relative;
}

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

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

/* Fixture List Styles */
.fixture-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
}
.fixture-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    background: white;
    border-radius: 8px;
    text-decoration: none;
    color: inherit;
    border: 1px solid #eee;
}
.fixture-item .team {
    display: flex;
    align-items: center;
    gap: 10px;
    flex: 1;
}
.fixture-item .team-logo {
    width: 40px;
    height: 40px;
    object-fit: contain;
}
</style>

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

<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 rosterFilterControls = document.querySelector('.roster-filter-controls');
    const addPlayerModal = document.getElementById('addPlayerModal');
    const playerSearchInput = document.getElementById('player_search');
    const playerSearchResults = document.getElementById('player_search_results');
    const selectedUserIdInput = document.getElementById('selected_user_id_for_player');
    const addPlayerBtn = document.getElementById('addPlayerBtn');
    const editPlayerModal = document.getElementById('editPlayerModal');
    const submitRosterModal = document.getElementById('submitRosterModal');
    const releasePlayerModal = document.getElementById('releasePlayerModal');
    const payRefereeFeeModal = document.getElementById('payRefereeFeeModal');

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

    // Wallet Data
    const teamWalletBalance = <?php echo floatval($team_wallet->balance ?? 0); ?>;
    const refereeFee = <?php echo floatval($settings['referee_fee'] ?? 50); ?>;
    const currencySymbol = '<?php echo $currency_symbol; ?>';

    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.get('status') === 'roster_submitted') {
        showToast('Squad submitted for approval successfully!', 'success');
    }
    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);
    });

    // Initial call in case of pre-checked boxes (e.g., browser back button)
    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 (confirmPaymentBtn) {
        confirmPaymentBtn.addEventListener('click', function() {
            if (!paymentData) return;
            
            if (paymentData.form) {
                // Fines payment via form
                paymentData.form.submit();
                closePaymentModal();
            }
        });
    }

    // --- Wallet Payment Logic ---
    if (payWalletButton) {
        payWalletButton.addEventListener('click', function(e) {
            e.preventDefault();
            console.log('Wallet Payment (Team): 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 (Team): Selected Fines', selectedFines);
            console.log('Wallet Payment (Team): Total Amount', totalAmount);

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

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

            // Show Confirmation Modal for Wallet
            paymentText.textContent = `Pay ${selectedFines.length} fines (${'<?php echo $currency_symbol; ?>' + totalAmount.toFixed(2)}) using Team 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 (Team): Confirmed');
                const form = document.getElementById('fines-payment-form');
                console.log('Wallet Payment (Team): Form found', form);
                
                // Append hidden input to simulate button click
                const hiddenInput = document.createElement('input');
                hiddenInput.type = 'hidden';
                hiddenInput.name = 'pay_via_wallet';
                hiddenInput.value = '1';
                form.appendChild(hiddenInput);
                console.log('Wallet Payment (Team): Hidden input appended');

                form.action = 'pay_fines_via_wallet.php'; 
                console.log('Wallet Payment (Team): Submitting to', form.action);
                form.submit();
                closePaymentModal();
            };
        });
    }

    // --- Roster Filtering Logic ---
    if (rosterFilterControls) {
        const rosterRows = document.querySelectorAll('#roster-tbody tr');

        rosterFilterControls.addEventListener('click', function(e) {
            if (e.target.matches('.filter-btn')) {
                // Update active button
                rosterFilterControls.querySelector('.active').classList.remove('active');
                e.target.classList.add('active');

                const filter = e.target.dataset.filter;

                // Filter rows
                rosterRows.forEach(row => {
                    if (filter === 'all' || row.dataset.status === filter) {
                        row.style.display = '';
                    } else {
                        row.style.display = 'none';
                    }
                });
            }
        });
    }

    // --- Add Player Modal Logic ---
    function openAddPlayerModal() { addPlayerModal.classList.add('show'); }
    function closeAddPlayerModal() { addPlayerModal.classList.remove('show'); }

    // --- Submit Roster Modal Logic ---
    window.openSubmitRosterModal = function() { submitRosterModal.classList.add('show'); }
    window.closeSubmitRosterModal = function() { submitRosterModal.classList.remove('show'); }

    // --- Release Player Modal Logic ---
    window.openReleasePlayerModal = function(playerId, playerName) {
        document.getElementById('releasePlayerId').value = playerId;
        document.getElementById('releasePlayerName').textContent = playerName;
        releasePlayerModal.classList.add('show');
    }
    window.closeReleasePlayerModal = function() { releasePlayerModal.classList.remove('show'); }

    // --- Referee Fee Modal Logic ---
    window.openPayRefereeFeeModal = function(fixtureId, matchDescription) {
        document.getElementById('referee_fee_fixture_id').value = fixtureId;
        const infoEl = document.getElementById('referee_fee_match_info');
        if (infoEl && matchDescription) {
            infoEl.innerHTML = 'Match: <strong>' + matchDescription + '</strong>';
        }
        
        // Update Actions based on balance
        const actionsDiv = document.getElementById('referee-fee-actions');
        if (teamWalletBalance < refereeFee) {
            const needed = refereeFee - teamWalletBalance;
            actionsDiv.innerHTML = `<div class="alert alert-danger">Insufficient funds. You need ${currencySymbol}${needed.toFixed(2)} more.<br>Please contact your Club Manager to transfer funds.</div>`;
        } else {
            actionsDiv.innerHTML = `<button type="submit" class="btn btn-block">Pay Fee</button>`;
        }

        payRefereeFeeModal.classList.add('show');
    }
    window.closePayRefereeFeeModal = function() { payRefereeFeeModal.classList.remove('show'); }

    // --- Edit Player Modal Logic ---
    window.openEditPlayerModal = function(player) {
        document.getElementById('edit_player_id').value = player.id;
        document.getElementById('edit_redirect_to').value = 'my_team.php?tab=squad';
        document.getElementById('edit_squad_number').value = player.squad_number || '';
        document.getElementById('edit_position').value = player.position || 'Midfielder';
        document.getElementById('edit_height_cm').value = player.height_cm || '';
        document.getElementById('edit_weight_kg').value = player.weight_kg || '';
        document.getElementById('edit_preferred_foot').value = player.preferred_foot || 'Right';
        document.getElementById('edit_date_of_birth').value = player.date_of_birth || '';
        document.getElementById('edit_nationality').value = player.nationality || '';
        
        editPlayerModal.classList.add('show');
    }
    
    window.closeEditPlayerModal = function() { editPlayerModal.classList.remove('show'); }

    if (playerSearchInput) {
        playerSearchInput.addEventListener('input', function() {
            const query = this.value;
            addPlayerBtn.disabled = true;
            selectedUserIdInput.value = '';
            if (query.length < 2) { playerSearchResults.innerHTML = ''; playerSearchResults.classList.remove('show'); return; }

            fetch(`api/search_users.php?q=${encodeURIComponent(query)}`)
                .then(res => res.json())
                .then(data => {
                    playerSearchResults.innerHTML = '';
                    if (data.length > 0) playerSearchResults.classList.add('show');
                    else playerSearchResults.classList.remove('show');

                    data.forEach(user => {
                        const div = document.createElement('div');
                        div.className = 'search-result-item';
                        div.textContent = `${user.first_name} ${user.last_name} (${user.email})`;
                        div.onclick = () => {
                            playerSearchInput.value = `${user.first_name} ${user.last_name}`;
                            selectedUserIdInput.value = user.id;
                            playerSearchResults.innerHTML = '';
                            playerSearchResults.classList.remove('show');
                            addPlayerBtn.disabled = false;
                        };
                        playerSearchResults.appendChild(div);
                    });
                });
        });
        
        // Close search results when clicking outside
        document.addEventListener('click', function(e) {
            if (!playerSearchInput.contains(e.target) && !playerSearchResults.contains(e.target)) {
                playerSearchResults.classList.remove('show');
            }
        });
    }

    // Attach to global scope if needed for inline onclick
    window.openAddPlayerModal = openAddPlayerModal;
    window.closeAddPlayerModal = closeAddPlayerModal;
    window.addEventListener('click', (e) => { 
        if (e.target === addPlayerModal) closeAddPlayerModal();
        if (e.target === editPlayerModal) closeEditPlayerModal();
        if (e.target === submitRosterModal) closeSubmitRosterModal();
        if (e.target === releasePlayerModal) closeReleasePlayerModal();
        if (e.target === payRefereeFeeModal) closePayRefereeFeeModal();
    });
});
</script>
