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

// Protect this page: redirect to login if user is not logged in.
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}
$user_id = $_SESSION['user_id'];

// --- Instantiate Models ---
$fantasyModel = new Fantasy();
$seasonModel = new Season();
$playerModel = new Player();
$fantasySquadModel = new FantasySquad();
$fixtureModel = new Fixture();
$gameweekModel = new Gameweek();
$settingModel = new Setting();
$leagueModel = new League();

// --- Auto-Migration for league_id in fantasy_teams ---
$db = new Database();
try {
    $db->query("SELECT league_id FROM fantasy_teams LIMIT 1");
    $db->execute();
} catch (Exception $e) {
    // Add league_id and a default value, then create a unique key
    try {
        $db->query("ALTER TABLE fantasy_teams ADD COLUMN league_id INT(11) NOT NULL DEFAULT 1 AFTER season");
        $db->execute();
        // Add a unique constraint to prevent multiple teams per user per league per season
        $db->query("ALTER TABLE fantasy_teams ADD UNIQUE KEY `user_season_league` (`user_id`, `season`, `league_id`)");
        $db->execute();
    } catch (Exception $e) {
        // Ignore if it fails, might already exist from another page load
    }
}

// --- Determine League Context ---
$leagues = $leagueModel->getAll();
$selected_league_id = filter_input(INPUT_GET, 'league_id', FILTER_VALIDATE_INT);
if (!$selected_league_id && !empty($leagues)) {
    $selected_league_id = $leagues[0]->id;
}

// --- Get User's Fantasy Team ---
$seasons = $seasonModel->getAll();
$latest_season = null;
foreach ($seasons as $season) {
    if (isset($season->is_active) && $season->is_active) {
        $latest_season = $season->name;
        break;
    }
}
$latest_season = $latest_season ?? ($seasons[0]->name ?? date('Y') . '/' . (date('Y') + 1));

$user_fantasy_team = $fantasyModel->getTeamByUserIdAndLeague($user_id, $latest_season, $selected_league_id);

// Check if squad is already created to redirect before header output
$current_squad_raw = [];
if ($user_fantasy_team) {
    $current_squad_raw = $fantasySquadModel->getSquadByTeamId($user_fantasy_team->id);
    if (count($current_squad_raw) > 0) {
        header('Location: fantasy_lineup.php?league_id=' . $selected_league_id);
        exit();
    }
}

$pageTitle = 'Fantasy Football';
include 'includes/header.php';

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

// Helper function for currency formatting
function formatFantasyPrice($amount, $currency_symbol) {
    return $currency_symbol . number_format($amount, 1) . 'm';
}

// --- Determine Current Gameweek ---
$current_gameweek = 1;
$league_id_for_gameweek = $selected_league_id;
$latest_finished_gameweek = $fixtureModel->getLatestFinishedGameweek($league_id_for_gameweek);
if ($latest_finished_gameweek) {
    $current_gameweek = $latest_finished_gameweek + 1;
} else {
    $next_fixture = $fixtureModel->getNextUpcomingFixture($league_id_for_gameweek);
    if ($next_fixture) {
        $current_gameweek = $next_fixture->gameweek;
    }
}

$deadline_passed = $gameweekModel->hasDeadlinePassed($current_gameweek, $league_id_for_gameweek, $latest_season);

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

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

.fantasy-welcome-page {
    max-width: 1200px;
    margin: 0 auto;
}

.fantasy-hero-wrapper {
    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);
}

.team-identity {
    display: flex;
    align-items: center;
    gap: 15px;
    margin-bottom: 20px;
}

.team-kit-icon {
    font-size: 2.5rem;
    background: rgba(255,255,255,0.1);
    width: 60px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
}

.team-text h1 { margin: 0; font-size: 1.5rem; }
.manager-name { opacity: 0.8; font-size: 0.9rem; }

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

.gameweek-badge {
    text-align: center;
    background: rgba(255,255,255,0.1);
    padding: 5px 15px;
    border-radius: 8px;
}
.gw-label { display: block; font-size: 0.7rem; text-transform: uppercase; }
.gw-number { font-size: 1.5rem; font-weight: bold; }

.fantasy-stats-strip {
    display: flex;
    gap: 10px;
    overflow-x: auto;
}
.fantasy-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;
}
.fantasy-stats-strip .label { display: block; font-size: 0.7rem; opacity: 0.8; }
.fantasy-stats-strip .value { font-size: 1.1rem; font-weight: bold; }

.fantasy-welcome-page .dashboard-section {
    background: transparent;
    border: none;
    box-shadow: none;
    padding: 0;
}

.how-to-play-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    margin-top: 2rem;
    gap: 1.5rem;
}

.how-to-item {
    background: var(--card-bg);
    padding: 2rem;
    border-radius: 12px;
    text-align: center;
    box-shadow: 0 4px 15px rgba(0,0,0,0.05);
    border: 1px solid var(--border-color);
    transition: transform 0.2s, box-shadow 0.2s;
}

.how-to-item:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 25px rgba(0,0,0,0.08);
}

.how-to-item i {
    font-size: 2.5rem;
    color: var(--primary-color);
    margin-bottom: 1rem;
}

.how-to-item h3 {
    margin: 0 0 0.5rem 0;
    font-size: 1.2rem;
}

.how-to-item p {
    font-size: 0.9rem;
    color: var(--text-color);
    opacity: 0.8;
    line-height: 1.5;
}

.create-team-section {
    text-align: center;
    margin-top: 3rem;
    background: var(--card-bg);
    padding: 2rem;
    border-radius: 12px;
}

.create-team-section p {
    margin-bottom: 1rem;
}

.budget-progress-bar-container {
    background: rgba(0,0,0,0.2);
    border-radius: 20px;
    padding: 3px;
    margin: -10px 0 20px 0;
}

.budget-progress-bar {
    height: 10px;
    background: linear-gradient(90deg, #00ff85 0%, #f1c40f 70%, #e74c3c 100%);
    border-radius: 20px;
    width: 0%;
    transition: width 0.5s cubic-bezier(0.25, 0.8, 0.25, 1);
}

/* --- Onboarding --- */
.onboarding-progress {
    display: flex;
    justify-content: space-between;
    margin-bottom: 2rem;
    position: relative;
    max-width: 600px;
    margin-left: auto;
    margin-right: auto;
}

.onboarding-progress::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 0;
    right: 0;
    height: 2px;
    background: #e0e0e0;
    z-index: 0;
    transform: translateY(-50%);
}

.step {
    position: relative;
    z-index: 1;
    background: #f0f2f5;
    padding: 0 10px;
    display: flex;
    align-items: center;
    gap: 8px;
    color: #95a5a6;
}

.step.active, .step.completed {
    color: var(--primary-color, #3498db);
    font-weight: 600;
}

.step-icon {
    width: 30px;
    height: 30px;
    background: #fff;
    border: 2px solid #e0e0e0;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
}

.step.active .step-icon {
    border-color: var(--primary-color, #3498db);
    background: var(--primary-color, #3498db);
    color: white;
}

.step.completed .step-icon {
    border-color: #27ae60;
    background: #27ae60;
    color: white;
}

.fantasy-dashboard {
    background-color: #f0f2f5;
    margin: -2rem 0;
    /* Extend to edges */
    padding: 0;
}

.fantasy-header {
    background: var(--primary-color, #3498db);
    color: #fff;
    padding: 1.5rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.fantasy-info-bar {
    display: flex;
    gap: 2rem;
    background: rgba(255,255,255,0.1);
    padding: 10px 20px;
    border-radius: 8px;
    backdrop-filter: blur(5px);
}

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

.info-label {
    font-size: 0.75rem;
    text-transform: uppercase;
    opacity: 0.8;
}

.info-value {
    font-size: 1.2rem;
    font-weight: bold;
}

.points-display {
    text-align: left;
}

.points-display .points-value {
    font-size: 2.5em;
    font-weight: bold;
    display: block;
    line-height: 1;
}

.points-display .points-label {
    font-size: 0.9em;
    opacity: 0.8;
}

.team-name-display {
    text-align: right;
}

.team-name-display h4 {
    margin: 0 0 8px 0;
    font-size: 1.2em;
    color: #fff;
}

.fantasy-form-container {
    text-align: center;
    padding: 2rem;
    background: #fff;
    border-radius: 8px;
}

#create-fantasy-team-form {
    display: flex;
    flex-direction: column;
    gap: 1rem;
    max-width: 400px;
    margin: 1rem auto 0 auto;
}

#create-fantasy-team-form input {
    padding: 12px;
    border: 1px solid #ddd;
    border-radius: 6px;
    font-size: 1rem;
}

/* --- Submit Lineup --- */
.pitch-row.goalkeeper {
    display: flex;
    justify-content: center;
}

.lineup-controls {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 2rem;
    background: #f9f9f9;
    padding: 1rem;
    border-radius: 8px;
}

.pitch-area {
    background-image: linear-gradient(0deg, #27ae60 0%, #2ecc71 100%);
    border: 2px solid #fff;
    border-radius: 8px;
    padding: 1rem;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.fantasy-pitch {
    height: 600px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.pitch {
    height: 450px;
    display: flex;
    flex-direction: column-reverse;
    justify-content: space-around;
}

.pitch-row {
    display: flex;
    justify-content: space-around;
    align-items: center;
}

.squad-selection-row {
    display: flex;
    justify-content: center;
    gap: 1rem;
    flex: 1;
    align-items: center;
}

.player-slot {
    width: 80px;
    height: 90px;
    border: 2px dashed rgba(255, 255, 255, 0.5);
    border-radius: 4px;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: background-color 0.2s;
    position: relative;
}

.player-slot:hover {
    background-color: rgba(255, 255, 255, 0.1);
}

.player-slot .fa-plus {
    color: rgba(255, 255, 255, 0.7);
    font-size: 1.5rem;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    opacity: 0;
    transition: opacity 0.2s;
}

.player-slot:hover .fa-plus {
    opacity: 1;
}

.player-slot:hover .slot-placeholder {
    opacity: 0.2;
}

.player-card {
    text-align: center;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.player-shirt {
    color: #3498db;
    font-size: 2.5rem;
}

.player-shirt img {
    width: 50px;
    height: 50px;
    object-fit: cover;
    border-radius: 50%;
}

.player-name-label {
    background-color: rgba(0, 0, 0, 0.6);
    color: white;
    font-size: 0.7rem;
    padding: 2px 6px;
    border-radius: 4px;
    white-space: nowrap;
    margin-top: 4px;
    display: inline-block;
}

.player-price-tag {
    background-color: #27ae60;
    color: white;
    font-size: 0.7rem;
    padding: 1px 5px;
    border-radius: 4px;
    margin-top: 2px;
    font-weight: bold;
    display: inline-block;
}

.slot-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: rgba(255,255,255,0.8);
    transition: opacity 0.2s;
}

.slot-placeholder i {
    font-size: 1.8rem;
    margin-bottom: 5px;
}

.slot-placeholder span {
    font-size: 0.8rem;
    font-weight: 700;
}

.substitutes-bench-area {
    margin-top: 2rem;
}

.substitutes-bench {
    display: flex;
    gap: 10px;
    justify-content: center;
    background: #f0f2f5;
    padding: 1rem;
    border-radius: 8px;
}

.sub-slot {
    background-color: #e9ecef;
    border-style: solid;
}

.sub-slot .fa-plus {
    color: #6c757d;
}

.sub-slot .player-shirt {
    color: #868e96;
}

/* --- Modal Styles --- */
.modal {
    display: none; 
    position: fixed; 
    z-index: 1000; 
    left: 0;
    top: 0;
    width: 100%; 
    height: 100%; 
    overflow: auto; 
    background-color: rgba(0,0,0,0.5); 
    opacity: 0;
    transition: opacity 0.3s ease;
}

.modal.show {
    display: block;
    opacity: 1;
}

.modal-content {
    background-color: #fefefe;
    margin: 5% auto; 
    padding: 0;
    border: 1px solid #888;
    width: 90%;
    max-width: 600px;
    border-radius: 12px;
    box-shadow: 0 5px 15px rgba(0,0,0,0.3);
}

.modal-header {
    padding: 1rem 1.5rem;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.modal-body {
    padding: 1.5rem;
    max-height: 70vh;
    overflow-y: auto;
}

.modal-close-btn {
    background: none;
    border: none;
    font-size: 1.5rem;
    cursor: pointer;
    color: #aaa;
}

.player-search-input {
    width: 100%;
    padding: 12px;
    border: 1px solid #ddd;
    border-radius: 8px;
    margin-bottom: 1rem;
    font-size: 1rem;
}

.modal-player-list {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
}

.modal-player-item {
    display: flex;
    justify-content: space-between;
    padding: 10px;
    border-radius: 6px;
    cursor: pointer;
    transition: background 0.2s;
    border: 1px solid #eee;
}

.modal-player-item:hover {
    background-color: #f5f7fa;
    border-color: var(--primary-color, #3498db);
}

.modal-player-item.disabled {
    opacity: 0.6;
    cursor: not-allowed;
    background-color: #f9f9f9;
}

.modal-player-item .player-info {
    display: flex;
    align-items: center;
    gap: 10px;
}

.modal-player-item .modal-player-img {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    object-fit: cover;
}

.modal-player-item .player-details {
    display: flex;
    flex-direction: column;
}

/* --- Toast Notification Styles --- */
#toast-container {
    position: fixed;
    bottom: 20px;
    right: 20px;
    z-index: 10000;
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.toast {
    background-color: #333;
    color: #fff;
    padding: 12px 20px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
    opacity: 1;
    transition: opacity 0.3s ease-in-out, transform 0.3s ease-in-out;
    transform: translateY(0);
    min-width: 250px;
    display: flex;
    align-items: center;
    font-size: 0.95rem;
}

.toast.hide {
    opacity: 0;
    transform: translateY(20px);
}

.toast-success { background-color: #28a745; }
.toast-error { background-color: #dc3545; }
.toast-info { background-color: #17a2b8; }
</style>
<?php
if (!$user_fantasy_team) {
    // If user has no team, show a form to create one
    // This is a more engaging welcome page for new fantasy players.
    ?>
    <div class="fantasy-hero-wrapper fantasy-welcome-hero">
         <div class="fantasy-hero-content">
            <div class="team-identity">
                <div class="team-kit-icon"><i class="fa-solid fa-shield-halved"></i></div>
                <div class="team-text">
                    <h1 class="team-name">Welcome to Fantasy</h1>
                    <span class="manager-name">Your journey to become the ultimate manager starts here.</span>
                </div>
            </div>
        </div>

    </div>
    <div class="page-content fantasy-welcome-page">
        <div class="dashboard-section" style="background: #fff; padding: 20px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">
            <form action="fantasy.php" method="GET" class="selectors-form">
                <label for="league_id_select" style="font-weight: bold; margin-right: 10px; font-size: 1.1rem;">Select League:</label>
                <select name="league_id" id="league_id_select" onchange="this.form.submit()" style="flex: 1; padding: 10px; border-radius: 6px; border: 1px solid #ddd; font-size: 1rem;">
                    <?php foreach ($leagues as $league): ?>
                        <option value="<?php echo $league->id; ?>" <?php echo ($league->id == $selected_league_id) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($league->name); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </form>
        </div>

        <div class="dashboard-section">
            <h2 class="dashboard-title">How to Play</h2>
            <div class="how-to-play-grid">
                <div class="how-to-item">
                    <i class="fa-solid fa-user-plus"></i>
                    <h3>1. Create Your Team</h3>
                    <p>Every great legacy starts with a name. Pick a unique name for your fantasy team!</p>
                </div>
                <div class="how-to-item">
                    <i class="fa-solid fa-users"></i>
                    <h3>2. Build Your Squad</h3>
                    <p>With a budget of <?php echo $currency_symbol; ?>100.0m, select 15 players: 2 Goalkeepers, 5 Defenders, 5 Midfielders, and 3 Forwards.</p>
                </div>
                <div class="how-to-item">
                    <i class="fa-solid fa-futbol"></i>
                    <h3>3. Score Points</h3>
                    <p>Your players score points for goals, assists, clean sheets, and more in their real-life matches.</p>
                </div>
                <div class="how-to-item">
                    <i class="fa-solid fa-trophy"></i>
                    <h3>4. Compete & Win</h3>
                    <p>Join leagues to compete with friends and other managers. Make transfers and pick your captain wisely to top the table!</p>
                </div>
            </div>
        </div>

        <div class="dashboard-section create-team-section">
            <h2 class="dashboard-title">Let's Get Started!</h2>
            <p>Choose a name for your team to begin your fantasy manager career.</p>
            <div class="form-container" style="max-width: 500px; margin: 2rem auto 0 auto;">
                <form action="fantasy_create_team.php" method="POST" class="auth-form">
                    <input type="hidden" name="league_id" value="<?php echo $selected_league_id; ?>">
                    <div class="form-group">
                        <label for="team_name">My Team Name</label>
                        <input type="text" name="team_name" id="team_name" placeholder="e.g., The <?php echo htmlspecialchars($appName); ?> Champions" required>
                    </div>
                    <button type="submit" class="btn btn-primary" style="width: 100%;">Create My Team</button>
                </form>
            </div>
        </div>
    </div>
    <?php
    include_once 'includes/footer.php';
    exit();
}

// --- Fetch Data for Squad Builder ---
$all_players = $playerModel->getPlayersForFantasySelection($selected_league_id);

// This part will now only execute if the squad is empty (initial creation)
// Flatten all_players for easy JS lookup
$all_players_map = [];
foreach ($all_players as $player) {
    $all_players_map[$player->id] = $player;
}

?>

<!-- New Fantasy Hero Section -->
<div class="fantasy-hero-wrapper">
    <div class="fantasy-hero-content">
        <div class="team-identity">
            <div class="team-kit-icon"><i class="fa-solid fa-shirt"></i></div>
            <div class="team-text">
                <h1 class="team-name"><?php echo htmlspecialchars($user_fantasy_team->name); ?></h1>
                <span class="manager-name"><?php echo htmlspecialchars($_SESSION['user_name'] ?? 'Manager'); ?></span>
            </div>
        </div>
        <div class="gameweek-badge">
            <span class="gw-label">Gameweek</span>
            <span class="gw-number"><?php echo $current_gameweek; ?></span>
        </div>
    </div>
    
    <div class="fantasy-stats-strip">
        <div class="stat-box">
            <span class="label">Bank</span>
            <span class="value" id="money-remaining"><?php echo formatFantasyPrice($user_fantasy_team->bank, $currency_symbol); ?></span>
        </div>
        <div class="stat-box">
            <span class="label">Squad Value</span>
            <span class="value" id="squad-value"><?php echo formatFantasyPrice($user_fantasy_team->squad_value ?? 0, $currency_symbol); ?></span>
        </div>
        <div class="stat-box">
            <span class="label">GW Points</span>
            <span class="value"><?php echo $user_fantasy_team->gameweek_points; ?></span>
        </div>
        <div class="stat-box">
            <span class="label">Total Points</span>
            <span class="value"><?php echo $user_fantasy_team->total_points; ?></span>
        </div>
    </div>

    <div class="budget-progress-bar-container">
        <div id="budget-progress-bar" class="budget-progress-bar"></div>
    </div>

</div>

<div class="page-content">
    <div class="onboarding-progress">
        <div class="step completed"><span class="step-icon"><i class="fa-solid fa-check"></i></span> <span class="step-text">Create Team</span></div>
        <div class="step active"><span class="step-icon">2</span> <span class="step-text">Select Squad</span></div>
        <div class="step"><span class="step-icon">3</span> <span class="step-text">Play</span></div>
    </div>

    <div class="dashboard-section">
        <div class="lineup-controls">
            <div class="instructions">
                <h3>Build Your Squad</h3>
                <p>Select 15 players within the <strong><?php echo $currency_symbol; ?>100.0m</strong> budget.</p>
            </div>
            <div class="controls-actions" style="display: flex; gap: 10px;">
                <button type="button" id="reset-squad-btn" class="btn btn-secondary"><i class="fa-solid fa-rotate-left"></i> Reset</button>
                <button type="button" id="auto-pick-btn" class="btn btn-secondary"><i class="fa-solid fa-wand-magic-sparkles"></i> Auto Pick</button>
                <button type="button" id="save-squad-btn" class="btn btn-primary btn-lg" disabled>Confirm Squad <i class="fa-solid fa-arrow-right"></i></button>
            </div>
        </div>

        <?php if ($deadline_passed): ?>
            <div class="status-message info" style="background: #e1f5fe; color: #2c3e50; padding: 15px; border-radius: 8px; margin-bottom: 20px; border-left: 4px solid #29b6f6;">The deadline for Gameweek <?php echo $current_gameweek; ?> has passed. You can still create your team, but you will start scoring points from <strong>Gameweek <?php echo $current_gameweek + 1; ?></strong>.</div>
        <?php endif; ?>

        <div class="lineup-builder-container">
            <div class="pitch-area fantasy-pitch">
                <div class="squad-selection-row">
                    <?php for ($i = 0; $i < 2; $i++): ?>
                        <div class="player-slot" data-position="Goalkeeper"><div class="slot-placeholder"><i class="fa-solid fa-shirt"></i><span>GK</span></div><i class="fa-solid fa-plus add-icon"></i></div>
                    <?php endfor; ?>
                </div>
                <div class="squad-selection-row">
                    <?php for ($i = 0; $i < 5; $i++): ?><div class="player-slot" data-position="Defender"><div class="slot-placeholder"><i class="fa-solid fa-shirt"></i><span>DEF</span></div><i class="fa-solid fa-plus add-icon"></i></div><?php endfor; ?>
                </div>
                <div class="squad-selection-row">
                    <?php for ($i = 0; $i < 5; $i++): ?><div class="player-slot" data-position="Midfielder"><div class="slot-placeholder"><i class="fa-solid fa-shirt"></i><span>MID</span></div><i class="fa-solid fa-plus add-icon"></i></div><?php endfor; ?>
                </div>
                <div class="squad-selection-row">
                    <?php for ($i = 0; $i < 3; $i++): ?><div class="player-slot" data-position="Forward"><div class="slot-placeholder"><i class="fa-solid fa-shirt"></i><span>FWD</span></div><i class="fa-solid fa-plus add-icon"></i></div><?php endfor; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal for Player Selection -->
<div id="playerSelectModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="modal-title">Select a Player</h3>
            <button id="modal-close-btn" class="modal-close-btn">&times;</button>
        </div>
        <div class="modal-body">
            <input type="text" id="modal-player-search" placeholder="Search player..." class="player-search-input">
            <div id="playerList" class="modal-player-list"></div>
        </div>
    </div>
</div>

<!-- Confirmation Modal -->
<div id="confirmationModal" class="modal">
    <div class="modal-content" style="max-width: 400px;">
        <div class="modal-header">
            <h3>Confirm Action</h3>
            <button class="modal-close-btn" id="confirm-modal-close">&times;</button>
        </div>
        <div class="modal-body">
            <p id="confirmation-message"></p>
            <div style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 20px;">
                <button class="btn btn-secondary" id="confirm-modal-cancel">Cancel</button>
                <button class="btn btn-primary" id="confirm-modal-ok">Confirm</button>
            </div>
        </div>
    </div>
</div>

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

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

<script>
document.addEventListener('DOMContentLoaded', function() {
    const allPlayers = <?php echo json_encode($all_players_map); ?>;
    const totalBudget = 100.0;
    const currencySymbol = '<?php echo $currency_symbol; ?>';
    const deadlinePassed = <?php echo json_encode($deadline_passed); ?>;

    const saveSquadBtn = document.getElementById('save-squad-btn');
    const autoPickBtn = document.getElementById('auto-pick-btn');
    const resetSquadBtn = document.getElementById('reset-squad-btn');
    const moneyRemainingSpan = document.getElementById('money-remaining');
    const squadValueSpan = document.getElementById('squad-value');
    const modal = document.getElementById('playerSelectModal');
    const modalTitle = document.getElementById('modal-title');
    const modalPlayerList = document.getElementById('playerList');
    const modalCloseBtn = document.getElementById('modal-close-btn');
    const modalPlayerSearch = document.getElementById('modal-player-search');
    const modalPositionFilters = modal.querySelector('.player-filters');
    
    const confirmationModal = document.getElementById('confirmationModal');
    const confirmMessage = document.getElementById('confirmation-message');
    const confirmOkBtn = document.getElementById('confirm-modal-ok');
    const confirmCancelBtn = document.getElementById('confirm-modal-cancel');
    const confirmCloseBtn = document.getElementById('confirm-modal-close');
    const toastContainer = document.getElementById('toast-container');

    // Check URL for errors
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.has('error')) {
        showToast(urlParams.get('error').replace(/_/g, ' '), 'error');
    }

    let activeSlot = null; // The slot currently being filled
    let currentSquad = {}; // {playerId: {playerData, slotElement}}
    let squadValue = 0;

    // --- Utility Functions ---
    function formatFantasyPriceJS(amount) {
        const numericAmount = parseFloat(amount);
        if (isNaN(numericAmount)) {
            return currencySymbol + '0.0m'; // Fallback for invalid numbers
        }
        return currencySymbol + numericAmount.toFixed(1) + 'm';
    }

    function updateBankAndSquadValue() {
        let currentSquadValue = 0;
        Object.values(currentSquad).forEach(playerObj => {
            currentSquadValue += parseFloat(playerObj.playerData.fantasy_price || 0);
        });
        squadValue = currentSquadValue;
        const remainingBank = totalBudget - squadValue;
        moneyRemainingSpan.textContent = formatFantasyPriceJS(remainingBank);
        squadValueSpan.textContent = formatFantasyPriceJS(squadValue);

        const budgetProgressBar = document.getElementById('budget-progress-bar');
        if (budgetProgressBar) {
            const percentageUsed = (squadValue / totalBudget) * 100;
            budgetProgressBar.style.width = `${Math.min(100, percentageUsed)}%`;
        }
    }

    function getSquadCountByPosition() {
        const counts = { 'Goalkeeper': 0, 'Defender': 0, 'Midfielder': 0, 'Forward': 0 };
        Object.values(currentSquad).forEach(playerObj => {
            counts[playerObj.slotElement.dataset.position]++;
        });
        return counts;
    }

    function validateSquad() {
        const valid = Object.keys(currentSquad).length === 15;
        saveSquadBtn.disabled = !valid;
    }

    // --- Toast & Confirmation Utilities ---
    function showToast(message, type = 'info') {
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`;
        toast.textContent = message;
        toastContainer.appendChild(toast);
        
        // Trigger reflow
        void toast.offsetWidth;
        
        setTimeout(() => {
            toast.classList.add('hide');
            toast.addEventListener('transitionend', () => toast.remove());
        }, 3000);
    }

    function showConfirmation(message, onConfirm) {
        confirmMessage.textContent = message;
        confirmationModal.classList.add('show');
        
        // Remove previous event listeners to avoid stacking
        const newOkBtn = confirmOkBtn.cloneNode(true);
        confirmOkBtn.parentNode.replaceChild(newOkBtn, confirmOkBtn);
        
        newOkBtn.addEventListener('click', () => {
            confirmationModal.classList.remove('show');
            onConfirm();
        });
    }

    function closeConfirmation() {
        confirmationModal.classList.remove('show');
    }

    // --- Player Selection Modal ---
    function showPlayerSelectionModal(slot) {
        if (deadlinePassed) return;
        activeSlot = slot;
        modalTitle.textContent = `Select a ${slot.dataset.position}`;
        modal.classList.add('show');
        populateModalPlayerList();
    }

    function populateModalPlayerList() {
        const searchQuery = modalPlayerSearch.value.toLowerCase();
        const requiredPosition = activeSlot.dataset.position;

        let playerListHTML = '';
        const playersInSquadIds = Object.keys(currentSquad).map(Number);

        for (const playerId in allPlayers) {
            const player = allPlayers[playerId];
            // Filter by selected position in modal, and by player's actual position
            const positionMatch = (player.position === requiredPosition);
            const nameMatch = (player.first_name + ' ' + player.last_name).toLowerCase().includes(searchQuery);
            const isInSquad = playersInSquadIds.includes(parseInt(player.id));

            if (positionMatch && nameMatch && !isInSquad) {
                playerListHTML += `<div class="modal-player-item" data-player-id="${player.id}" data-player-price="${player.fantasy_price}" data-player-position="${player.position}">
                                    <div class="player-info">
                                        <img src="${player.profile_picture || '/smart_football/public/assets/images/default_avatar.png'}" class="modal-player-img">
                                        <div class="player-details">
                                            <span>#${player.squad_number} - ${player.first_name} ${player.last_name}</span>
                                            <small>${player.club_name}</small>
                                        </div>
                                    </div>
                                    <span>${formatFantasyPriceJS(player.fantasy_price)}</span>
                                </div>`;
            } else if (isInSquad) {
                playerListHTML += `<div class="modal-player-item disabled">
                                    <div class="player-info">
                                        <span>#${player.squad_number} - ${player.first_name} ${player.last_name}</span>
                                    </div>
                                    <span>In Squad</span>
                                </div>`;
            }
        }

        if (playerListHTML === '') {
            playerListHTML = '<p class="no-data-msg">No players found matching criteria.</p>';
        }
        modalPlayerList.innerHTML = playerListHTML;

        document.querySelectorAll('.modal-player-item:not(.disabled)').forEach(item => {
            item.addEventListener('click', () => {
                const selectedPlayer = allPlayers[item.dataset.playerId];
                placePlayerInSlot(selectedPlayer, activeSlot);
                modal.classList.remove('show');
            });
        });
    }

    function placePlayerInSlot(playerData, slot) {
        // If there's a player in the target slot, remove them first
        const existingPlayerCard = slot.querySelector('.player-card');
        if (existingPlayerCard) {
            removePlayerFromSlot(slot); // This will update bank and currentSquad
        }

        // Check if adding this player exceeds the bank
        const tempSquadValue = squadValue + parseFloat(playerData.fantasy_price);
        if (tempSquadValue > totalBudget) {
            showToast("You don't have enough money in the bank for this player.", "error");
            // Re-add the plus icon if the slot is now empty
            resetSlot(slot);
            return;
        }

        // Add player to new slot
        slot.innerHTML = `<div class="player-card" data-player-id='${playerData.id}' data-player-price='${playerData.fantasy_price}'>
                            <div class="player-shirt"><img src="${playerData.profile_picture || '/smart_football/public/assets/images/default_avatar.png'}" alt="Player"></div>
                            <span class="player-name-label">${playerData.last_name}</span>
                            <span class="player-price-tag">${formatFantasyPriceJS(playerData.fantasy_price)}</span>
                        </div>`;
        slot.querySelector('.player-card').addEventListener('click', handleSlotClick);

        currentSquad[playerData.id] = { playerData: playerData, slotElement: slot }; // Store reference to the slot
        updateBankAndSquadValue();
        validateSquad();
    }

    function removePlayerFromSlot(slot) {
        const playerCard = slot.querySelector('.player-card');
        if (!playerCard) return;

        const playerId = parseInt(playerCard.dataset.playerId);
        const playerPrice = parseFloat(playerCard.dataset.playerPrice);

        delete currentSquad[playerId];

        resetSlot(slot);
        slot.addEventListener('click', handleSlotClick); // Re-add listener
        updateBankAndSquadValue();
        validateSquad();
    }

    function resetSlot(slot) {
        const pos = slot.dataset.position;
        let shortPos = 'GK';
        if(pos === 'Defender') shortPos = 'DEF'; else if(pos === 'Midfielder') shortPos = 'MID'; else if(pos === 'Forward') shortPos = 'FWD';
        
        slot.innerHTML = `<div class="slot-placeholder"><i class="fa-solid fa-shirt"></i><span>${shortPos}</span></div><i class="fa-solid fa-plus add-icon"></i>`;
    }

    function handleSlotClick(e) {
        const slot = e.target.closest('.player-slot');
        if (!slot) return;

        if (slot.querySelector('.player-card')) {
            removePlayerFromSlot(slot);
        } else {
            showPlayerSelectionModal(slot);
        }
    }

    // --- Auto Pick Logic ---
    if (autoPickBtn) {
        autoPickBtn.addEventListener('click', autoPickSquad);
    }

    if (resetSquadBtn) {
        resetSquadBtn.addEventListener('click', resetSquad);
    }

    function resetSquad() {
        if (Object.keys(currentSquad).length > 0) {
            showConfirmation("Are you sure you want to clear your squad selection?", function() {
                currentSquad = {};
                document.querySelectorAll('.player-slot').forEach(slot => resetSlot(slot));
                updateBankAndSquadValue();
                validateSquad();
                showToast("Squad cleared.", "success");
            });
        }
    }

    function autoPickSquad() {
        // 1. Clear Squad
        currentSquad = {};
        document.querySelectorAll('.player-slot').forEach(slot => resetSlot(slot));
        updateBankAndSquadValue();

        // 2. Prepare Pools
        const playersByPos = { 'Goalkeeper': [], 'Defender': [], 'Midfielder': [], 'Forward': [] };
        Object.values(allPlayers).forEach(p => {
            if (!isNaN(parseFloat(p.fantasy_price))) {
                playersByPos[p.position].push(p);
            }
        });

        // 3. Select Randomly
        let selected = [];
        const requirements = { 'Goalkeeper': 2, 'Defender': 5, 'Midfielder': 5, 'Forward': 3 };
        const shuffle = (arr) => arr.sort(() => Math.random() - 0.5);

        for (const [pos, count] of Object.entries(requirements)) {
            if (playersByPos[pos].length < count) {
                showToast(`Not enough ${pos}s available to auto-pick.`, "error");
                return;
            }
            const shuffled = shuffle([...playersByPos[pos]]);
            selected.push(...shuffled.slice(0, count));
        }

        // 4. Budget Adjustment (Swap expensive players if over budget)
        let totalCost = selected.reduce((sum, p) => sum + parseFloat(p.fantasy_price), 0);
        let attempts = 0;
        const maxAttempts = 200;

        while (totalCost > totalBudget && attempts < maxAttempts) {
            // Sort by price descending
            selected.sort((a, b) => parseFloat(b.fantasy_price) - parseFloat(a.fantasy_price));
            
            // Try to swap a random player from the top half of expensive players
            const indexToSwap = Math.floor(Math.random() * Math.min(selected.length, 5)); 
            const playerOut = selected[indexToSwap];
            const currentIds = selected.map(p => p.id);
            
            // Find cheaper candidates
            const candidates = playersByPos[playerOut.position].filter(p => !currentIds.includes(p.id) && parseFloat(p.fantasy_price) < parseFloat(playerOut.fantasy_price));

            if (candidates.length > 0) {
                const playerIn = candidates[Math.floor(Math.random() * candidates.length)];
                selected[indexToSwap] = playerIn;
                totalCost = selected.reduce((sum, p) => sum + parseFloat(p.fantasy_price), 0);
            }
            attempts++;
        }

        // 5. Place in Slots
        const selectedByPos = { 'Goalkeeper': [], 'Defender': [], 'Midfielder': [], 'Forward': [] };
        selected.forEach(p => selectedByPos[p.position].push(p));

        document.querySelectorAll('.player-slot').forEach(slot => {
            const pos = slot.dataset.position;
            if (selectedByPos[pos].length > 0) {
                placePlayerInSlot(selectedByPos[pos].pop(), slot);
            }
        });
    }

    // --- Event Listeners ---
    document.querySelectorAll('.player-slot').forEach(slot => slot.addEventListener('click', handleSlotClick));

    modalCloseBtn.addEventListener('click', () => modal.classList.remove('show'));
    modal.addEventListener('click', (event) => {
        if (event.target === modal) modal.classList.remove('show');
    });
    
    confirmCancelBtn.addEventListener('click', closeConfirmation);
    confirmCloseBtn.addEventListener('click', closeConfirmation);

    modalPlayerSearch.addEventListener('keyup', populateModalPlayerList);
    
    saveSquadBtn.addEventListener('click', function() {
        if (Object.keys(currentSquad).length !== 15) {
            showToast("Please select a full squad of 15 players.", "error");
            return;
        }

        // Create a hidden form and submit
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = 'fantasy_squad_process.php';

        const fantasyTeamIdInput = document.createElement('input');
        fantasyTeamIdInput.type = 'hidden';
        fantasyTeamIdInput.name = 'fantasy_team_id';
        fantasyTeamIdInput.value = <?php echo $user_fantasy_team->id; ?>;
        form.appendChild(fantasyTeamIdInput);

        Object.keys(currentSquad).forEach(playerId => {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'player_ids[]';
            input.value = playerId;
            form.appendChild(input);
        });

        document.body.appendChild(form);
        form.submit();
    });    

    updateBankAndSquadValue();
    validateSquad();
});
</script>