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

// Filtrid
$discipline = getGet('discipline', 'all');
$year = getGet('year', date('Y'));
$competition = getGet('competition', 'all');

// Valideeri sisend
$valid_disciplines = ['all', 'koolisoit', 'takistussoit', 'kestvusratsutamine'];
if (!in_array($discipline, $valid_disciplines)) {
    $discipline = 'all';
}

$error = '';
$results = [];
$competitions = [];

try {
    // Lae võistlused filteriks
    $stmt = $pdo->prepare("
        SELECT DISTINCT id, name, date, discipline 
        FROM competitions 
        WHERE strftime('%Y', date) = ?
        ORDER BY date DESC
    ");
    $stmt->execute([$year]);
    $competitions = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Ehita päring
    $where_conditions = ["strftime('%Y', c.date) = ?"];
    $params = [$year];
    
    if ($discipline !== 'all') {
        $where_conditions[] = "r.discipline = ?";
        $params[] = $discipline;
    }
    
    if ($competition !== 'all') {
        $where_conditions[] = "c.id = ?";
        $params[] = $competition;
    }
    
    $where_clause = implode(' AND ', $where_conditions);
    
    // Lae tulemused
    $stmt = $pdo->prepare("
        SELECT 
            r.*,
            u.firstName, u.lastName, u.birthDate,
            c.name as competitionName, c.date as competitionDate, c.location
        FROM results r
        JOIN users u ON r.userId = u.id
        JOIN competitions c ON r.competitionId = c.id
        WHERE {$where_clause}
        ORDER BY c.date DESC, r.points DESC
    ");
    $stmt->execute($params);
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Lisa vanusegrupid
    foreach ($results as &$result) {
        $result['ageGroup'] = getAgeGroup($result['birthDate'], $year);
    }
    
} catch(PDOException $e) {
    $error = 'Tulemuste laadimine ebaõnnestus: ' . $e->getMessage();
    error_log('Results error: ' . $e->getMessage());
}

$page_title = 'Võistluste tulemused';
$page_description = 'Vaata kõiki Estreka Ratsaklubi võistluste tulemusi ja punkte.';

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

<main class="results-main">
    <div class="container">
        <!-- Header -->
        <div class="page-header">
            <div class="page-header-content">
                <h1 class="page-title">Võistluste tulemused</h1>
                <p class="page-subtitle">
                    Kõik tulemused hooajast <?php echo $year; ?>
                    <?php if ($discipline !== 'all'): ?>
                        - <?php echo getDisciplineName($discipline); ?>
                    <?php endif; ?>
                </p>
            </div>
        </div>

        <!-- Filtrid -->
        <div class="filters-section">
            <form method="GET" class="filters-form">
                <div class="filters-grid">
                    <div class="filter-group">
                        <label for="discipline" class="filter-label">Distsipliin</label>
                        <select name="discipline" id="discipline" class="filter-select">
                            <option value="all" <?php echo $discipline === 'all' ? 'selected' : ''; ?>>
                                Kõik distsipliinid
                            </option>
                            <?php foreach (['koolisoit', 'takistussoit', 'kestvusratsutamine'] as $disc): ?>
                                <option value="<?php echo $disc; ?>" <?php echo $discipline === $disc ? 'selected' : ''; ?>>
                                    <?php echo getDisciplineName($disc); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="filter-group">
                        <label for="competition" class="filter-label">Võistlus</label>
                        <select name="competition" id="competition" class="filter-select">
                            <option value="all" <?php echo $competition === 'all' ? 'selected' : ''; ?>>
                                Kõik võistlused
                            </option>
                            <?php foreach ($competitions as $comp): ?>
                                <option value="<?php echo $comp['id']; ?>" <?php echo $competition == $comp['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($comp['name']) . ' (' . formatDate($comp['date']) . ')'; ?>
                                </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>

        <!-- Tulemused -->
        <?php if ($error): ?>
            <div class="alert alert-error">
                <i class="icon-alert-circle"></i>
                <span><?php echo htmlspecialchars($error); ?></span>
            </div>
        <?php elseif (empty($results)): ?>
            <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>
                <a href="?discipline=all&competition=all&year=<?php echo date('Y'); ?>" class="btn btn-primary">
                    Vaata kõiki tulemusi
                </a>
            </div>
        <?php else: ?>
            <div class="results-container">
                <div class="results-header">
                    <h2 class="results-title">
                        Tulemused (<?php echo count($results); ?>)
                    </h2>
                </div>

                <div class="results-list">
                    <?php 
                    $current_competition = '';
                    foreach ($results as $result): 
                        if ($current_competition !== $result['competitionName']):
                            if ($current_competition !== ''): ?>
                                </div> <!-- competition-results end -->
                            <?php endif; ?>
                            <div class="competition-section">
                                <div class="competition-header">
                                    <div class="competition-info">
                                        <h3 class="competition-name">
                                            <?php echo htmlspecialchars($result['competitionName']); ?>
                                        </h3>
                                        <div class="competition-meta">
                                            <span class="competition-date">
                                                <?php echo formatDate($result['competitionDate']); ?>
                                            </span>
                                            <?php if ($result['location']): ?>
                                                <span class="competition-location">
                                                    <i class="icon-map-pin"></i>
                                                    <?php echo htmlspecialchars($result['location']); ?>
                                                </span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    <div class="discipline-badge <?php echo $result['discipline']; ?>">
                                        <?php echo getDisciplineName($result['discipline']); ?>
                                    </div>
                                </div>
                                <div class="competition-results">
                            <?php 
                            $current_competition = $result['competitionName'];
                        endif; 
                        ?>
                        
                        <div class="result-card">
                            <div class="result-athlete">
                                <div class="athlete-name">
                                    <?php echo htmlspecialchars($result['firstName'] . ' ' . $result['lastName']); ?>
                                </div>
                                <div class="athlete-meta">
                                    <?php echo getAgeGroupName($result['ageGroup']); ?>
                                </div>
                            </div>
                            
                            <div class="result-details">
                                <?php if ($result['discipline'] === 'koolisoit'): ?>
                                    <div class="result-data">
                                        <span class="data-label">Protsent:</span>
                                        <span class="data-value"><?php echo formatPercentage($result['percentage']); ?></span>
                                    </div>
                                    <div class="result-data">
                                        <span class="data-label">Skeem:</span>
                                        <span class="data-value"><?php echo htmlspecialchars($result['scheme']); ?></span>
                                    </div>
                                <?php elseif ($result['discipline'] === 'takistussoit'): ?>
                                    <div class="result-data">
                                        <span class="data-label">Karistuspunktid:</span>
                                        <span class="data-value"><?php echo $result['faultPoints']; ?></span>
                                    </div>
                                    <?php if ($result['height']): ?>
                                        <div class="result-data">
                                            <span class="data-label">Kõrgus:</span>
                                            <span class="data-value"><?php echo $result['height']; ?>cm</span>
                                        </div>
                                    <?php endif; ?>
                                    <!-- LISATUD: Takistussõidu aja kuvamine -->
                                    <?php if ($result['time_seconds']): ?>
                                        <div class="result-data time-data">
                                            <span class="data-label">Aeg:</span>
                                            <span class="data-value time-value">
                                                <?php echo formatTime($result['time_seconds'], 'takistussoit'); ?>
                                            </span>
                                        </div>
                                    <?php endif; ?>
                                <?php elseif ($result['discipline'] === 'kestvusratsutamine'): ?>
                                    <div class="result-data">
                                        <span class="data-label">Distants:</span>
                                        <span class="data-value"><?php echo $result['distance']; ?>km</span>
                                    </div>
                                    <!-- LISATUD: Kestvusratsutamise aja kuvamine -->
                                    <?php if ($result['time_seconds']): ?>
                                        <div class="result-data time-data">
                                            <span class="data-label">Lõpuaeg:</span>
                                            <span class="data-value time-value">
                                                <?php echo formatTime($result['time_seconds'], 'kestvusratsutamine'); ?>
                                            </span>
                                        </div>
                                        
                                        <!-- PARANDATUD: Kiirus ilma raamita -->
                                        <?php 
                                        $average_speed = calculateAverageSpeed($result['distance'], $result['time_seconds']);
                                        if ($average_speed): 
                                        ?>
                                            <div class="speed-inline">
                                                Kiirus: <span class="speed-subtle"><?php echo formatSpeed($average_speed); ?></span>
                                            </div>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                    <!-- LISATUD: Pulsi kuvamine -->
                                    <?php if ($result['pulse']): ?>
                                        <div class="result-data">
                                            <span class="data-label">Pulss:</span>
                                            <span class="data-value"><?php echo $result['pulse']; ?> l/min</span>
                                        </div>
                                    <?php endif; ?>
                                <?php endif; ?>
                                
                                <?php if ($result['placement']): ?>
                                    <div class="placement-inline">
                                        Koht: <span class="placement-value"><?php echo $result['placement']; ?>.</span>
                                        <?php if ($result['placement'] <= 3): ?>
                                            <?php 
                                            $medals = [1 => '🥇', 2 => '🥈', 3 => '🥉'];
                                            echo ' ' . $medals[$result['placement']];
                                            ?>
                                        <?php endif; ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                            
                            <div class="result-points">
                                <div class="points-value">
                                    <?php echo formatPoints($result['points']); ?>
                                </div>
                                <div class="points-label">punkti</div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                    
                    <?php if ($current_competition !== ''): ?>
                        </div> <!-- competition-results end -->
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>
    </div>
</main>

<style>
/* Results Page Styles - ENHANCED WITH SPEED DISPLAY */
.results-main {
    padding: var(--spacing-8) 0;
    min-height: 100vh;
}

.page-header {
    margin-bottom: var(--spacing-8);
}

.page-title {
    margin-bottom: var(--spacing-2);
}

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

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

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

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

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

.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);
}

.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);
}

/* Results Container */
.results-container {
    background: white;
    border-radius: var(--radius-lg);
    box-shadow: var(--shadow);
    overflow: hidden;
}

.results-header {
    padding: var(--spacing-6);
    border-bottom: 1px solid var(--gray-200);
}

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

/* Competition Sections */
.competition-section {
    border-bottom: 1px solid var(--gray-100);
}

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

.competition-name {
    margin: 0 0 var(--spacing-1);
    font-size: var(--font-size-lg);
    font-weight: 600;
}

.competition-meta {
    display: flex;
    gap: var(--spacing-4);
    font-size: var(--font-size-sm);
    color: var(--gray-600);
}

.competition-location {
    display: flex;
    align-items: center;
    gap: var(--spacing-1);
}

.discipline-badge {
    padding: var(--spacing-2) var(--spacing-3);
    border-radius: var(--radius);
    font-size: var(--font-size-sm);
    font-weight: 500;
    color: white;
}

.discipline-badge.koolisoit { background: linear-gradient(135deg, var(--primary-color), var(--primary-dark)); }
.discipline-badge.takistussoit { background: linear-gradient(135deg, var(--success-color), #047857); }
.discipline-badge.kestvusratsutamine { background: linear-gradient(135deg, #8b5cf6, #7c3aed); }

.competition-results {
    padding: var(--spacing-4) 0;
}

/* Result Cards - ENHANCED WITH SPEED DISPLAY */
.result-card {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: var(--spacing-4) var(--spacing-6);
    border-bottom: 1px solid var(--gray-100);
    transition: background-color var(--transition-fast);
    gap: var(--spacing-4);
}

.result-card:hover {
    background: var(--gray-50);
}

.result-card:last-child {
    border-bottom: none;
}

.result-athlete {
    min-width: 150px;
}

.athlete-name {
    font-weight: 500;
    color: var(--gray-900);
    margin-bottom: var(--spacing-1);
}

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

.result-details {
    display: flex;
    gap: var(--spacing-4);
    flex-wrap: wrap;
    flex: 1;
    justify-content: center;
}

.result-data {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-1);
    text-align: center;
    min-width: 80px;
}

/* ENHANCED: Time data styling */
.result-data.time-data {
    background: linear-gradient(135deg, #e3f2fd, #bbdefb);
    padding: var(--spacing-2) var(--spacing-3);
    border-radius: var(--radius);
    border: 1px solid #90caf9;
}

/* LISATUD: Kiiruse andmete stiilid */
.result-data.speed-data {
    background: linear-gradient(135deg, #f0fdf4, #dcfce7);
    padding: var(--spacing-2) var(--spacing-3);
    border-radius: var(--radius);
    border: 1px solid #22c55e;
}

.speed-data .data-label {
    color: #15803d;
    font-weight: 600;
}

.result-data.placement-data {
    background: linear-gradient(135deg, #fff3e0, #ffe0b2);
    padding: var(--spacing-2) var(--spacing-3);
    border-radius: var(--radius);
    border: 1px solid #ffcc02;
}

.data-label {
    font-size: var(--font-size-xs);
    color: var(--gray-500);
    text-transform: uppercase;
    letter-spacing: 0.05em;
    font-weight: 500;
}

.time-data .data-label {
    color: #1565c0;
    font-weight: 600;
}

.data-value {
    font-weight: 600;
    color: var(--gray-900);
    font-size: var(--font-size-sm);
}

/* ENHANCED: Time value styling */
.data-value.time-value {
    font-family: 'Courier New', monospace;
    font-size: var(--font-size-base);
    font-weight: 700;
    color: #1565c0;
    letter-spacing: 1px;
    background: rgba(255, 255, 255, 0.8);
    padding: var(--spacing-1) var(--spacing-2);
    border-radius: var(--radius-sm);
    border: 1px solid #2196f3;
}

/* LISATUD: Kiiruse väärtuse stiilid */
.data-value.speed-value {
    font-family: 'Courier New', monospace;
    font-size: var(--font-size-base);
    font-weight: 700;
    color: #15803d;
    letter-spacing: 1px;
    background: rgba(255, 255, 255, 0.8);
    padding: var(--spacing-1) var(--spacing-2);
    border-radius: var(--radius-sm);
    border: 1px solid #22c55e;
}

.data-value.placement {
    color: var(--warning-color);
    font-size: var(--font-size-lg);
    font-weight: 700;
}

.result-points {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: var(--spacing-1);
    min-width: 80px;
    padding: var(--spacing-2) var(--spacing-3);
    background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
    color: white;
    border-radius: var(--radius);
}

.points-value {
    font-size: var(--font-size-xl);
    font-weight: 700;
    line-height: 1;
}

.points-label {
    font-size: var(--font-size-xs);
    opacity: 0.9;
    text-transform: uppercase;
    letter-spacing: 0.05em;
}

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

.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;
}

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

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

.btn {
    padding: var(--spacing-3) var(--spacing-4);
    border: 1px solid;
    border-radius: var(--radius);
    cursor: pointer;
    font-weight: 500;
    font-size: var(--font-size-sm);
    display: inline-flex;
    align-items: center;
    gap: var(--spacing-2);
    transition: all var(--transition-fast);
    text-decoration: none;
}

.btn-primary {
    background: var(--primary-color);
    color: white;
    border-color: var(--primary-color);
}

.btn-primary:hover {
    background: var(--primary-dark);
    border-color: var(--primary-dark);
}

/* Alert */
.alert {
    padding: var(--spacing-4);
    border-radius: var(--radius);
    margin-bottom: var(--spacing-4);
    display: flex;
    align-items: center;
    gap: var(--spacing-3);
}

.alert-error {
    background: color-mix(in srgb, var(--danger-color) 10%, transparent);
    color: var(--danger-color);
    border: 1px solid color-mix(in srgb, var(--danger-color) 20%, transparent);
}

/* LISATUD: Ajaindikaator */
.time-value::after {
    content: '';
    display: inline-block;
    width: 4px;
    height: 4px;
    border-radius: 50%;
    margin-left: var(--spacing-1);
    background: #2196f3;
}

/* Responsive */
@media (max-width: 768px) {
    .filters-grid {
        grid-template-columns: 1fr;
    }
    
    .competition-header {
        flex-direction: column;
        align-items: flex-start;
        gap: var(--spacing-3);
    }
    
    .result-card {
        flex-direction: column;
        align-items: flex-start;
        gap: var(--spacing-3);
        padding: var(--spacing-4);
    }
    
    .result-details {
        width: 100%;
        justify-content: space-between;
        gap: var(--spacing-2);
    }
    
    .result-data {
        min-width: auto;
        flex: 1;
    }
    
    .result-points {
        align-self: center;
        padding: var(--spacing-3) var(--spacing-4);
    }
    
    .result-data.time-data {
        background: linear-gradient(135deg, #e8f4fd, #cfe8fc);
        padding: var(--spacing-3);
        border-radius: var(--radius-lg);
        margin: var(--spacing-2) 0;
    }
    
    .data-value.time-value {
        font-size: var(--font-size-base);
    }
    
    .speed-inline,
    .placement-inline {
        margin-top: var(--spacing-2);
        font-size: var(--font-size-sm);
    }
}

@media (max-width: 480px) {
    .result-details {
        flex-direction: column;
        align-items: center;
        gap: var(--spacing-3);
    }
    
    .result-data {
        width: 100%;
        text-align: center;
        padding: var(--spacing-2);
        background: var(--gray-50);
        border-radius: var(--radius);
    }
    
    .result-data.time-data {
        background: linear-gradient(135deg, #e3f2fd, #bbdefb);
        border: 1px solid #90caf9;
    }
    
    .speed-inline,
    .placement-inline {
        text-align: center;
        margin: var(--spacing-2) 0;
    }
}

/* Visual indicators for different time formats */
.time-value::after {
    content: '';
    display: inline-block;
    width: 6px;
    height: 6px;
    border-radius: 50%;
    margin-left: var(--spacing-1);
    background: #2196f3;
}

/* Different colors for different disciplines */
.discipline-badge.takistussoit + * .time-value::after {
    background: var(--success-color);
}

.discipline-badge.kestvusratsutamine + * .time-value::after {
    background: #8b5cf6;
}
</style>

<script>
// Lihtne DOM load event - enam pole vaja kiiruse kategooriaid 
document.addEventListener('DOMContentLoaded', function() {
    console.log('✅ Results page loaded');
});
</script>

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