<?php
/**
 * Estreka Ratsaklubi - Üldised funktsioonid
 * PARANDATUD: Täpselt vastavalt reeglitele + Multi-day võistlused + Kiiruse arvutamine
 */

// URL KONFIGURATSIOON
define('BASE_URL', '/ratsaklubi.estreka');
define('BASE_PATH', $_SERVER['DOCUMENT_ROOT'] . '/ratsaklubi.estreka');

function url($path = '') {
    return BASE_URL . ($path ? '/' . ltrim($path, '/') : '');
}

function emailUrl($path = '') {
    $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $relative_url = BASE_URL . ($path ? '/' . ltrim($path, '/') : '');
    return $protocol . '://' . $host . $relative_url;
}

/**
 * Arvutab sportlase isiklikud insights'id
 */
function calculatePersonalInsights($user_id, $year, $pdo) {
    $insights = [];
    
    try {
        // Lae kõik sportlase tulemused selleks aastaks
        $stmt = $pdo->prepare("
            SELECT 
                r.*,
                c.name as competitionName, 
                c.date as competitionDate, 
                c.location
            FROM results r
            JOIN competitions c ON r.competitionId = c.id
            WHERE r.userId = ? AND strftime('%Y', c.date) = ?
            ORDER BY c.date ASC
        ");
        $stmt->execute([$user_id, $year]);
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if (empty($results)) {
            return $insights; // Tagasta tühi, kui tulemusi pole
        }
        
        // 1. Osaluse analüüs
        $insights['participation'] = calculateParticipationInsights($results);
        
        // 2. Distsipliinide analüüs
        $insights['disciplines'] = calculateDisciplineInsights($results);
        
        // 3. Tulemuste mustrid
        $insights['performance'] = calculatePerformanceInsights($results);
        
        // 4. Isiklikud soovitused
        $insights['recommendations'] = generatePersonalRecommendations($results, $insights);
        
    } catch (Exception $e) {
        error_log('Personal insights calculation error: ' . $e->getMessage());
        return [];
    }
    
    return $insights;
}

/**
 * Arvutab osaluse insights'id
 */
function calculateParticipationInsights($results) {
    $locations = [];
    $current_year_locations = [];
    $current_year = date('Y');
    
    foreach ($results as $result) {
        if (!empty($result['location'])) {
            $location = $result['location'];
            $locations[$location] = ($locations[$location] ?? 0) + 1;
            
            if (date('Y', strtotime($result['competitionDate'])) == $current_year) {
                $current_year_locations[$location] = true;
            }
        }
    }
    
    if (empty($locations)) {
        return [];
    }
    
    // Leia lemmikkoht
    arsort($locations);
    $favorite_location = array_key_first($locations);
    $favorite_count = $locations[$favorite_location];
    
    // Loe eelmiste aastate kohad
    $previous_locations = array_keys($locations);
    $new_locations_count = 0;
    
    foreach ($current_year_locations as $loc => $val) {
        // Kui see koht on ainult sel aastal, siis on uus
        $found_in_previous = false;
        foreach ($results as $result) {
            if ($result['location'] === $loc && date('Y', strtotime($result['competitionDate'])) < $current_year) {
                $found_in_previous = true;
                break;
            }
        }
        if (!$found_in_previous) {
            $new_locations_count++;
        }
    }
    
    return [
        'unique_locations' => count($locations),
        'favorite_location' => $favorite_location,
        'favorite_location_count' => $favorite_count,
        'new_locations_this_year' => $new_locations_count
    ];
}

/**
 * Arvutab distsipliinide insights'id
 */
function calculateDisciplineInsights($results) {
    $disciplines = [];
    
    foreach ($results as $result) {
        $disc = $result['discipline'];
        if (!isset($disciplines[$disc])) {
            $disciplines[$disc] = [];
        }
        
        // Takistussõit - kõrgused
        if ($disc === 'takistussoit' && !empty($result['height'])) {
            $disciplines[$disc]['heights'][] = $result['height'];
        }
        
        // Koolisõit - skeemid
        if ($disc === 'koolisoit' && !empty($result['scheme'])) {
            $disciplines[$disc]['schemes'][] = [
                'scheme' => $result['scheme'],
                'percentage' => $result['percentage']
            ];
        }
        
        // Kestvusratsutamine - distantsid
        if ($disc === 'kestvusratsutamine' && !empty($result['distance'])) {
            $disciplines[$disc]['distances'][] = $result['distance'];
        }
    }
    
    $insights = [];
    
    foreach ($disciplines as $disc => $data) {
        $disc_insights = [];
        
        // Takistussõidu analüüs
        if ($disc === 'takistussoit' && !empty($data['heights'])) {
            $heights = $data['heights'];
            $height_counts = array_count_values($heights);
            arsort($height_counts);
            
            $disc_insights['height_stats'] = [
                'favorite' => array_key_first($height_counts),
                'count' => $height_counts[array_key_first($height_counts)],
                'highest' => max($heights),
                'average' => round(array_sum($heights) / count($heights))
            ];
        }
        
        // Koolisõidu analüüs
        if ($disc === 'koolisoit' && !empty($data['schemes'])) {
            $schemes = $data['schemes'];
            $scheme_counts = [];
            $scheme_averages = [];
            
            foreach ($schemes as $scheme_data) {
                $scheme = $scheme_data['scheme'];
                $scheme_counts[$scheme] = ($scheme_counts[$scheme] ?? 0) + 1;
                
                if (!isset($scheme_averages[$scheme])) {
                    $scheme_averages[$scheme] = [];
                }
                if (!empty($scheme_data['percentage'])) {
                    $scheme_averages[$scheme][] = $scheme_data['percentage'];
                }
            }
            
            arsort($scheme_counts);
            $favorite_scheme = array_key_first($scheme_counts);
            
            // Leia parim skeem (kõrgeim keskmine protsent)
            $best_scheme = null;
            $best_avg = 0;
            foreach ($scheme_averages as $scheme => $percentages) {
                if (!empty($percentages)) {
                    $avg = array_sum($percentages) / count($percentages);
                    if ($avg > $best_avg) {
                        $best_avg = $avg;
                        $best_scheme = $scheme;
                    }
                }
            }
            
            $disc_insights['scheme_stats'] = [
                'favorite' => $favorite_scheme,
                'count' => $scheme_counts[$favorite_scheme],
                'best_performing' => $best_scheme,
                'best_avg' => $best_avg
            ];
        }
        
        // Kestvusratsutamise analüüs
        if ($disc === 'kestvusratsutamine' && !empty($data['distances'])) {
            $distances = $data['distances'];
            $distance_counts = array_count_values($distances);
            arsort($distance_counts);
            
            $disc_insights['distance_stats'] = [
                'favorite' => array_key_first($distance_counts),
                'total' => array_sum($distances),
                'average' => array_sum($distances) / count($distances),
                'longest' => max($distances)
            ];
        }
        
        if (!empty($disc_insights)) {
            $insights[$disc] = $disc_insights;
        }
    }
    
    return $insights;
}

/**
 * Arvutab tulemuste mustreid
 */
function calculatePerformanceInsights($results) {
    $insights = [];
    
    // Kuude analüüs
    $monthly_points = [];
    $location_points = [];
    $finished_count = 0;
    $total_count = count($results);
    $placements = [];
    
    foreach ($results as $result) {
        $month = date('n', strtotime($result['competitionDate']));
        $month_name = getEstonianMonthName($month);
        
        if (!isset($monthly_points[$month])) {
            $monthly_points[$month] = ['points' => [], 'name' => $month_name];
        }
        $monthly_points[$month]['points'][] = $result['points'];
        
        // Kohtade analüüs
        if (!empty($result['location'])) {
            if (!isset($location_points[$result['location']])) {
                $location_points[$result['location']] = [];
            }
            $location_points[$result['location']][] = $result['points'];
        }
        
        // Lõpetamise statistika
        if ($result['finished']) {
            $finished_count++;
        }
        
        // Kohad
        if (!empty($result['placement'])) {
            $placements[] = $result['placement'];
        }
    }
    
    // Leia parim kuu
    $best_month = null;
    $best_month_avg = 0;
    foreach ($monthly_points as $month => $data) {
        $avg = array_sum($data['points']) / count($data['points']);
        if ($avg > $best_month_avg) {
            $best_month_avg = $avg;
            $best_month = ['name' => $data['name'], 'avg' => $avg];
        }
    }
    
    // Leia parim koht (keskmine punktide järgi)
    $best_location = null;
    $best_location_avg = 0;
    foreach ($location_points as $location => $points) {
        if (count($points) >= 2) { // Ainult kui vähemalt 2 võistlust seal
            $avg = array_sum($points) / count($points);
            if ($avg > $best_location_avg) {
                $best_location_avg = $avg;
                $best_location = ['name' => $location, 'avg' => $avg];
            }
        }
    }
    
    $insights['finish_rate'] = round(($finished_count / $total_count) * 100);
    
    if ($best_month) {
        $insights['best_month'] = $best_month;
    }
    
    if ($best_location) {
        $insights['best_location'] = $best_location;
    }
    
    if (!empty($placements)) {
        $insights['best_placement'] = min($placements);
        $top10_count = count(array_filter($placements, function($p) { return $p <= 10; }));
        $insights['top10_rate'] = round(($top10_count / count($placements)) * 100);
    }
    
    return $insights;
}

/**
 * Genereerib isiklikud soovitused
 */
function generatePersonalRecommendations($results, $insights) {
    $recommendations = [];
    
    // Analüüsi andmeid ja tee soovitusi
    
    // 1. Takistussõidu soovitused
    if (!empty($insights['disciplines']['takistussoit']['height_stats'])) {
        $height_stats = $insights['disciplines']['takistussoit']['height_stats'];
        $current_max = $height_stats['highest'];
        $favorite = $height_stats['favorite'];
        
        if ($current_max - $favorite <= 10) {
            $next_height = $current_max + 10;
            $recommendations[] = [
                'icon' => '<i class="icon-zap"></i>',
                'text' => "Proovi {$next_height}cm takistusi - {$current_max}cm oled juba kindlalt läbinud!"
            ];
        }
    }
    
    // 2. Koolisõidu soovitused
    if (!empty($insights['disciplines']['koolisoit']['scheme_stats'])) {
        $scheme_stats = $insights['disciplines']['koolisoit']['scheme_stats'];
        $best_scheme = $scheme_stats['best_performing'] ?? null;
        $favorite_scheme = $scheme_stats['favorite'];
        
        if ($best_scheme && $best_scheme !== $favorite_scheme) {
            $recommendations[] = [
                'icon' => '<i class="icon-target"></i>',
                'text' => "{$best_scheme} on sinu parim skeem - proovi seda sagedamini!"
            ];
        }
    }
    
    // 3. Kohtade soovitused
    if (!empty($insights['performance']['best_location'])) {
        $best_location = $insights['performance']['best_location']['name'];
        $recommendations[] = [
            'icon' => '<i class="icon-map-pin"></i>',
            'text' => "{$best_location} on sinu õnnelik koht - planeeri sinna rohkem võistlusi!"
        ];
    }
    
    // 4. Hooajalised soovitused
    if (!empty($insights['performance']['best_month'])) {
        $best_month = $insights['performance']['best_month']['name'];
        $recommendations[] = [
            'icon' => '<i class="icon-calendar"></i>',
            'text' => "{$best_month} on sinu parim kuu - planeeri tähtsamad võistlused selleks ajaks!"
        ];
    }
    
    // 5. Kestvusratsutamise soovitused
    if (!empty($insights['disciplines']['kestvusratsutamine']['distance_stats'])) {
        $distance_stats = $insights['disciplines']['kestvusratsutamine']['distance_stats'];
        $longest = $distance_stats['longest'];
        $next_challenge = $longest + 5;
        
        $recommendations[] = [
            'icon' => '<i class="icon-activity"></i>',
            'text' => "Järgmine väljakutse: {$next_challenge}km distants - {$longest}km läks ju hästi!"
        ];
    }
    
    // 6. Üldised soovitused
    if (!empty($insights['performance']['finish_rate']) && $insights['performance']['finish_rate'] < 90) {
        $recommendations[] = [
            'icon' => '<i class="icon-check-circle"></i>',
            'text' => "Keskendub lõpetamisele - iga lõpetatud võistlus on võit!"
        ];
    }
    
    return $recommendations;
}

/**
 * Tagastab eestikeelse kuu nime
 */
function getEstonianMonthName($month_number) {
    $estonian_months = [
        1 => 'Jaanuar',
        2 => 'Veebruar', 
        3 => 'Märts',
        4 => 'Aprill',
        5 => 'Mai',
        6 => 'Juuni',
        7 => 'Juuli',
        8 => 'August',
        9 => 'September',
        10 => 'Oktoober',
        11 => 'November',
        12 => 'Detsember'
    ];
    
    return $estonian_months[$month_number] ?? 'Tundmatu';
}

// UUED FUNKTSIOONID: Multi-day võistlused
/**
 * Formaadi võistluse kuupäevad
 */
function formatCompetitionDates($competition) {
    if ($competition['is_multi_day'] && $competition['start_date'] !== $competition['end_date']) {
        $start = formatDate($competition['start_date']);
        $end = formatDate($competition['end_date']);
        return $start . ' - ' . $end;
    } else {
        // Kasuta start_date kui see on olemas, muidu vana date välja
        $display_date = $competition['start_date'] ?: $competition['date'];
        return formatDate($display_date);
    }
}

/**
 * Arvuta võistluse päevade arv
 */
function getCompetitionDays($competition) {
    if ($competition['is_multi_day'] && $competition['start_date'] && $competition['end_date']) {
        $start = new DateTime($competition['start_date']);
        $end = new DateTime($competition['end_date']);
        return $end->diff($start)->days + 1;
    }
    return 1;
}

// LISATUD: Kiiruse arvutamise funktsioonid
/**
 * Arvutab keskmise kiiruse km/h
 */
function calculateAverageSpeed($distance_km, $time_seconds) {
    if (!$distance_km || !$time_seconds || $distance_km <= 0 || $time_seconds <= 0) {
        return null;
    }
    
    // Kiirus km/h = distants(km) / aeg(h)
    $time_hours = $time_seconds / 3600;
    $speed_kmh = $distance_km / $time_hours;
    
    return round($speed_kmh, 2);
}

/**
 * Vormistab kiiruse kuvamiseks
 */
function formatSpeed($speed_kmh) {
    if ($speed_kmh === null || $speed_kmh <= 0) return '-';
    return number_format((float)$speed_kmh, 2) . ' km/h';
}

/**
 * Kestvusratsutamise distantsi valideerimine
 */
function validateEnduranceDistance($distance) {
    if (empty($distance)) return false;
    
    $distance_num = (float)$distance;
    
    // Mõistlik vahemik: 5-200 km
    return $distance_num >= 5 && $distance_num <= 200;
}

// PUNKTIARVESTUSE SÜSTEEM - TÄPSELT VASTAVALT REEGLITELE
$POINTS_SYSTEM = [
    'koolisoit' => [
        'percentage' => [
            ['min' => 70, 'points' => 12],
            ['min' => 68, 'points' => 10], 
            ['min' => 65, 'points' => 8],
            ['min' => 62, 'points' => 6],
            ['min' => 60, 'points' => 5],
            ['min' => 58, 'points' => 4],
            ['min' => 55, 'points' => 3],
            ['min' => 50, 'points' => 2],
            ['min' => 0, 'points' => 1]
        ],
        'scheme' => [
            'L-skeem' => 3,    // Kõige raskem (+3p)
            'A-skeem' => 2,    // Raske (+2p)
            'ABC-skeem' => 1,  // Keskmine (+1p)
            'NH4A-skeem' => 1, // Noorhobuste skeem (sama tase kui ABC) (+1p)
            'ST-skeem' => 0    // Kõige kergem (+0p)
        ],
        'placement' => [1 => 5, 2 => 4, 3 => 3, 4 => 2, 5 => 1],
        'participation' => 0.5,
        'max_starts' => 6
    ],
    'takistussoit' => [
        'fault_points' => [
            ['max' => 0, 'points' => 12],
            ['max' => 4, 'points' => 10],
            ['max' => 8, 'points' => 8], 
            ['max' => 12, 'points' => 6],
            ['max' => 16, 'points' => 4],
            ['max' => 20, 'points' => 2],
            ['max' => PHP_INT_MAX, 'points' => 1]
        ],
        'participation' => 0.5,
        'max_starts' => 10
    ],
    'kestvusratsutamine' => [
        'distance' => [
            ['min' => 100, 'points' => 12],   // 100+ km: 12 punkti
            ['min' => 80, 'points' => 10],    // 80-99 km: 10 punkti
            ['min' => 40, 'points' => 8],     // 40-79 km: 8 punkti
            ['min' => 0, 'points' => 6]       // PARANDATUD: kuni 39 km: 6 punkti
        ],
        'placement' => [1 => 6, 2 => 5, 3 => 4, 4 => 3, 5 => 2],
        'completion_bonus' => 1,              // Edukalt lõpetamine (sõltumata kohast)
        'participation' => 0.5,
        'max_starts' => 4
    ]
];

/**
 * Arvutab punktid koolisõidu jaoks
 */
function calculateDressagePoints($percentage, $scheme, $placement, $finished = true) {
    global $POINTS_SYSTEM;
    
    if (!$finished) {
        return [
            'points' => 0.5,
            'base_points' => 0,
            'scheme_bonus' => 0,
            'placement_bonus' => 0,
            'participation' => 0.5
        ];
    }
    
    // Baaspunktid protsendi järgi
    $base_points = 1; // vaikimisi alla 50%
    foreach ($POINTS_SYSTEM['koolisoit']['percentage'] as $range) {
        if ($percentage >= $range['min']) {
            $base_points = $range['points'];
            break;
        }
    }
    
    // Skeemi bonus
    $scheme_bonus = $POINTS_SYSTEM['koolisoit']['scheme'][$scheme] ?? 0;
    
    // Koha bonus
    $placement_bonus = $POINTS_SYSTEM['koolisoit']['placement'][$placement] ?? 0;
    
    // Osalemispunkt
    $participation = $POINTS_SYSTEM['koolisoit']['participation'];
    
    $total = $base_points + $scheme_bonus + $placement_bonus + $participation;
    
    return [
        'points' => $total,
        'base_points' => $base_points,
        'scheme_bonus' => $scheme_bonus,
        'placement_bonus' => $placement_bonus,
        'participation' => $participation
    ];
}

/**
 * Arvutab punktid takistussõidu jaoks (AINULT karistuspunktide alusel)
 */
function calculateJumpingPoints($fault_points, $finished = true, $height = null, $time_seconds = null, $placement = null) {
    global $POINTS_SYSTEM;
    
    if (!$finished) {
        return [
            'points' => $POINTS_SYSTEM['takistussoit']['participation'],
            'base_points' => 0,
            'participation' => $POINTS_SYSTEM['takistussoit']['participation'],
            'breakdown' => 'Raja läbimine, ka kui katkestab'
        ];
    }
    
    // AINULT karistuspunktide põhine arvestus
    $base_points = 1; // vaikimisi üle 20 karistuspunkti
    foreach ($POINTS_SYSTEM['takistussoit']['fault_points'] as $range) {
        if ($fault_points <= $range['max']) {
            $base_points = $range['points'];
            break;
        }
    }
    
    $participation = $POINTS_SYSTEM['takistussoit']['participation'];
    $total = $base_points + $participation;
    
    $breakdown = "Karistuspunktid: {$fault_points} → {$base_points}p + Osalemine: {$participation}p";
    
    return [
        'points' => round($total, 1),
        'base_points' => $base_points,
        'participation' => $participation,
        'breakdown' => $breakdown
    ];
}

/**
 * PARANDATUD: Arvutab punktid kestvusratsutamise jaoks + kiiruse arvutamine
 */
function calculateEndurancePoints($distance_km, $placement, $finished = true, $time_seconds = null, $pulse = null) {
    global $POINTS_SYSTEM;
    
    if (!$finished) {
        return [
            'points' => $POINTS_SYSTEM['kestvusratsutamine']['participation'],
            'distance_points' => 0,
            'placement_points' => 0,
            'completion_bonus' => 0,
            'participation' => $POINTS_SYSTEM['kestvusratsutamine']['participation'],
            'breakdown' => 'Ka kui ei lõpeta',
            'average_speed' => null
        ];
    }
    
    // PARANDATUD: Distantsi punktid vastavalt reeglitele
    $distance_points = 6; // vaikimisi kuni 39km = 6 punkti
    foreach ($POINTS_SYSTEM['kestvusratsutamine']['distance'] as $range) {
        if ($distance_km >= $range['min']) {
            $distance_points = $range['points'];
            break;
        }
    }
    
    // Koha punktid (kui koht on määratud)
    $placement_points = 0;
    if ($placement !== null && isset($POINTS_SYSTEM['kestvusratsutamine']['placement'][$placement])) {
        $placement_points = $POINTS_SYSTEM['kestvusratsutamine']['placement'][$placement];
    } else {
        // Kui koht pole määratud, aga edukalt lõpetas = 1 punkt
        $placement_points = 1;
    }
    
    // Boonused
    $completion_bonus = $POINTS_SYSTEM['kestvusratsutamine']['completion_bonus'];
    $participation = $POINTS_SYSTEM['kestvusratsutamine']['participation'];
    
    $total = $distance_points + $placement_points + $completion_bonus + $participation;
    
    // LISATUD: Kiiruse arvutamine
    $average_speed = calculateAverageSpeed($distance_km, $time_seconds);
    $speed_info = '';
    if ($average_speed) {
        $speed_info = " | Kiirus: " . formatSpeed($average_speed);
    }
    
    // Breakdown kirjeldus koos kiirusega
    if ($placement !== null) {
        $breakdown = "Distants {$distance_km}km → {$distance_points}p + {$placement}. koht → {$placement_points}p + Lõpetamine → {$completion_bonus}p + Osalemine → {$participation}p{$speed_info}";
    } else {
        $breakdown = "Distants {$distance_km}km → {$distance_points}p + Lõpetamine ilma kohata → {$placement_points}p + Lõpetamine → {$completion_bonus}p + Osalemine → {$participation}p{$speed_info}";
    }
    
    return [
        'points' => $total,
        'distance_points' => $distance_points,
        'placement_points' => $placement_points,
        'completion_bonus' => $completion_bonus,
        'participation' => $participation,
        'breakdown' => $breakdown,
        'average_speed' => $average_speed
    ];
}

/**
 * Arvutab punktid distsipliini järgi
 */
function calculatePoints($discipline, $data) {
    switch ($discipline) {
        case 'koolisoit':
            return calculateDressagePoints(
                $data['percentage'] ?? 0,
                $data['scheme'] ?? 'ST-skeem',
                $data['placement'] ?? null,
                $data['finished'] ?? true
            );
        case 'takistussoit':
            return calculateJumpingPoints(
                $data['fault_points'] ?? 0,
                $data['finished'] ?? true,
                $data['height'] ?? null,
                $data['time_seconds'] ?? null,
                $data['placement'] ?? null
            );
        case 'kestvusratsutamine':
            return calculateEndurancePoints(
                $data['distance'] ?? 0,
                $data['placement'] ?? null,
                $data['finished'] ?? true,
                $data['time_seconds'] ?? null,
                $data['pulse'] ?? null
            );
        default:
            throw new InvalidArgumentException("Tundmatu distsipliin: $discipline");
    }
}

/**
 * Arvutab hooaja arvestuse
 */
function calculateSeasonStandings($all_results, $discipline) {
    global $POINTS_SYSTEM;
    
    $max_starts = $POINTS_SYSTEM[$discipline]['max_starts'];
    
    // Sorteeri punktide järgi kõrgeimad enne
    usort($all_results, function($a, $b) {
        return $b['points'] <=> $a['points'];
    });
    
    // Võta ainult maksimum lubatud starte
    $counted_results = array_slice($all_results, 0, $max_starts);
    
    // Arvuta kogusumma
    $total_points = array_sum(array_column($counted_results, 'points'));
    
    return [
        'total_points' => round($total_points, 2),
        'counted_results' => $counted_results,
        'all_results' => $all_results,
        'starts_count' => count($all_results),
        'max_starts' => $max_starts
    ];
}

/**
 * PARANDATUD: Vormistab aja distsipliini järgi
 */
function formatTime($seconds, $discipline = null) {
    if ($seconds === null || $seconds <= 0) return '-';
    
    // PARANDUS: Takistussõit kasutab sec.centisec formaati (ametlik formaat)
    if ($discipline === 'takistussoit') {
        return number_format((float)$seconds, 2) . 's';
    }
    
    // Kestvusratsutamine ja üldine: kuvame h:mm:ss või mm:ss
    $hours = floor($seconds / 3600);
    $minutes = floor(($seconds % 3600) / 60);
    $secs = $seconds % 60;
    
    if ($hours > 0) {
        return sprintf('%d:%02d:%02d', $hours, $minutes, $secs);
    } else {
        return sprintf('%d:%02d', $minutes, $secs);
    }
}

/**
 * PARANDATUD: Konverteerib aja sekunditeks (distsipliini-spetsiifiline)
 */
function parseTimeToSeconds($time_string, $discipline = null) {
    if (empty($time_string)) return null;
    
    // PARANDUS: Takistussõit kasutab sec.centisec formaati
    if ($discipline === 'takistussoit') {
        // Eemaldame tühikud ja kontrollime formaati
        $cleaned = trim($time_string);
        
        // Eemaldame võimaliku 's' lõpust
        $cleaned = rtrim($cleaned, 's');
        
        // Asendame koma punktiga (eesti keele harjumus)
        $cleaned = str_replace(',', '.', $cleaned);
        
        // Kontrollime kas on kehtiv number
        if (is_numeric($cleaned)) {
            $value = (float)$cleaned;
            // Mõistlik vahemik takistussõidu jaoks (5-600 sekundit)
            if ($value >= 5 && $value <= 600) {
                return $value;
            }
        }
        
        return null;
    }
    
    // Kestvusratsutamine ja üldine: h:mm:ss formaat (jääb samaks)
    $parts = explode(':', $time_string);
    
    if (count($parts) == 3) {
        // h:mm:ss
        return $parts[0] * 3600 + $parts[1] * 60 + $parts[2];
    } elseif (count($parts) == 2) {
        // mm:ss
        return $parts[0] * 60 + $parts[1];
    } elseif (count($parts) == 1 && is_numeric($parts[0])) {
        // ainult minutid
        return $parts[0] * 60;
    }
    
    return null;
}

/**
 * LISATUD: Takistussõidu aja valideerimise funktsioon
 */
function validateJumpingTimeInput($time_string) {
    if (empty($time_string)) return true; // Valikuline väli
    
    $cleaned = trim($time_string);
    $cleaned = rtrim($cleaned, 's'); // Eemalda võimalik 's'
    $cleaned = str_replace(',', '.', $cleaned); // Asenda koma punktiga
    
    // Kontrollime formaati: number.number (nt. 65.42)
    if (!preg_match('/^(\d{1,3})(\.\d{1,2})?$/', $cleaned)) {
        return false;
    }
    
    $seconds = (float)$cleaned;
    
    // Mõistlik ajavahemik takistussõidu jaoks
    return $seconds >= 5 && $seconds <= 600;
}

/**
 * Määrab vanusegruppi
 */
function getAgeGroup($birth_date, $season_year = null) {
    if ($season_year === null) {
        $season_year = date('Y');
    }
    
    $age = $season_year - date('Y', strtotime($birth_date));
    return $age <= 18 ? 'noored' : 'täiskasvanud';
}

/**
 * Tagastab distsipliini nimetuse
 */
function getDisciplineName($discipline) {
    $names = [
        'koolisoit' => 'Koolisõit',
        'takistussoit' => 'Takistussõit',
        'kestvusratsutamine' => 'Kestvusratsutamine'
    ];
    return $names[$discipline] ?? $discipline;
}

/**
 * Tagastab vanusegruppi nimetuse
 */
function getAgeGroupName($age_group_or_birth_date) {
    if (is_string($age_group_or_birth_date) && strpos($age_group_or_birth_date, '-') !== false) {
        $age_group = getAgeGroup($age_group_or_birth_date);
    } else {
        $age_group = $age_group_or_birth_date;
    }
    
    $names = [
        'all' => 'Kõik',
        'noored' => 'Noored (kuni 18)',
        'täiskasvanud' => 'Täiskasvanud (üle 18)'
    ];
    return $names[$age_group] ?? $age_group;
}

/**
 * Vormistab punktid
 */
function formatPoints($points) {
    return number_format((float)$points, 1, '.', '');
}

/**
 * Vormistab protsendi
 */
function formatPercentage($percentage) {
    return $percentage ? number_format((float)$percentage, 3) . '%' : '-';
}

/**
 * Vormistab kuupäeva
 */
function formatDate($date) {
    return $date ? date('d.m.Y', strtotime($date)) : '-';
}

/**
 * Kontrollib kasutaja sisselogimist
 */
function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

/**
 * Kontrollib admin õigusi
 */
function isAdmin() {
    return isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin';
}

/**
 * Kontrollib sportlase õigusi
 */
function isAthlete() {
    return isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'athlete';
}

/**
 * Nõuab sisselogimist
 */
function requireLogin() {
    if (!isLoggedIn()) {
        header('Location: ' . url('login.php'));
        exit;
    }
}

/**
 * Nõuab admin õigusi
 */
function requireAdmin() {
    requireLogin();
    if (!isAdmin()) {
        header('Location: ' . url());
        exit;
    }
}

/**
 * Turvaliselt tagastab POST andmed
 */
function getPost($key, $default = null) {
    return isset($_POST[$key]) ? trim($_POST[$key]) : $default;
}

/**
 * Turvaliselt tagastab GET andmed
 */
function getGet($key, $default = null) {
    return isset($_GET[$key]) ? trim($_GET[$key]) : $default;
}

/**
 * Kuvab veateateid
 */
function showError($message) {
    return '<div class="alert alert-error">' . htmlspecialchars($message) . '</div>';
}

/**
 * Kuvab eduteadet
 */
function showSuccess($message) {
    return '<div class="alert alert-success">' . htmlspecialchars($message) . '</div>';
}

/**
 * Genereerib turvalisema salasõna hash
 */
function hashPassword($password) {
    return password_hash($password, PASSWORD_DEFAULT);
}

/**
 * Kontrollib salasõna
 */
function verifyPassword($password, $hash) {
    return password_verify($password, $hash);
}

/**
 * Tagastab skeemi värvi CSS klassi
 */
function getSchemeColorClass($scheme) {
    $colors = [
        'L-skeem' => 'scheme-l',
        'A-skeem' => 'scheme-a',
        'ABC-skeem' => 'scheme-abc',
        'NH4A-skeem' => 'scheme-nh4a',
        'ST-skeem' => 'scheme-st'
    ];
    return $colors[$scheme] ?? 'scheme-default';
}

/**
 * Tagastab meeleolu emotikoni
 */
function getMoodEmoji($mood) {
    $emojis = [
        1 => '😤',
        2 => '😕',
        3 => '😐',
        4 => '😊',
        5 => '😍'
    ];
    return $emojis[$mood] ?? '😐';
}

/**
 * Logib tegevused
 */
function logActivity($user_id, $action, $details = '') {
    global $pdo;
    try {
        $stmt = $pdo->prepare("
            INSERT INTO activity_log (user_id, action, details, created_at)
            VALUES (?, ?, ?, datetime('now'))
        ");
        $stmt->execute([$user_id, $action, $details]);
    } catch(Exception $e) {
        error_log("Activity log error: " . $e->getMessage());
    }
}
?>