<?php 
include 'includes/header.php';

// Check if user is logged in
if(!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

// Get current game week
$stmt = $pdo->query("SELECT * FROM voting_periods WHERE is_active = TRUE LIMIT 1");
$currentGameWeek = $stmt->fetch(PDO::FETCH_ASSOC);

if(!$currentGameWeek) {
    echo "<div class='container'><div class='alert error'>No active voting period at the moment.</div></div>";
    include 'includes/footer.php';
    exit;
}

// Users can now vote as many times as they want!
?>

<!-- Countdown Timer -->
<?php if($currentGameWeek): ?>
<div class="countdown-timer">
    <h3>Voting Closes In:</h3>
    <div id="countdown" class="countdown-display">
        <div class="countdown-item">
            <span id="days">00</span>
            <small>Days</small>
        </div>
        <div class="countdown-item">
            <span id="hours">00</span>
            <small>Hours</small>
        </div>
        <div class="countdown-item">
            <span id="minutes">00</span>
            <small>Minutes</small>
        </div>
        <div class="countdown-item">
            <span id="seconds">00</span>
            <small>Seconds</small>
        </div>
    </div>
</div>

<style>
.countdown-timer {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 2rem;
    border-radius: 15px;
    text-align: center;
    margin: 2rem 0;
    box-shadow: 0 10px 30px rgba(0,0,0,0.2);
}

.countdown-timer h3 {
    margin-bottom: 1.5rem;
    font-size: 1.5rem;
    font-weight: 600;
}

.countdown-display {
    display: flex;
    justify-content: center;
    gap: 2rem;
    flex-wrap: wrap;
}

.countdown-item {
    background: rgba(255, 255, 255, 0.2);
    padding: 1.5rem 1rem;
    border-radius: 10px;
    min-width: 100px;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.3);
}

.countdown-item span {
    display: block;
    font-size: 2.5rem;
    font-weight: bold;
    margin-bottom: 0.5rem;
    text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
}

.countdown-item small {
    font-size: 0.9rem;
    opacity: 0.9;
    text-transform: uppercase;
    letter-spacing: 1px;
}

.countdown-timer.urgent {
    background: linear-gradient(135deg, #ff6b6b, #ee5a52);
    animation: pulse 2s infinite;
}

@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.02); }
    100% { transform: scale(1); }
}

@media (max-width: 768px) {
    .countdown-display {
        gap: 1rem;
    }
    
    .countdown-item {
        min-width: 80px;
        padding: 1rem 0.5rem;
    }
    
    .countdown-item span {
        font-size: 2rem;
    }
}
</style>

<script>
// Countdown Timer
function updateCountdown() {
    const endDate = new Date('<?php echo $currentGameWeek['end_date']; ?>').getTime();
    const now = new Date().getTime();
    const distance = endDate - now;
    
    if (distance < 0) {
        document.getElementById('countdown').innerHTML = '<div style="font-size: 1.5rem; font-weight: bold;">Voting Period Ended</div>';
        document.querySelector('.countdown-timer').classList.add('urgent');
        return;
    }
    
    const days = Math.floor(distance / (1000 * 60 * 60 * 24));
    const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((distance % (1000 * 60)) / 1000);
    
    document.getElementById('days').textContent = days.toString().padStart(2, '0');
    document.getElementById('hours').textContent = hours.toString().padStart(2, '0');
    document.getElementById('minutes').textContent = minutes.toString().padStart(2, '0');
    document.getElementById('seconds').textContent = seconds.toString().padStart(2, '0');
    
    // Add urgent class when less than 24 hours remaining
    if (distance < (24 * 60 * 60 * 1000)) {
        document.querySelector('.countdown-timer').classList.add('urgent');
    }
}

// Update countdown every second
setInterval(updateCountdown, 1000);
updateCountdown(); // Initial call
</script>
<?php endif; ?>

<div class="container">
    <h1>Vote for Game Week <?php echo $currentGameWeek['game_week']; ?></h1>
    <p class="subtitle">Select your team of 11 players and 1 coach</p>
    <div class="requirements">
        <strong>Vote as many times as you want!</strong> All your votes will be counted towards the leaderboard.<br>
        Requirements: 1 Goalkeeper, 3-5 Defenders, 3-5 Midfielders, 1-4 Forwards, 1 Coach (Total: 11 players + 1 coach)
    </div>

    <?php if(isset($_SESSION['success'])): ?>
        <div class="alert success">
            <?php echo $_SESSION['success']; ?>
            <div style="margin-top: 10px;">
                <a href="vote.php" class="btn btn-secondary">
                    <i class="fas fa-vote-yea"></i> Vote Again
                </a>
                <a href="leaderboard.php" class="btn btn-primary">
                    <i class="fas fa-trophy"></i> View Leaderboard
                </a>
            </div>
        </div>
        <?php unset($_SESSION['success']); ?>
    <?php endif; ?>

    <?php if(isset($_SESSION['error'])): ?>
        <div class="alert error">
            <?php echo $_SESSION['error']; ?>
        </div>
        <?php unset($_SESSION['error']); ?>
    <?php endif; ?>

    <form id="voteForm" method="POST" action="process-vote.php">
        <input type="hidden" name="game_week" value="<?php echo $currentGameWeek['game_week']; ?>">

        <!-- Goalkeepers Section -->
        <section class="voting-section">
            <h2>Goalkeepers <small>(Select 1)</small></h2>
            <div class="players-grid" id="goalkeepers-grid">
                <?php
                $stmt = $pdo->prepare("SELECT p.*, pos.name as position FROM players p 
                                    JOIN positions pos ON p.position_id = pos.id 
                                    WHERE pos.code = 'GK' AND p.game_week = ? AND p.is_active = TRUE 
                                    LIMIT 3");
                $stmt->execute([$currentGameWeek['game_week']]);
                $goalkeepers = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                if(empty($goalkeepers)) {
                    echo "<p>No goalkeepers available for this game week.</p>";
                } else {
                    foreach($goalkeepers as $gk): ?>
                    <div class="player-card" data-position="gk">
                        <input type="radio" name="goalkeeper" value="<?php echo $gk['id']; ?>" class="position-gk">
                        <img src="<?php echo $gk['photo'] ?: 'assets/default-player.jpg'; ?>" alt="<?php echo $gk['name']; ?>">
                        <h4><?php echo $gk['name']; ?></h4>
                        <p><?php echo $gk['team']; ?></p>
                    </div>
                    <?php endforeach;
                } ?>
            </div>
            <div id="gk-count" class="selection-count">Selected: 0/1</div>
        </section>

        <!-- Defenders Section -->
        <section class="voting-section">
            <h2>Defenders <small>(Select 3-5)</small></h2>
            <div class="players-grid" id="defenders-grid">
                <?php
                $stmt = $pdo->prepare("SELECT p.*, pos.name as position FROM players p 
                                    JOIN positions pos ON p.position_id = pos.id 
                                    WHERE pos.code = 'DEF' AND p.game_week = ? AND p.is_active = TRUE 
                                    LIMIT 5");
                $stmt->execute([$currentGameWeek['game_week']]);
                $defenders = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                if(empty($defenders)) {
                    echo "<p>No defenders available for this game week.</p>";
                } else {
                    foreach($defenders as $def): ?>
                    <div class="player-card" data-position="def">
                        <input type="checkbox" name="defenders[]" value="<?php echo $def['id']; ?>" class="position-def">
                        <img src="<?php echo $def['photo'] ?: 'assets/default-player.jpg'; ?>" alt="<?php echo $def['name']; ?>">
                        <h4><?php echo $def['name']; ?></h4>
                        <p><?php echo $def['team']; ?></p>
                    </div>
                    <?php endforeach;
                } ?>
            </div>
            <div id="def-count" class="selection-count">Selected: 0/3</div>
        </section>

        <!-- Midfielders Section -->
        <section class="voting-section">
            <h2>Midfielders <small>(Select 3-5)</small></h2>
            <div class="players-grid" id="midfielders-grid">
                <?php
                $stmt = $pdo->prepare("SELECT p.*, pos.name as position FROM players p 
                                    JOIN positions pos ON p.position_id = pos.id 
                                    WHERE pos.code = 'MID' AND p.game_week = ? AND p.is_active = TRUE 
                                    LIMIT 5");
                $stmt->execute([$currentGameWeek['game_week']]);
                $midfielders = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                if(empty($midfielders)) {
                    echo "<p>No midfielders available for this game week.</p>";
                } else {
                    foreach($midfielders as $mid): ?>
                    <div class="player-card" data-position="mid">
                        <input type="checkbox" name="midfielders[]" value="<?php echo $mid['id']; ?>" class="position-mid">
                        <img src="<?php echo $mid['photo'] ?: 'assets/default-player.jpg'; ?>" alt="<?php echo $mid['name']; ?>">
                        <h4><?php echo $mid['name']; ?></h4>
                        <p><?php echo $mid['team']; ?></p>
                    </div>
                    <?php endforeach;
                } ?>
            </div>
            <div id="mid-count" class="selection-count">Selected: 0/3</div>
        </section>

        <!-- Forwards Section -->
        <section class="voting-section">
            <h2>Forwards <small>(Select 1-4)</small></h2>
            <div class="players-grid" id="forwards-grid">
                <?php
                $stmt = $pdo->prepare("SELECT p.*, pos.name as position FROM players p 
                                    JOIN positions pos ON p.position_id = pos.id 
                                    WHERE pos.code = 'FWD' AND p.game_week = ? AND p.is_active = TRUE 
                                    LIMIT 4");
                $stmt->execute([$currentGameWeek['game_week']]);
                $forwards = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                if(empty($forwards)) {
                    echo "<p>No forwards available for this game week.</p>";
                } else {
                    foreach($forwards as $fwd): ?>
                    <div class="player-card" data-position="fwd">
                        <input type="checkbox" name="forwards[]" value="<?php echo $fwd['id']; ?>" class="position-fwd">
                        <img src="<?php echo $fwd['photo'] ?: 'assets/default-player.jpg'; ?>" alt="<?php echo $fwd['name']; ?>">
                        <h4><?php echo $fwd['name']; ?></h4>
                        <p><?php echo $fwd['team']; ?></p>
                    </div>
                    <?php endforeach;
                } ?>
            </div>
            <div id="fwd-count" class="selection-count">Selected: 0/1</div>
        </section>

        <!-- Coaches Section -->
        <section class="voting-section">
            <h2>Coaches <small>(Select 1)</small></h2>
            <div class="players-grid" id="coaches-grid">
                <?php
                $stmt = $pdo->prepare("SELECT * FROM coaches WHERE game_week = ? AND is_active = TRUE LIMIT 3");
                $stmt->execute([$currentGameWeek['game_week']]);
                $coaches = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                if(empty($coaches)) {
                    echo "<p>No coaches available for this game week.</p>";
                } else {
                    foreach($coaches as $coach): ?>
                    <div class="player-card" data-position="coach">
                        <input type="radio" name="coach" value="<?php echo $coach['id']; ?>" class="position-coach">
                        <img src="<?php echo $coach['photo'] ?: 'assets/default-coach.jpg'; ?>" alt="<?php echo $coach['name']; ?>">
                        <h4><?php echo $coach['name']; ?></h4>
                        <p><?php echo $coach['team']; ?></p>
                    </div>
                    <?php endforeach;
                } ?>
            </div>
            <div id="coach-count" class="selection-count">Selected: 0/1</div>
        </section>

        <div class="total-selection">
            <h3>Total Selected: <span id="total-count">0</span>/11 players + <span id="coach-total">0</span>/1 coach</h3>
            <div class="validation-message" id="validation-message"></div>
            <button type="submit" class="btn btn-primary" id="submit-btn" disabled>Submit Vote</button>
        </div>
    </form>
</div>

<script src="js/vote-validation.js"></script>

<!-- ADD THIS RIGHT AFTER THE SCRIPT TAG -->
<script>
console.log('Checking if vote-validation.js loaded...');

// Test if the file loaded
function checkScriptLoaded() {
    // Test if our simple functions exist
    const tests = {
        'updateAllCounts': typeof updateAllCounts,
        'setupEventListeners': typeof setupEventListeners,
        'debugVoting': typeof debugVoting
    };
    
    console.log('Script functions check:', tests);
    
    // If scripts didn't load, load our inline version
    if (typeof updateAllCounts === 'undefined') {
        console.log('vote-validation.js not loaded properly, using inline fallback');
        loadInlineFallback();
    } else {
        console.log('vote-validation.js loaded successfully');
        // Initialize the simple version
        document.addEventListener('DOMContentLoaded', function() {
            setupEventListeners();
            updateAllCounts();
        });
    }
}

// Inline fallback that DEFINITELY works
function loadInlineFallback() {
    console.log('Loading guaranteed inline validation...');
    
    // Global selections object
    window.selections = {
        gk: 0,
        def: 0,
        mid: 0,
        fwd: 0,
        coach: 0
    };
    
    // Initialize when DOM is ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initVoting);
    } else {
        initVoting();
    }
    
    function initVoting() {
        console.log('Initializing guaranteed voting system...');
        setupGuaranteedEvents();
        updateGuaranteedCounts();
        setupGuaranteedForm();
        
        // Force check current selections immediately
        setTimeout(updateGuaranteedCounts, 100);
    }
    
    function setupGuaranteedEvents() {
        console.log('Setting up guaranteed event listeners...');
        
        // Remove any existing listeners first
        const cards = document.querySelectorAll('.player-card');
        cards.forEach(card => {
            card.replaceWith(card.cloneNode(true));
        });
        
        // Add new listeners
        document.querySelectorAll('.player-card').forEach(card => {
            card.addEventListener('click', function(e) {
                console.log('Card clicked:', this);
                const input = this.querySelector('input');
                if (input && e.target !== input) {
                    if (input.type === 'checkbox') {
                        input.checked = !input.checked;
                        console.log('Checkbox toggled:', input.checked);
                    } else if (input.type === 'radio') {
                        input.checked = true;
                        console.log('Radio selected');
                    }
                    // Force change event
                    input.dispatchEvent(new Event('change', { bubbles: true }));
                }
                updateGuaranteedCounts();
            });
        });
        
        // Also listen to input changes directly
        document.querySelectorAll('.player-card input').forEach(input => {
            input.addEventListener('change', function() {
                console.log('Input changed:', this.name, this.checked);
                updateGuaranteedCounts();
            });
        });
        
        console.log('Event listeners setup complete');
    }
    
    function updateGuaranteedCounts() {
        console.log('Updating guaranteed counts...');
        
        // Count ALL checked inputs
        const allChecked = document.querySelectorAll('.player-card input:checked');
        console.log('Total checked inputs:', allChecked.length);
        
        // Count by position
        selections.gk = document.querySelectorAll('input[name="goalkeeper"]:checked').length;
        selections.def = document.querySelectorAll('input[name="defenders[]"]:checked').length;
        selections.mid = document.querySelectorAll('input[name="midfielders[]"]:checked').length;
        selections.fwd = document.querySelectorAll('input[name="forwards[]"]:checked').length;
        selections.coach = document.querySelectorAll('input[name="coach"]:checked').length;
        
        const totalPlayers = selections.gk + selections.def + selections.mid + selections.fwd;
        
        console.log('GUARANTEED COUNTS - GK:', selections.gk, 'DEF:', selections.def, 'MID:', selections.mid, 'FWD:', selections.fwd, 'Coach:', selections.coach, 'Total:', totalPlayers);
        
        // Update display
        document.getElementById('gk-count').textContent = `Selected: ${selections.gk}/1`;
        document.getElementById('def-count').textContent = `Selected: ${selections.def}/3`;
        document.getElementById('mid-count').textContent = `Selected: ${selections.mid}/3`;
        document.getElementById('fwd-count').textContent = `Selected: ${selections.fwd}/1`;
        document.getElementById('coach-count').textContent = `Selected: ${selections.coach}/1`;
        
        if (document.getElementById('total-count')) {
            document.getElementById('total-count').textContent = totalPlayers;
        }
        if (document.getElementById('coach-total')) {
            document.getElementById('coach-total').textContent = selections.coach;
        }
        
        // Update button state
        updateGuaranteedButton(totalPlayers);
    }
    
    function updateGuaranteedButton(totalPlayers) {
        const submitBtn = document.getElementById('submit-btn');
        if (!submitBtn) {
            console.error('Submit button not found!');
            return;
        }
        
        const isValid = selections.gk === 1 && 
                       selections.def >= 3 && selections.def <= 5 &&
                       selections.mid >= 3 && selections.mid <= 5 &&
                       selections.fwd >= 1 && selections.fwd <= 4 &&
                       selections.coach === 1 &&
                       totalPlayers === 11;
        
        console.log('Button validation - Valid:', isValid, 'Total:', totalPlayers);
        
        if (isValid) {
            submitBtn.disabled = false;
            submitBtn.style.background = '#27ae60';
            submitBtn.style.cursor = 'pointer';
        } else {
            submitBtn.disabled = true;
            submitBtn.style.background = '#bdc3c7';
            submitBtn.style.cursor = 'not-allowed';
        }
    }
    
    function setupGuaranteedForm() {
        const form = document.getElementById('voteForm');
        if (form) {
            form.addEventListener('submit', function(e) {
                console.log('Form submission intercepted');
                updateGuaranteedCounts(); // Final count update
                
                const totalPlayers = selections.gk + selections.def + selections.mid + selections.fwd;
                const isValid = selections.gk === 1 && selections.def >= 3 && selections.mid >= 3 && 
                              selections.fwd >= 1 && selections.coach === 1 && totalPlayers === 11;
                
                if (!isValid) {
                    e.preventDefault();
                    alert('Please select exactly 11 players and 1 coach before submitting.');
                    return false;
                }
                
                // Show loading
                const submitBtn = document.getElementById('submit-btn');
                if (submitBtn) {
                    submitBtn.disabled = true;
                    submitBtn.innerHTML = 'Submitting... <i class="fas fa-spinner fa-spin"></i>';
                }
                
                return true;
            });
        }
    }
}

// Check immediately
checkScriptLoaded();
</script>

<style>
.requirements {
    background: linear-gradient(135deg, var(--light-blue), #dbeafe);
    padding: 1.2rem;
    border-radius: 10px;
    border-left: 5px solid var(--primary-blue);
    margin-bottom: 2rem;
    font-size: 1rem;
    box-shadow: 0 3px 10px rgba(26, 115, 232, 0.1);
}

.validation-message {
    margin: 1rem 0;
    padding: 1rem;
    border-radius: 8px;
    font-weight: bold;
    transition: all 0.3s ease;
}

.validation-message.valid {
    background: #d4edda;
    color: #155724;
    border: 2px solid #c3e6cb;
}

.validation-message.invalid {
    background: #f8d7da;
    color: #721c24;
    border: 2px solid #f5c6cb;
}

.player-card {
    cursor: pointer;
    transition: all 0.3s ease;
}

.player-card.selected {
    border-color: #27ae60 !important;
    background: linear-gradient(135deg, #f8fff8, #e8f6f3) !important;
    transform: translateY(-3px);
    box-shadow: 0 5px 20px rgba(39, 174, 96, 0.3) !important;
}

.selection-count {
    font-weight: bold;
    margin-top: 1rem;
    padding: 0.8rem;
    background: #f8f9fa;
    border-radius: 8px;
    border-left: 4px solid #3498db;
    font-size: 1.1em;
    transition: all 0.3s ease;
}

#submit-btn:disabled {
    background: #bdc3c7 !important;
    cursor: not-allowed !important;
    opacity: 0.7;
    transform: none !important;
}

#submit-btn:not(:disabled):hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(39, 174, 96, 0.4);
}
</style>

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