<?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 needed for pre-header logic
$fantasyModel = new Fantasy();
$seasonModel = new Season();
$leagueModel = new League();

// --- 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
$latest_season = $seasonModel->getAll()[0]->name ?? date('Y') . '/' . (date('Y') + 1);
$user_fantasy_team = $fantasyModel->getTeamByUserIdAndLeague($user_id, $latest_season, $selected_league_id);

if (!$user_fantasy_team) {
    // If user has no team, they can't make transfers. Redirect them.
    header('Location: fantasy.php?league_id=' . $selected_league_id);
    exit();
}

// Now that all checks and redirects are done, we can start outputting the page.
$pageTitle = 'Fantasy Transfers';
include 'includes/header.php';

// Instantiate remaining models for display logic
$playerModel = new Player();
$fantasySquadModel = new FantasySquad();
$fixtureModel = new Fixture();
$gameweekModel = new Gameweek();

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

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

// --- Logic: Earn 1 free transfer every week, max 4, then reset to 1 ---
$db = new Database();
$last_gw_update = $user_fantasy_team->last_gw_update ?? ($current_gameweek - 1);
$current_ft = $user_fantasy_team->free_transfers ?? 1;

if ($current_gameweek > $last_gw_update) {
    $weeks_passed = $current_gameweek - $last_gw_update;
    for ($i = 0; $i < $weeks_passed; $i++) {
        if ($current_ft < 4) {
            $current_ft++;
        } else {
            $current_ft = 1;
        }
    }
    // Update DB
    $db->query("UPDATE fantasy_teams SET free_transfers = :ft, last_gw_update = :gw WHERE id = :id");
    $db->bind(':ft', $current_ft);
    $db->bind(':gw', $current_gameweek);
    $db->bind(':id', $user_fantasy_team->id);
    $db->execute();
    $user_fantasy_team->free_transfers = $current_ft; // Update local object
}

// Get all available players for the league
$all_players = $playerModel->getPlayersForFantasySelection($selected_league_id);

// Get the user's current squad to know which players are already selected
$current_squad = $fantasySquadModel->getSquadByTeamId($user_fantasy_team->id);
$current_squad_ids = array_map(fn($p) => $p->player_id, $current_squad);

// Fetch player prices for the current squad, as getSquadByTeamId doesn't fetch it
foreach ($current_squad as $player) {
    $player_details = $playerModel->getPlayersForFantasySelection($selected_league_id, $player->player_id);
    $player->fantasy_price = $player_details[0]->fantasy_price ?? 0;
}

?>

<div class="page-content" id="transfers-page" data-bank="<?php echo $user_fantasy_team->bank; ?>" data-free-transfers="<?php echo $user_fantasy_team->free_transfers ?? 1; ?>" data-league-id="<?php echo $selected_league_id; ?>">
    <div class="transfers-header">
        <h1>Transfers</h1>
        <div class="transfers-info-bar">
            <div class="info-item">
                <span class="info-label">Free Transfers</span>
                <span class="info-value" id="free-transfers-count"><?php echo $user_fantasy_team->free_transfers ?? 1; ?></span>
            </div>
            <div class="info-item">
                <span class="info-label">Points Cost</span>
                <span class="info-value" id="points-cost">0</span>
            </div>
            <div class="info-item">
                <span class="info-label">Bank</span>
                <span class="info-value" id="money-remaining">$<?php echo number_format($user_fantasy_team->bank, 1); ?>m</span>
            </div>
        </div>
    </div>

    <div class="transfers-container">
        <!-- My Team Panel -->
        <div class="transfers-panel my-team-panel">
            <h3>My Team</h3>
            <div class="table-wrapper">
                <table class="styled-table transfers-table" id="my-team-table">
                    <thead><tr><th>Player</th><th>Pos</th><th>Price</th><th></th></tr></thead>
                    <tbody>
                        <?php foreach ($current_squad as $player): ?>
                            <tr data-player-id="<?php echo $player->player_id; ?>" data-position="<?php echo $player->position; ?>" data-price="<?php echo $player->fantasy_price; ?>">
                                <td>
                                    <div class="player-name-col"><?php echo htmlspecialchars($player->last_name); ?></div>
                                    <small><?php echo htmlspecialchars($player->club_name); ?></small>
                                </td>
                                <td><?php echo htmlspecialchars(strtoupper(substr($player->position, 0, 3))); ?></td>
                                <td>$<?php echo number_format($player->fantasy_price, 1); ?>m</td>
                                <td><button class="btn-sm btn-remove" <?php echo $deadline_passed ? 'disabled' : ''; ?>>Remove</button></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Player List Panel -->
        <div class="transfers-panel player-list-panel">
            <div class="player-list-header">
                <div class="player-filters sub-tabs">
                    <a href="#" class="sub-tab-link active" data-position="All">All</a>
                    <a href="#" class="sub-tab-link" data-position="Goalkeeper">GK</a>
                    <a href="#" class="sub-tab-link" data-position="Defender">DEF</a>
                    <a href="#" class="sub-tab-link" data-position="Midfielder">MID</a>
                    <a href="#" class="sub-tab-link" data-position="Forward">FWD</a>
                </div>
                <input type="text" id="player-search-input" placeholder="Search player..." class="player-search-input">
            </div>
            <div class="table-wrapper">
                <table class="styled-table transfers-table" id="player-list-table">
                    <thead><tr><th>Player</th><th>Team</th><th>Price</th><th></th></tr></thead>
                    <tbody>
                        <?php foreach ($all_players as $player): ?>
                            <tr data-player-id="<?php echo $player->id; ?>" data-position="<?php echo $player->position; ?>" data-price="<?php echo $player->fantasy_price; ?>" <?php echo in_array($player->id, $current_squad_ids) ? 'class="in-squad"' : ''; ?>>
                                <td><?php echo htmlspecialchars($player->first_name . ' ' . $player->last_name); ?></td>
                                <td><?php echo htmlspecialchars($player->club_short_name); ?></td>
                                <td>$<?php echo number_format($player->fantasy_price, 1); ?>m</td>
                                <td>
                                    <?php if (in_array($player->id, $current_squad_ids)): ?>
                                        <button class="btn-sm btn-add" disabled>In Squad</button>
                                    <?php else: ?>
                                        <button class="btn-sm btn-add" <?php echo $deadline_passed ? 'disabled' : ''; ?>>Add</button>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="transfers-footer-bar">
        <button id="reset-transfers-btn" class="btn btn-secondary" <?php echo $deadline_passed ? 'disabled' : ''; ?>>Reset</button>
        <button id="confirm-transfers-btn" class="btn" disabled <?php echo $deadline_passed ? 'disabled' : ''; ?>>Make Transfers</button>
    </div>

</div>

<!-- Confirmation Modal -->
<div id="confirmation-modal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>Confirm Transfers</h3>
            <button class="modal-close-btn">&times;</button>
        </div>
        <div class="modal-body">
            <p>Are you sure you want to make these transfers?</p>
            <div id="confirmation-summary"></div>
            <p class="warning-text">This action cannot be undone. Points will be deducted if applicable.</p>
            <div class="modal-actions">
                <button type="button" class="btn btn-secondary modal-close-btn-action">Cancel</button>
                <button type="button" id="final-confirm-btn" class="btn">Confirm Transfers</button>
            </div>
        </div>
    </div>
</div>

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

<script>
document.addEventListener('DOMContentLoaded', function() {
    const transfersPage = document.getElementById('transfers-page');
    if(!transfersPage) return;

    const initialBank = parseFloat(transfersPage.dataset.bank);
    const freeTransfers = parseInt(transfersPage.dataset.freeTransfers);
    const leagueId = parseInt(transfersPage.dataset.leagueId);

    const myTeamTable = document.getElementById('my-team-table').querySelector('tbody');
    const playerListTable = document.getElementById('player-list-table').querySelector('tbody');
    const confirmBtn = document.getElementById('confirm-transfers-btn');
    const resetBtn = document.getElementById('reset-transfers-btn');
    const confirmationModal = document.getElementById('confirmation-modal');
    const finalConfirmBtn = document.getElementById('final-confirm-btn');
    const toastContainer = document.getElementById('toast-container');

    let bank = initialBank;
    let pendingTransfers = []; // { out: {id, price, row}, in: {id, price, row} }
    let playerToRemove = null; // {id, price, position, row}

    function updateDisplay() {
        document.getElementById('money-remaining').textContent = `$${bank.toFixed(1)}m`;
        const transfersMade = pendingTransfers.length;
        const pointsCost = Math.max(0, transfersMade - freeTransfers) * 4;
        document.getElementById('points-cost').textContent = `${pointsCost}`;
        
        confirmBtn.disabled = transfersMade === 0;
    }

    function showToast(message, type = 'success') {
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`;
        toast.textContent = message;
        toastContainer.appendChild(toast);
        setTimeout(() => {
            toast.classList.add('hide');
            toast.addEventListener('transitionend', () => toast.remove());
        }, 3000);
    }

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

    function handleRemovePlayer(e) {
        if (!e.target.matches('.btn-remove')) return;

        // If another player is already selected for removal, deselect it first
        if (playerToRemove) {
            playerToRemove.row.classList.remove('selected-for-transfer');
            playerListTable.querySelectorAll('.btn-add:not([disabled])').forEach(btn => btn.disabled = true);
        }

        const row = e.target.closest('tr');
        playerToRemove = {
            id: parseInt(row.dataset.playerId),
            price: parseFloat(row.dataset.price),
            position: row.dataset.position,
            row: row
        };

        row.classList.add('selected-for-transfer');
        // Enable add buttons on the other table that are not already in the squad
        playerListTable.querySelectorAll('tr:not(.in-squad) .btn-add').forEach(btn => {
            btn.disabled = false;
        });
    }

    function handleAddPlayer(e) {
        if (!e.target.matches('.btn-add') || e.target.disabled) return;

        if (!playerToRemove) {
            alert('Please select a player from your team to remove first.');
            return;
        }

        const row = e.target.closest('tr');
        const playerIn = {
            id: parseInt(row.dataset.playerId),
            price: parseFloat(row.dataset.price),
            position: row.dataset.position,
            row: row
        };

        // --- Validation ---
        if (playerIn.position !== playerToRemove.position) {
            alert('You can only replace a player with another player of the same position.');
            return;
        }

        const newBankBalance = bank + playerToRemove.price - playerIn.price;
        if (newBankBalance < 0) {
            alert('You do not have enough money in the bank for this transfer.');
            return;
        }

        // --- Process the transfer in the UI ---
        bank = newBankBalance;
        pendingTransfers.push({ out: playerToRemove, in: playerIn });

        // Visually swap the players
        playerToRemove.row.classList.add('transferred-out');
        playerIn.row.classList.add('in-squad'); // Mark as in squad to hide it

        // Deselect the removed player
        playerToRemove.row.classList.remove('selected-for-transfer');
        playerToRemove = null;

        // Disable all add buttons again until a new player is removed
        playerListTable.querySelectorAll('.btn-add:not([disabled])').forEach(btn => btn.disabled = true);

        updateDisplay();
        applyFilters(); // Re-apply filters to hide the newly added player
    }

    function handleFilter(e) {
        e.preventDefault();
        if (!e.target.matches('.sub-tab-link')) return;

        document.querySelector('.player-filters .sub-tab-link.active').classList.remove('active');
        e.target.classList.add('active');

        applyFilters();
    }

    function handleSearch() {
        applyFilters();
    }

    function applyFilters() {
        const filterPosition = document.querySelector('.player-filters .sub-tab-link.active').dataset.position;
        const searchQuery = document.getElementById('player-search-input').value.toLowerCase();
        const allRows = playerListTable.querySelectorAll('tr');

        allRows.forEach(row => {
            const positionMatch = (filterPosition === 'All' || row.dataset.position === filterPosition);
            const nameMatch = row.textContent.toLowerCase().includes(searchQuery);

            // Hide if it's already in the squad (either originally or via transfer)
            const inSquad = row.classList.contains('in-squad');

            if (positionMatch && nameMatch && !inSquad) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        });
    }

    function handleReset() {
        window.location.reload();
    }

    function handleConfirm() {
        if (pendingTransfers.length === 0) return;
        
        // Populate summary
        const summaryDiv = document.getElementById('confirmation-summary');
        let summaryHTML = '<ul style="list-style: none; padding: 0;">';
        pendingTransfers.forEach(t => {
            const playerOutName = t.out.row.querySelector('.player-name-col').textContent;
            const playerInName = t.in.row.querySelector('.player-name-col').textContent;
            summaryHTML += `<li style="margin-bottom: 5px;">🔴 <strong>OUT:</strong> ${playerOutName} <br> 🟢 <strong>IN:</strong> ${playerInName}</li>`;
        });
        summaryHTML += '</ul>';
        
        const transfersMade = pendingTransfers.length;
        const cost = Math.max(0, transfersMade - freeTransfers) * 4;
        if (cost > 0) {
            summaryHTML += `<p><strong>Points Cost:</strong> ${cost}</p>`;
        }
        summaryDiv.innerHTML = summaryHTML;

        confirmationModal.classList.add('show');
    }

    finalConfirmBtn.addEventListener('click', function() {
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = 'fantasy_transfers_process.php';
        
        // Add redirect hint so the process file knows where to send us back
        const redirectInput = document.createElement('input');
        redirectInput.type = 'hidden';
        redirectInput.name = 'redirect_to';
        redirectInput.value = 'fantasy_transfers.php';
        form.appendChild(redirectInput);

        const leagueInput = document.createElement('input');
        leagueInput.type = 'hidden';
        leagueInput.name = 'league_id';
        leagueInput.value = leagueId;
        form.appendChild(leagueInput);
        
        pendingTransfers.forEach((transfer, index) => {
            const outInput = document.createElement('input');
            outInput.type = 'hidden';
            outInput.name = `transfers[${index}][out]`;
            outInput.value = transfer.out.id;
            form.appendChild(outInput);

            const inInput = document.createElement('input');
            inInput.type = 'hidden';
            inInput.name = `transfers[${index}][in]`;
            inInput.value = transfer.in.id;
            form.appendChild(inInput);
        });

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

    // Close modal logic
    confirmationModal.querySelectorAll('.modal-close-btn, .modal-close-btn-action').forEach(btn => {
        btn.addEventListener('click', () => confirmationModal.classList.remove('show'));
    });
    window.addEventListener('click', (e) => {
        if (e.target === confirmationModal) confirmationModal.classList.remove('show');
    });

    // --- Event Listeners ---
    myTeamTable.addEventListener('click', handleRemovePlayer);
    playerListTable.addEventListener('click', handleAddPlayer);
    document.querySelector('.player-filters').addEventListener('click', handleFilter);
    document.getElementById('player-search-input').addEventListener('keyup', handleSearch);
    resetBtn.addEventListener('click', handleReset);
    confirmBtn.addEventListener('click', handleConfirm);

    // --- Initial State ---
    playerListTable.querySelectorAll('.btn-add:not([disabled])').forEach(btn => btn.disabled = true);
    applyFilters(); // Run once on load to hide players already in squad
    updateDisplay();
});
</script>

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