<?php
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

// Get available disciplines with result counts
$disciplines_with_counts = [];
$current_year = date('Y');

try {
    $stmt = $pdo->prepare("
        SELECT 
            r.discipline,
            COUNT(DISTINCT r.userId) as athlete_count,
            COUNT(r.id) as result_count
        FROM results r
        JOIN competitions c ON r.competitionId = c.id
        WHERE strftime('%Y', c.date) = ?
        GROUP BY r.discipline
        ORDER BY result_count DESC
    ");
    $stmt->execute([$current_year]);
    $disciplines_with_counts = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    error_log('Discipline counts error: ' . $e->getMessage());
    $disciplines_with_counts = [];
}

// Determine default discipline based on result counts
$default_discipline = 'koolisoit'; // Default fallback
if (!empty($disciplines_with_counts)) {
    // Use discipline with most results as default
    $default_discipline = $disciplines_with_counts[0]['discipline'];
}

// Filters
$discipline = getGet('discipline', $default_discipline);
$age_group = getGet('ageGroup', 'all');
$year = getGet('year', date('Y'));

// Validate input
$valid_disciplines = ['koolisoit', 'takistussoit', 'kestvusratsutamine'];
$valid_age_groups = ['all', 'noored', 'täiskasvanud'];

if (!in_array($discipline, $valid_disciplines)) {
    $discipline = $default_discipline;
}
if (!in_array($age_group, $valid_age_groups)) {
    $age_group = 'all';
}

$error = '';
$rankings = [];

try {
    // Load athletes and their results
    $sql = "
        SELECT 
            u.id, u.firstName, u.lastName, u.birthDate,
            r.points, r.finished, r.createdAt as resultDate,
            c.name as competitionName, c.date as competitionDate
        FROM users u
        LEFT JOIN results r ON u.id = r.userId AND r.discipline = ?
        LEFT JOIN competitions c ON r.competitionId = c.id
        WHERE u.isActive = 1 AND u.role = 'athlete'
            AND (r.id IS NULL OR strftime('%Y', c.date) = ?)
        ORDER BY u.lastName, u.firstName, c.date DESC
    ";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$discipline, $year]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Group by athlete
    $athletes = [];
    foreach ($rows as $row) {
        if (!isset($athletes[$row['id']])) {
            $athletes[$row['id']] = [
                'id' => $row['id'],
                'firstName' => $row['firstName'],
                'lastName' => $row['lastName'],
                'birthDate' => $row['birthDate'],
                'ageGroup' => getAgeGroup($row['birthDate'], $year),
                'results' => []
            ];
        }
        if ($row['points'] !== null) {
            $athletes[$row['id']]['results'][] = [
                'points' => (float)$row['points'],
                'finished' => $row['finished'],
                'competitionName' => $row['competitionName'],
                'competitionDate' => $row['competitionDate']
            ];
        }
    }
    
    // Calculate season standings for each athlete - FIXED: avoid references
    $athlete_keys = array_keys($athletes);
    for ($i = 0; $i < count($athlete_keys); $i++) {
        $key = $athlete_keys[$i];
        $season_data = calculateSeasonStandings($athletes[$key]['results'], $discipline);
        $athletes[$key] = array_merge($athletes[$key], $season_data);
    }
    
    // Filter by age group
    if ($age_group !== 'all') {
        $athletes = array_filter($athletes, function($athlete) use ($age_group) {
            return $athlete['ageGroup'] === $age_group;
        });
    }
    
    // IMPORTANT CHANGE: Filter out athletes with no results
    $athletes = array_filter($athletes, function($athlete) {
        return !empty($athlete['results']);
    });
    
    // Sort by points
    usort($athletes, function($a, $b) {
        return $b['total_points'] <=> $a['total_points'];
    });
    
    // Add positions - FIXED: avoid references
    $athletes = array_values($athletes); // Re-index array after filtering
    for ($i = 0; $i < count($athletes); $i++) {
        $athletes[$i]['position'] = $i + 1;
    }
    
    $rankings = $athletes;
    
    // If no results found for current discipline, check if we need to redirect to a discipline with results
    if (empty($rankings) && !isset($_GET['no_redirect'])) {
        // Find first discipline with results
        foreach ($disciplines_with_counts as $disc_data) {
            if ($disc_data['athlete_count'] > 0 && $disc_data['discipline'] != $discipline) {
                // Redirect to that discipline
                header('Location: ' . url('public/rankings.php?discipline=' . $disc_data['discipline'] . 
                                        '&ageGroup=' . $age_group . 
                                        '&year=' . $year . 
                                        '&no_redirect=1'));
                exit;
            }
        }
    }
    
} catch(PDOException $e) {
    $error = 'Tabelite laadimine ebaõnnestus: ' . $e->getMessage();
    error_log('Rankings error: ' . $e->getMessage());
}

$page_title = getDisciplineName($discipline) . ' - Hooaja tabelid';
$page_description = 'Vaata ' . getDisciplineName($discipline) . ' hooaja ' . $year . ' tabeleid. Jälgi sportlaste positsioone ja punkte.';

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

<main class="rankings-main">
    <div class="container">
        <!-- Header -->
        <div class="page-header">
            <div class="page-header-content">
                <h1 class="page-title">Hooaja järjestused</h1>
                <p class="page-subtitle">
                    <?php echo getDisciplineName($discipline); ?> - <?php echo $year; ?>. aasta
                    <?php if ($age_group !== 'all'): ?>
                        (<?php echo getAgeGroupName($age_group); ?>)
                    <?php endif; ?>
                </p>
            </div>
            <div class="page-actions">
                <button onclick="exportToPDF()" class="btn btn-secondary">
                    <i class="icon-download"></i>
                    <span>Ekspordi PDF</span>
                </button>
            </div>
        </div>

        <!-- Filters -->
        <div class="filters-section">
            <form method="GET" class="filters-form">
                <input type="hidden" name="no_redirect" value="1">
                <div class="filters-grid">
                    <div class="filter-group">
                        <label for="discipline" class="filter-label">Distsipliin</label>
                        <select name="discipline" id="discipline" class="filter-select">
                            <?php foreach ($valid_disciplines as $disc): ?>
                                <?php 
                                // Get result count for this discipline
                                $disc_count = 0;
                                foreach ($disciplines_with_counts as $dc) {
                                    if ($dc['discipline'] === $disc) {
                                        $disc_count = $dc['result_count'];
                                        break;
                                    }
                                }
                                ?>
                                <option value="<?php echo $disc; ?>" <?php echo $discipline === $disc ? 'selected' : ''; ?>>
                                    <?php echo getDisciplineName($disc); ?> 
                                    <?php if ($disc_count > 0): ?>
                                        (<?php echo $disc_count; ?>)
                                    <?php endif; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="filter-group">
                        <label for="ageGroup" class="filter-label">Vanusegrupp</label>
                        <select name="ageGroup" id="ageGroup" class="filter-select">
                            <?php foreach ($valid_age_groups as $group): ?>
                                <option value="<?php echo $group; ?>" <?php echo $age_group === $group ? 'selected' : ''; ?>>
                                    <?php echo getAgeGroupName($group); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="filter-group">
                        <label for="year" class="filter-label">Aasta</label>
                        <select name="year" id="year" class="filter-select">
                            <?php for ($y = date('Y'); $y >= date('Y') - 4; $y--): ?>
                                <option value="<?php echo $y; ?>" <?php echo $year == $y ? 'selected' : ''; ?>>
                                    <?php echo $y; ?>
                                </option>
                            <?php endfor; ?>
                        </select>
                    </div>

                    <div class="filter-group">
                        <label class="filter-label">&nbsp;</label>
                        <button type="submit" class="btn btn-primary">
                            <i class="icon-filter"></i>
                            <span>Filtreeri</span>
                        </button>
                    </div>
                </div>
            </form>
        </div>

        <!-- Tables -->
        <?php if ($error): ?>
            <div class="alert alert-error">
                <i class="icon-alert-circle"></i>
                <span><?php echo htmlspecialchars($error); ?></span>
            </div>
        <?php elseif (empty($rankings)): ?>
            <div class="empty-state">
                <div class="empty-icon">
                    <i class="icon-trophy"></i>
                </div>
                <h3>Tulemusi ei leitud</h3>
                <p>Valitud kriteeriumide järgi ei leitud ühtegi tulemust.</p>
                <?php if (!empty($disciplines_with_counts)): ?>
                    <p class="suggestion-text">Tulemusi on olemas järgnevates distsipliinides:</p>
                    <div class="suggestion-buttons">
                        <?php foreach ($disciplines_with_counts as $disc_data): ?>
                            <?php if ($disc_data['athlete_count'] > 0): ?>
                                <a href="?discipline=<?php echo $disc_data['discipline']; ?>&ageGroup=<?php echo $age_group; ?>&year=<?php echo $year; ?>&no_redirect=1" class="btn btn-outline">
                                    <i class="icon-award"></i>
                                    <?php echo getDisciplineName($disc_data['discipline']); ?> (<?php echo $disc_data['result_count']; ?>)
                                </a>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <a href="?discipline=koolisoit&ageGroup=all&year=<?php echo date('Y'); ?>" class="btn btn-primary">
                        <i class="icon-refresh-cw"></i>
                        <span>Lähtesta filtrid</span>
                    </a>
                <?php endif; ?>
            </div>
        <?php else: ?>
            <div class="rankings-container">
                <div class="rankings-header">
                    <h2 class="rankings-title">
                        <?php echo getDisciplineName($discipline); ?> - <?php echo $year; ?>
                    </h2>
                    <div class="rankings-count">
                        <?php echo count($rankings); ?> sportlast
                    </div>
                </div>

                <div class="rankings-table-wrapper">
                    <table class="rankings-table" id="rankingsTable">
                        <thead>
                            <tr>
                                <th class="rank-col">Koht</th>
                                <th class="athlete-col">Sportlane</th>
                                <th class="points-col">Punktid</th>
                                <th class="starts-col">Starte</th>
                                <th class="counted-col">Arvestatud</th>
                                <th class="best-col">Parim</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($rankings as $athlete): ?>
                                <tr class="<?php echo $athlete['position'] <= 3 ? 'podium-place' : ''; ?> <?php echo $athlete['position'] === 1 ? 'first-place' : ''; ?>">
                                    <td class="rank-cell">
                                        <div class="rank-container">
                                            <?php if ($athlete['position'] <= 3): ?>
                                                <i class="icon-medal medal-<?php echo $athlete['position'] === 1 ? 'gold' : ($athlete['position'] === 2 ? 'silver' : 'bronze'); ?>"></i>
                                            <?php endif; ?>
                                            <span class="rank-number"><?php echo $athlete['position']; ?>.</span>
                                        </div>
                                    </td>
                                    <td class="athlete-cell">
                                        <div class="athlete-info">
                                            <div class="athlete-name">
                                                <?php echo htmlspecialchars($athlete['firstName'] . ' ' . $athlete['lastName']); ?>
                                            </div>
                                            <div class="athlete-meta">
                                                <?php echo getAgeGroupName($athlete['ageGroup']); ?>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="points-cell">
                                        <div class="points-display">
                                            <?php echo formatPoints($athlete['total_points']); ?>
                                        </div>
                                    </td>
                                    <td class="starts-cell">
                                        <?php echo $athlete['starts_count']; ?>
                                    </td>
                                    <td class="counted-cell">
                                        <div class="counted-info">
                                            <span class="counted-number"><?php echo count($athlete['counted_results']); ?></span>
                                            <span class="counted-max">/ <?php echo $athlete['max_starts']; ?></span>
                                        </div>
                                    </td>
                                    <td class="best-cell">
                                        <?php if (!empty($athlete['all_results'])): ?>
                                            <?php echo formatPoints(max(array_column($athlete['all_results'], 'points'))); ?>
                                        <?php else: ?>
                                            -
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        <?php endif; ?>

        <!-- Point calculation rules -->
        <div class="rules-section">
            <div class="rules-card">
                <div class="rules-header">
                    <i class="icon-info"></i>
                    <h3>Punktiarvestuse reeglid - <?php echo getDisciplineName($discipline); ?></h3>
                </div>
                <div class="rules-content">
                    <?php if ($discipline === 'koolisoit'): ?>
                        <div class="rule-item">
                            <strong>Arvestatakse 6 parimat tulemust</strong>
                        </div>
                        <ul class="rules-list">
                            <li>Baaspunktid: 70%+ = 12p, 68-69% = 10p, 65-67% = 8p, 62-64% = 6p, 60-61% = 5p, jne</li>
                            <li>Skeemi bonus: L-skeem +3p, A-skeem +2p, ABC-skeem +1p, NH4A-skeem +1p</li>
                            <li>Koha bonus: 1. koht +5p, 2. koht +4p, 3. koht +3p, 4. koht +2p, 5. koht +1p</li>
                            <li>Osalemispunkt: +0.5p</li>
                        </ul>
                    <?php elseif ($discipline === 'takistussoit'): ?>
                        <div class="rule-item">
                            <strong>Arvestatakse 10 parimat tulemust</strong>
                        </div>
                        <ul class="rules-list">
                            <li>0 karistuspunkti = 12p, 1-4 = 10p, 5-8 = 8p, 9-12 = 6p, 13-16 = 4p, 17-20 = 2p, 20+ = 1p</li>
                            <li>Osalemispunkt: +0.5p</li>
                        </ul>
                    <?php else: ?>
                        <div class="rule-item">
                            <strong>Arvestatakse 4 parimat tulemust</strong>
                        </div>
                        <ul class="rules-list">
                            <li>Distants: 100+km = 12p, 80-99km = 10p, 40-79km = 8p, kuni 39km = 6p</li>
                            <li>Koha bonus: 1. koht +6p, 2. koht +5p, 3. koht +4p, 4. koht +3p, 5. koht +2p</li>
                            <li>Lõpetamisbonus: +1p, Osalemispunkt: +0.5p</li>
                        </ul>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</main>

<style>
/* Rankings Page Styles - Scoped to avoid conflicts with header */
.rankings-main {
    padding: var(--spacing-8) 0;
    min-height: 100vh;
}

/* Scope all styles to be specific to the rankings page */
.rankings-main .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    margin-bottom: var(--spacing-8);
    gap: var(--spacing-4);
}

.rankings-main .page-header-content h1 {
    margin-bottom: var(--spacing-2);
}

.rankings-main .page-subtitle {
    color: var(--gray-600);
    font-size: var(--font-size-lg);
    margin: 0;
}

.rankings-main .page-actions {
    flex-shrink: 0;
}

/* Filters */
.rankings-main .filters-section {
    background: white;
    border-radius: var(--radius-lg);
    box-shadow: var(--shadow);
    padding: var(--spacing-6);
    margin-bottom: var(--spacing-8);
}

.rankings-main .filters-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: var(--spacing-4);
    align-items: end;
}

.rankings-main .filter-group {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-2);
}

.rankings-main .filter-label {
    font-weight: 500;
    color: var(--gray-700);
    font-size: var(--font-size-sm);
}

.rankings-main .filter-select {
    padding: var(--spacing-3);
    border: 1px solid var(--gray-300);
    border-radius: var(--radius);
    background: white;
    font-size: var(--font-size-sm);
    transition: border-color var(--transition-fast);
}

.rankings-main .filter-select:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px color-mix(in srgb, var(--primary-color) 10%, transparent);
}

/* Rankings Table */
.rankings-main .rankings-container {
    background: white;
    border-radius: var(--radius-lg);
    box-shadow: var(--shadow);
    overflow: hidden;
    margin-bottom: var(--spacing-8);
}

.rankings-main .rankings-header {
    padding: var(--spacing-6);
    border-bottom: 1px solid var(--gray-200);
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.rankings-main .rankings-title {
    font-size: var(--font-size-xl);
    font-weight: 600;
    margin: 0;
}

.rankings-main .rankings-count {
    color: var(--gray-500);
    font-size: var(--font-size-sm);
}

.rankings-main .rankings-table-wrapper {
    overflow-x: auto;
}

.rankings-main .rankings-table {
    width: 100%;
    border-collapse: collapse;
}

.rankings-main .rankings-table th {
    background-color: var(--gray-50);
    padding: var(--spacing-4);
    text-align: left;
    font-weight: 600;
    color: var(--gray-700);
    font-size: var(--font-size-sm);
    text-transform: uppercase;
    letter-spacing: 0.05em;
    border-bottom: 2px solid var(--gray-200);
}

.rankings-main .rankings-table td {
    padding: var(--spacing-4);
    border-bottom: 1px solid var(--gray-100);
    vertical-align: middle;
}

.rankings-main .rankings-table tr:hover {
    background-color: var(--gray-50);
}

.rankings-main .rankings-table tr.podium-place {
    background-color: color-mix(in srgb, var(--warning-color) 3%, transparent);
}

.rankings-main .rankings-table tr.first-place {
    background-color: color-mix(in srgb, var(--warning-color) 8%, transparent);
}

.rankings-main .rank-container {
    display: flex;
    align-items: center;
    gap: var(--spacing-2);
}

.rankings-main .medal-gold { color: #ffd700; }
.rankings-main .medal-silver { color: #c0c0c0; }
.rankings-main .medal-bronze { color: #cd7f32; }

.rankings-main .rank-number {
    font-weight: 600;
    font-size: var(--font-size-lg);
}

.rankings-main .athlete-info {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-1);
}

.rankings-main .athlete-name {
    font-weight: 500;
    color: var(--gray-900);
}

.rankings-main .athlete-meta {
    font-size: var(--font-size-xs);
    color: var(--gray-500);
}

.rankings-main .points-display {
    font-size: var(--font-size-xl);
    font-weight: 700;
    color: var(--primary-color);
}

.rankings-main .counted-info {
    display: flex;
    align-items: baseline;
    gap: var(--spacing-1);
}

.rankings-main .counted-number {
    font-weight: 600;
}

.rankings-main .counted-max {
    color: var(--gray-500);
    font-size: var(--font-size-sm);
}

/* Empty State */
.rankings-main .empty-state {
    text-align: center;
    padding: var(--spacing-16) var(--spacing-8);
    background: white;
    border-radius: var(--radius-lg);
    box-shadow: var(--shadow);
}

.rankings-main .empty-icon {
    width: 80px;
    height: 80px;
    margin: 0 auto var(--spacing-6);
    background-color: var(--gray-100);
    border-radius: var(--radius-full);
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--gray-400);
    font-size: 2rem;
}

.rankings-main .empty-state h3 {
    margin-bottom: var(--spacing-3);
    color: var(--gray-900);
}

.rankings-main .empty-state p {
    color: var(--gray-600);
    margin-bottom: var(--spacing-6);
}

/* Suggestion buttons */
.rankings-main .suggestion-text {
    color: var(--gray-700);
    margin-bottom: var(--spacing-3);
}

.rankings-main .suggestion-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: var(--spacing-3);
    justify-content: center;
}

/* Use a more specific selector for buttons in rankings page */
.rankings-main .btn-outline {
    background: transparent;
    border: 1px solid var(--primary-color);
    color: var(--primary-color);
}

.rankings-main .btn-outline:hover {
    background: var(--primary-color);
    color: white;
}

/* Rules Section */
.rankings-main .rules-section {
    margin-top: var(--spacing-8);
}

.rankings-main .rules-card {
    background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
    border-radius: var(--radius-lg);
    padding: var(--spacing-6);
    color: white;
}

.rankings-main .rules-header {
    display: flex;
    align-items: center;
    gap: var(--spacing-3);
    margin-bottom: var(--spacing-4);
}

.rankings-main .rules-header i {
    font-size: var(--font-size-xl);
    opacity: 0.9;
}

.rankings-main .rules-header h3 {
    margin: 0;
    font-size: var(--font-size-lg);
    font-weight: 600;
}

.rankings-main .rule-item {
    margin-bottom: var(--spacing-3);
    font-size: var(--font-size-base);
}

.rankings-main .rules-list {
    list-style: none;
    display: flex;
    flex-direction: column;
    gap: var(--spacing-2);
}

.rankings-main .rules-list li {
    position: relative;
    padding-left: var(--spacing-4);
    opacity: 0.9;
    font-size: var(--font-size-sm);
    line-height: 1.5;
}

.rankings-main .rules-list li::before {
    content: '•';
    position: absolute;
    left: 0;
    color: rgba(255, 255, 255, 0.7);
    font-weight: bold;
}

/* Responsive */
@media (max-width: 768px) {
    .rankings-main .page-header {
        flex-direction: column;
        align-items: stretch;
        gap: var(--spacing-4);
    }
    
    .rankings-main .filters-grid {
        grid-template-columns: 1fr;
    }
    
    .rankings-main .rankings-header {
        flex-direction: column;
        align-items: flex-start;
        gap: var(--spacing-2);
    }
    
    .rankings-main .rankings-table {
        font-size: var(--font-size-sm);
    }
    
    .rankings-main .rankings-table th,
    .rankings-main .rankings-table td {
        padding: var(--spacing-2) var(--spacing-3);
    }
    
    .rankings-main .suggestion-buttons {
        flex-direction: column;
        align-items: center;
    }
}

@media (max-width: 480px) {
    .rankings-main .rankings-table-wrapper {
        margin: 0 -1rem;
    }
    
    .rankings-main .athlete-col,
    .rankings-main .best-col {
        min-width: 150px;
    }
    
    .rankings-main .points-col,
    .rankings-main .starts-col,
    .rankings-main .counted-col {
        min-width: 80px;
    }
}
</style>

<script>
// Auto-submit form when filters change
document.addEventListener('DOMContentLoaded', function() {
    const filterSelects = document.querySelectorAll('.filter-select');
    filterSelects.forEach(select => {
        select.addEventListener('change', function() {
            // Small delay to improve UX
            setTimeout(() => {
                this.closest('form').submit();
            }, 100);
        });
    });
});

// Export to PDF function
function exportToPDF() {
    alert('PDF eksport tuleb peagi! Hetkel kasuta brauseri print funktsiooni.');
    window.print();
}

// Add loading states
const form = document.querySelector('.filters-form');
if (form) {
    form.addEventListener('submit', function() {
        const submitBtn = this.querySelector('button[type="submit"]');
        if (submitBtn) {
            submitBtn.innerHTML = '<i class="icon-loader animate-spin"></i><span>Laadimine...</span>';
            submitBtn.disabled = true;
        }
    });
}
</script>

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