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

// CSS fail määrata enne header.php
$page_css = 'admin-results.css';

// DEBUG: Error reporting ja logimine
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);

function debugLog($message, $data = null) {
    $log_message = "[" . date('Y-m-d H:i:s') . "] ADMIN RESULTS: " . $message;
    if ($data !== null) {
        $log_message .= " | Data: " . print_r($data, true);
    }
    error_log($log_message);
}

// Nõua admin õigusi
requireAdmin();

$error = '';
$success = '';

function getJumpingHeights() {
    return [
        60 => '60 cm',
        70 => '70 cm',
        80 => '80 cm',
        90 => '90 cm',
        100 => '100 cm',
        110 => '110 cm',
        120 => '120 cm',
        130 => '130 cm',
        140 => '140 cm'
    ];
}

// EEMALDATUD: getEnduranceDistances() - ei ole enam vaja kuna kasutame numbrilist sisestust

// Töötle tulemuse lisamist/muutmist
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_result'])) {
    debugLog('Processing result save', $_POST);
    
    try {
        $result_id = getPost('result_id');
        $userId = getPost('userId');
        $competitionId = getPost('competitionId');
        $discipline = getPost('discipline');
        $finished = isset($_POST['finished']) ? 1 : 0;
        $placement = getPost('placement');
        $notes = getPost('notes');
        
        // Distsipliini spetsiifilised väljad
        $percentage = getPost('percentage');
        $scheme = getPost('scheme');
        $faultPoints = getPost('faultPoints');
        $distance = getPost('distance');
        $height = getPost('height');
        $time_input = getPost('time_input');
        $pulse = getPost('pulse');
        
        if (empty($userId) || empty($competitionId) || empty($discipline)) {
            throw new Exception('Sportlane, võistlus ja distsipliin on kohustuslikud');
        }
        
        // Kontrolli kas distsipliin on võistlusel lubatud
        $stmt = $pdo->prepare("SELECT disciplines, discipline FROM competitions WHERE id = ?");
        $stmt->execute([$competitionId]);
        $competition = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$competition) {
            throw new Exception('Võistlust ei leitud');
        }
        
        $allowed_disciplines = [];
        if ($competition['disciplines']) {
            $allowed_disciplines = json_decode($competition['disciplines'], true) ?: [];
        } else {
            $allowed_disciplines = [$competition['discipline']];
        }
        
        if (!in_array($discipline, $allowed_disciplines)) {
            throw new Exception("Distsipliin '$discipline' ei ole sellel võistlusel lubatud");
        }
        
        // Arvuta punktid
        $points_data = [
            'finished' => $finished,
            'placement' => $placement ? (int)$placement : null
        ];
        
        if ($discipline === 'koolisoit') {
            if (empty($percentage) || empty($scheme)) {
                throw new Exception('Koolisõidu puhul on protsent ja skeem kohustuslikud');
            }
            $points_data['percentage'] = (float)$percentage;
            $points_data['scheme'] = $scheme;
            
        } elseif ($discipline === 'takistussoit') {
            if ($faultPoints === '') {
                throw new Exception('Takistussõidu puhul on karistuspunktid kohustuslikud');
            }
            $points_data['fault_points'] = (int)$faultPoints;
            
        } elseif ($discipline === 'kestvusratsutamine') {
            if (empty($distance)) {
                throw new Exception('Kestvusratsutamise puhul on distants kohustuslik');
            }
            
            // LISATUD: Valideeri numbriline distants
            if (!validateEnduranceDistance($distance)) {
                throw new Exception('Distants peab olema 5-200 km vahemikus');
            }
            
            $points_data['distance'] = (float)$distance;
        }
        
        debugLog('Points calculation input', $points_data);
        
        $calculated_points = calculatePoints($discipline, $points_data);
        $total_points = $calculated_points['points'];
        
        debugLog('Points calculated', ['total' => $total_points, 'breakdown' => $calculated_points]);
        
        // PARANDATUD: Konverteerib aeg sekunditeks distsipliini järgi
        $time_seconds = parseTimeToSeconds($time_input, $discipline);
        
        // LISATUD: Valideeri takistussõidu aja sisend
        if ($discipline === 'takistussoit' && !empty($time_input)) {
            if (!validateJumpingTimeInput($time_input)) {
                throw new Exception('Takistussõidu aeg peab olema formaadis sekundid.sajandikud (nt. 65.42)');
            }
        }
        
        debugLog('Time conversion', [
            'input' => $time_input,
            'discipline' => $discipline,
            'seconds' => $time_seconds
        ]);
        
        if ($result_id) {
            // Uuenda olemasolevat tulemust
            $sql = "UPDATE results SET 
                    userId = ?, competitionId = ?, discipline = ?, points = ?, 
                    finished = ?, placement = ?, notes = ?, 
                    percentage = ?, scheme = ?, faultPoints = ?, 
                    distance = ?, height = ?, time_seconds = ?, pulse = ?,
                    updatedAt = CURRENT_TIMESTAMP 
                    WHERE id = ?";
            $params = [
                $userId, $competitionId, $discipline, $total_points,
                $finished, $placement, $notes,
                $percentage, $scheme, $faultPoints,
                $distance, $height, $time_seconds, $pulse,
                $result_id
            ];
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            $success = 'Tulemus edukalt uuendatud!';
            logActivity($_SESSION['user_id'], 'result_updated', "Result updated for user $userId");
            
        } else {
            // Lisa uus tulemus
            $sql = "INSERT INTO results 
                    (userId, competitionId, discipline, points, finished, placement, notes, 
                     percentage, scheme, faultPoints, distance, height, time_seconds, pulse) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $params = [
                $userId, $competitionId, $discipline, $total_points,
                $finished, $placement, $notes,
                $percentage, $scheme, $faultPoints,
                $distance, $height, $time_seconds, $pulse
            ];
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            $success = 'Uus tulemus edukalt lisatud!';
            logActivity($_SESSION['user_id'], 'result_added', "Result added for user $userId");
        }
        
    } catch(Exception $e) {
        $error = 'Tulemuse salvestamine ebaõnnestus: ' . $e->getMessage();
        debugLog('Save result error', $e->getMessage());
    }
}

// Töötle tulemuse kustutamist
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_result'])) {
    $result_id = getPost('result_id');
    
    try {
        $stmt = $pdo->prepare("DELETE FROM results WHERE id = ?");
        $stmt->execute([$result_id]);
        $success = 'Tulemus edukalt kustutatud!';
        logActivity($_SESSION['user_id'], 'result_deleted', "Result deleted (ID: $result_id)");
        
    } catch(PDOException $e) {
        $error = 'Tulemuse kustutamine ebaõnnestus: ' . $e->getMessage();
        debugLog('Delete result error', $e->getMessage());
    }
}

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

// Lae võistlused filteriks koos õige disciplines andmetega
$competitions = [];
try {
    $stmt = $pdo->prepare("
        SELECT id, name, date, discipline, disciplines 
        FROM competitions 
        WHERE strftime('%Y', date) = ?
        ORDER BY date DESC
    ");
    $stmt->execute([$year]);
    $competitions_raw = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Kasuta õiget viitamist ja parsi disciplines
    foreach ($competitions_raw as $comp) {
        $processed_comp = $comp; // Kopeeri algne andmestruktuur
        
        if ($comp['disciplines']) {
            $disciplines_array = json_decode($comp['disciplines'], true);
            if (is_array($disciplines_array) && !empty($disciplines_array)) {
                $processed_comp['disciplines_array'] = $disciplines_array;
            } else {
                // JSON decode ebaõnnestus, kasuta vana discipline välja
                $processed_comp['disciplines_array'] = [$comp['discipline']];
            }
        } else {
            // disciplines väli on tühi, kasuta vana discipline välja
            $processed_comp['disciplines_array'] = [$comp['discipline']];
        }
        
        $competitions[] = $processed_comp;
    }
    
    debugLog('Competitions loaded', ['count' => count($competitions), 'sample' => $competitions[0] ?? null]);
    
} catch(PDOException $e) {
    debugLog('Competitions load error', $e->getMessage());
    $competitions = [];
}

// Lae sportlased filteriks
$athletes = [];
try {
    $stmt = $pdo->prepare("SELECT id, firstName, lastName FROM users WHERE role = 'athlete' AND isActive = 1 ORDER BY lastName, firstName");
    $stmt->execute();
    $athletes = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    debugLog('Athletes load error', $e->getMessage());
    $athletes = [];
}

// Lae tulemused
$results = [];
try {
    $where_conditions = ["strftime('%Y', c.date) = ?"];
    $params = [$year];
    
    if ($competition_filter !== 'all') {
        $where_conditions[] = "r.competitionId = ?";
        $params[] = $competition_filter;
    }
    
    if ($discipline_filter !== 'all') {
        $where_conditions[] = "r.discipline = ?";
        $params[] = $discipline_filter;
    }
    
    if ($athlete_filter !== 'all') {
        $where_conditions[] = "r.userId = ?";
        $params[] = $athlete_filter;
    }
    
    $where_clause = implode(' AND ', $where_conditions);
    
    $stmt = $pdo->prepare("
        SELECT 
            r.*,
            u.firstName, u.lastName,
            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);
    
} catch(PDOException $e) {
    $error = 'Tulemuste laadimine ebaõnnestus: ' . $e->getMessage();
    debugLog('Results load error', $e->getMessage());
    $results = [];
}

$page_title = 'Admin - Tulemuste haldamine';
$page_description = 'Sisesta ja halda võistluste tulemusi.';

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

<main class="admin-results-main">
    <div class="container">
        <!-- Header -->
        <div class="page-header">
            <div class="page-header-content">
                <h1 class="page-title">Tulemuste haldamine</h1>
                <p class="page-subtitle">
                    Sisesta ja halda võistluste tulemusi
                </p>
            </div>
            <div class="page-actions">
                <button onclick="openModal('resultModal')" class="btn btn-primary">
                    <i class="icon-plus"></i>
                    <span>Lisa tulemus</span>
                </button>
            </div>
        </div>

        <!-- Alerts -->
        <?php if ($error): ?>
            <div class="alert alert-error">
                <i class="icon-alert-circle"></i>
                <span><?php echo htmlspecialchars($error); ?></span>
            </div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="alert alert-success">
                <i class="icon-check-circle"></i>
                <span><?php echo htmlspecialchars($success); ?></span>
            </div>
        <?php endif; ?>

        <!-- Filtrid -->
        <div class="filters-section">
            <form method="GET" class="filters-form">
                <div class="filters-grid">
                    <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_filter === 'all' ? 'selected' : ''; ?>>
                                Kõik võistlused
                            </option>
                            <?php foreach ($competitions as $comp): ?>
                                <option value="<?php echo $comp['id']; ?>" <?php echo $competition_filter == $comp['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($comp['name']) . ' (' . formatDate($comp['date']) . ')'; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <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_filter === 'all' ? 'selected' : ''; ?>>
                                Kõik distsipliinid
                            </option>
                            <option value="koolisoit" <?php echo $discipline_filter === 'koolisoit' ? 'selected' : ''; ?>>
                                Koolisõit
                            </option>
                            <option value="takistussoit" <?php echo $discipline_filter === 'takistussoit' ? 'selected' : ''; ?>>
                                Takistussõit
                            </option>
                            <option value="kestvusratsutamine" <?php echo $discipline_filter === 'kestvusratsutamine' ? 'selected' : ''; ?>>
                                Kestvusratsutamine
                            </option>
                        </select>
                    </div>

                    <div class="filter-group">
                        <label for="athlete" class="filter-label">Sportlane</label>
                        <select name="athlete" id="athlete" class="filter-select">
                            <option value="all" <?php echo $athlete_filter === 'all' ? 'selected' : ''; ?>>
                                Kõik sportlased
                            </option>
                            <?php foreach ($athletes as $athlete): ?>
                                <option value="<?php echo $athlete['id']; ?>" <?php echo $athlete_filter == $athlete['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($athlete['firstName'] . ' ' . $athlete['lastName']); ?>
                                </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-secondary">
                            <i class="icon-filter"></i>
                            <span>Filtreeri</span>
                        </button>
                    </div>
                </div>
            </form>
        </div>

        <!-- Tulemuste loend -->
        <div class="results-container">
            <div class="results-header">
                <h2 class="results-title">
                    Tulemused (<?php echo count($results); ?>)
                </h2>
            </div>

            <?php if (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>
                    <button onclick="openModal('resultModal')" class="btn btn-primary">
                        <i class="icon-plus"></i>
                        <span>Lisa esimene tulemus</span>
                    </button>
                </div>
            <?php else: ?>
                <div class="results-table-wrapper">
                    <table class="results-table">
                        <thead>
                            <tr>
                                <th>Sportlane</th>
                                <th>Võistlus</th>
                                <th>Distsipliin</th>
                                <th>Detailid</th>
                                <th>Koht</th>
                                <th>Punktid</th>
                                <th>Staatus</th>
                                <th>Toimingud</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($results as $result): ?>
                                <tr>
                                    <td class="athlete-cell" data-label="Sportlane">
                                        <div class="athlete-name">
                                            <?php echo htmlspecialchars($result['firstName'] . ' ' . $result['lastName']); ?>
                                        </div>
                                    </td>
                                    <td class="competition-cell" data-label="Võistlus">
                                        <div class="competition-name">
                                            <?php echo htmlspecialchars($result['competitionName']); ?>
                                        </div>
                                        <div class="competition-date">
                                            <?php echo formatDate($result['competitionDate']); ?>
                                        </div>
                                    </td>
                                    <td class="discipline-cell" data-label="Distsipliin">
                                        <span class="discipline-badge <?php echo $result['discipline']; ?>">
                                            <?php echo getDisciplineName($result['discipline']); ?>
                                        </span>
                                    </td>
                                    <td class="details-cell" data-label="Detailid">
                                        <?php if ($result['discipline'] === 'koolisoit'): ?>
                                            <div class="detail-item">
                                                <?php echo formatPercentage($result['percentage']); ?> • <?php echo htmlspecialchars($result['scheme']); ?>
                                            </div>
                                        <?php elseif ($result['discipline'] === 'takistussoit'): ?>
                                            <div class="detail-item">
                                                <?php echo $result['faultPoints']; ?> karistuspunkti
                                                <?php if ($result['height']): ?>
                                                    <br>Kõrgus: <?php echo $result['height']; ?>cm
                                                <?php endif; ?>
                                                <?php if ($result['time_seconds']): ?>
                                                    <!-- PARANDATUD: Takistussõidu aja kuvamine -->
                                                    <br>Aeg: <?php echo formatTime($result['time_seconds'], 'takistussoit'); ?>
                                                <?php endif; ?>
                                            </div>
                                        <?php elseif ($result['discipline'] === 'kestvusratsutamine'): ?>
                                            <div class="detail-item">
                                                <?php echo $result['distance']; ?>km
                                                <?php if ($result['time_seconds']): ?>
                                                    <!-- Kestvusratsutamise aeg jääb samaks -->
                                                    <br>Aeg: <?php echo formatTime($result['time_seconds'], 'kestvusratsutamine'); ?>
                                                    <!-- PARANDATUD: Tagasihoidlik kiiruse kuvamine -->
                                                    <?php 
                                                    $average_speed = calculateAverageSpeed($result['distance'], $result['time_seconds']);
                                                    if ($average_speed): 
                                                    ?>
                                                        <br>Kiirus: <span class="speed-subtle"><?php echo formatSpeed($average_speed); ?></span>
                                                    <?php endif; ?>
                                                <?php endif; ?>
                                                <?php if ($result['pulse']): ?>
                                                    <br>Pulss: <?php echo $result['pulse']; ?> l/min
                                                <?php endif; ?>
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                    <td class="placement-cell" data-label="Koht">
                                        <?php if ($result['placement']): ?>
                                            <span class="placement-badge"><?php echo $result['placement']; ?>.</span>
                                        <?php else: ?>
                                            -
                                        <?php endif; ?>
                                    </td>
                                    <td class="points-cell" data-label="Punktid">
                                        <div class="points-value">
                                            <?php echo formatPoints($result['points']); ?>
                                        </div>
                                    </td>
                                    <td class="status-cell" data-label="Staatus">
                                        <?php if ($result['finished']): ?>
                                            <span class="status-badge finished">Lõpetas</span>
                                        <?php else: ?>
                                            <span class="status-badge unfinished">Katkestas</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="actions-cell" data-label="Toimingud">
                                        <div class="action-buttons">
                                            <button onclick="editResult(<?php echo htmlspecialchars(json_encode($result)); ?>)" 
                                                    class="btn-icon btn-primary" title="Muuda">
                                                <i class="icon-edit"></i>
                                            </button>
                                            
                                            <form method="POST" style="display: inline;" 
                                                  onsubmit="return confirm('Kas oled kindel, et tahad selle tulemuse kustutada?')">
                                                <input type="hidden" name="result_id" value="<?php echo $result['id']; ?>">
                                                <button type="submit" name="delete_result" class="btn-icon btn-danger" title="Kustuta">
                                                    <i class="icon-trash"></i>
                                                </button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Tulemuse modal -->
    <div id="resultModal" class="modal">
        <div class="modal-overlay">
            <div class="modal-content">
                <div class="modal-header">
                    <h3 class="modal-title" id="modalTitle">Lisa tulemus</h3>
                    <button class="modal-close" onclick="closeModal('resultModal')">
                        <i class="icon-x"></i>
                    </button>
                </div>

                <form method="POST" class="modal-form" id="resultForm">
                    <input type="hidden" name="result_id" id="result_id">
                    
                    <div class="form-grid">
                        <div class="form-group">
                            <label for="userId" class="form-label">Sportlane *</label>
                            <select id="userId" name="userId" class="form-select" required>
                                <option value="">Vali sportlane</option>
                                <?php foreach ($athletes as $athlete): ?>
                                    <option value="<?php echo $athlete['id']; ?>">
                                        <?php echo htmlspecialchars($athlete['firstName'] . ' ' . $athlete['lastName']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="modalCompetitionId" class="form-label">Võistlus *</label>
                            <select id="modalCompetitionId" name="competitionId" class="form-select" required onchange="updateCompetitionDisciplines()">
                                <option value="">Vali võistlus</option>
                                <?php foreach ($competitions as $comp): ?>
                                    <option value="<?php echo $comp['id']; ?>" 
                                            data-disciplines="<?php echo htmlspecialchars(json_encode($comp['disciplines_array'])); ?>"
                                            data-single-discipline="<?php echo htmlspecialchars($comp['discipline']); ?>">
                                        <?php echo htmlspecialchars($comp['name']) . ' (' . formatDate($comp['date']) . ')'; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="modalDiscipline" class="form-label">Distsipliin *</label>
                            <select id="modalDiscipline" name="discipline" class="form-select" required onchange="toggleDisciplineFields()">
                                <option value="">Vali esmalt võistlus</option>
                            </select>
                            <div class="form-help" id="modalDisciplineHelp">Vali esmalt võistlus, siis kuvatakse selle distsipliinid</div>
                        </div>

                        <div class="form-group">
                            <label for="placement" class="form-label">Koht</label>
                            <input type="number" id="placement" name="placement" class="form-input" 
                                   min="1" max="100" placeholder="Koht võistlusel">
                        </div>
                    </div>

                    <!-- Koolisõidu väljad -->
                    <div id="dressageFields" class="discipline-fields" style="display: none;">
                        <h4 class="fields-title">Koolisõidu andmed</h4>
                        <div class="form-grid">
                            <div class="form-group">
                                <label for="percentage" class="form-label">Protsent *</label>
                                <input type="number" id="percentage" name="percentage" class="form-input" 
                                       step="any" min="0" max="100" placeholder="65.456">
                            </div>

                            <div class="form-group">
                                <label for="scheme" class="form-label">Skeem *</label>
                                <select id="scheme" name="scheme" class="form-select">
                                    <option value="">Vali skeem</option>
                                    <option value="L-skeem">L-skeem (kõige raskem)</option>
                                    <option value="A-skeem">A-skeem (raske)</option>
                                    <option value="ABC-skeem">ABC-skeem (keskmine)</option>
                                    <option value="NH4A-skeem">NH4A-skeem (noorhobuste skeem)</option>
                                    <option value="ST-skeem">ST-skeem (kõige kergem)</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <!-- PARANDATUD: Takistussõidu väljad -->
                    <div id="jumpingFields" class="discipline-fields" style="display: none;">
                        <h4 class="fields-title">Takistussõit</h4>
                        <div class="form-grid">
                            <div class="form-group">
                                <label for="faultPoints" class="form-label">Karistuspunktid *</label>
                                <input type="number" id="faultPoints" name="faultPoints" class="form-input" 
                                       min="0" step="1" placeholder="0" required>
                                <div class="form-help">Kokku saadud karistuspunktid</div>
                            </div>

                            <div class="form-group">
                                <label for="height" class="form-label">Takistuste kõrgus (cm)</label>
                                <input type="number" id="height" name="height" class="form-input" 
                                       min="50" max="200" step="5" placeholder="80">
                                <div class="form-help">Takistuste kõrgus sentimeetrites</div>
                            </div>

                            <!-- PARANDATUD: Takistussõidu aja väli -->
                            <div class="form-group">
                                <label for="time_input_jumping" class="form-label">Aeg (sekundites)</label>
                                <input type="text" id="time_input_jumping" name="time_input" 
                                       class="form-input time-input jumping-time-input" 
                                       placeholder="65.42" pattern="^(\d{1,3})(\.\d{1,2})?$">
                                <div class="form-help jumping-time">
                                    <strong>⏱️ AMETLIK FORMAAT:</strong> sekundid.sajandikud (nt. 65.42) 
                                    <br><small>Mitte minutid:sekundid!</small>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Kõrguse kiirvalikud -->
                        <div class="height-presets">
                            <label class="form-label">Levinud kõrgused:</label>
                            <div class="preset-buttons">
                                <button type="button" class="btn-preset" onclick="setHeight(60, this)">60cm</button>
                                <button type="button" class="btn-preset" onclick="setHeight(80, this)">80cm</button>
                                <button type="button" class="btn-preset" onclick="setHeight(100, this)">100cm</button>
                                <button type="button" class="btn-preset" onclick="setHeight(120, this)">120cm</button>
                                <button type="button" class="btn-preset" onclick="setHeight(140, this)">140cm</button>
                            </div>
                        </div>
                    </div>

                    <!-- PARANDATUD: Kestvusratsutamise väljad -->
                    <div id="enduranceFields" class="discipline-fields" style="display: none;">
                        <h4 class="fields-title">Kestvusratsutamise andmed</h4>
                        <div class="form-grid">
                            <!-- PARANDATUD: Numbriline distantsi sisestus -->
                            <div class="form-group">
                                <label for="distance" class="form-label">Distants (km) *</label>
                                <input type="number" id="distance" name="distance" class="form-input" 
                                       min="5" max="200" step="0.1" placeholder="20.5" required>
                                <div class="form-help">Distants kilomeetrites (nt. 20.5)</div>
                            </div>

                            <div class="form-group">
                                <label for="time_input_endurance" class="form-label">Lõpuaeg</label>
                                <input type="text" id="time_input_endurance" name="time_input" class="form-input time-input" 
                                       placeholder="2:30:45" pattern="^(\d{1,2}):([0-5]\d):([0-5]\d)$">
                                <div class="form-help">Formaat: h:mm:ss (nt. 2:30:45)</div>
                            </div>

                            <div class="form-group">
                                <label for="pulse" class="form-label">Pulss pärast lõppu (l/min)</label>
                                <input type="number" id="pulse" name="pulse" class="form-input" 
                                       min="30" max="120" placeholder="64">
                                <div class="form-help">Pulss 10min pärast lõppu</div>
                            </div>
                        </div>
                        
                        <!-- LISATUD: Levinud distantside kiirvalikud -->
                        <div class="distance-presets">
                            <label class="form-label">Levinud distantsid:</label>
                            <div class="preset-buttons">
                                <button type="button" class="btn-preset" onclick="setDistance(15, this)">15 km</button>
                                <button type="button" class="btn-preset" onclick="setDistance(20, this)">20 km</button>
                                <button type="button" class="btn-preset" onclick="setDistance(25, this)">25 km</button>
                                <button type="button" class="btn-preset" onclick="setDistance(30, this)">30 km</button>
                                <button type="button" class="btn-preset" onclick="setDistance(40, this)">40 km</button>
                                <button type="button" class="btn-preset" onclick="setDistance(60, this)">60 km</button>
                                <button type="button" class="btn-preset" onclick="setDistance(80, this)">80 km</button>
                                <button type="button" class="btn-preset" onclick="setDistance(100, this)">100 km</button>
                            </div>
                        </div>
                        
                        <!-- LISATUD: Kiiruse eelvaade -->
                        <div id="speed_preview" class="speed-preview" style="display: none;">
                            <strong>Keskmine kiirus:</strong> <span id="calculated_speed">-</span>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="checkbox-label">
                            <input type="checkbox" name="finished" id="finished" class="checkbox-input" checked>
                            <span class="checkbox-custom"></span>
                            <span class="checkbox-text">Sportlane lõpetas võistluse</span>
                        </label>
                    </div>

                    <div class="form-group">
                        <label for="notes" class="form-label">Märkused</label>
                        <textarea id="notes" name="notes" class="form-textarea" rows="3" 
                                  placeholder="Lisainformatsioon tulemuse kohta..."></textarea>
                    </div>

                    <div class="modal-actions">
                        <button type="button" onclick="closeModal('resultModal')" class="btn btn-secondary">
                            Tühista
                        </button>
                        <button type="submit" name="save_result" class="btn btn-primary">
                            <i class="icon-save"></i>
                            <span id="saveButtonText">Lisa tulemus</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</main>

<!-- PARANDATUD CSS ja JavaScript -->
<style>
/* PARANDATUD: Takistussõidu aja välja stiilid */
.jumping-time-input {
    font-family: 'Courier New', monospace;
    font-size: 1.2em;
    text-align: center;
    letter-spacing: 2px;
    font-weight: bold;
    background: #f8f9ff;
    border: 2px solid #007bff;
}

.jumping-time-input:focus {
    background: #ffffff;
    border-color: #0056b3;
    box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.25);
}

.jumping-time-input.error {
    border-color: #dc3545;
    background: #fff5f5;
}

.form-help.jumping-time {
    background: linear-gradient(135deg, #fff3cd, #ffeaa7);
    padding: 12px;
    border-radius: 6px;
    border-left: 4px solid #ffc107;
    margin-top: 8px;
    font-weight: 500;
    color: #856404;
}

/* LISATUD: Distantsi eelvaadete stiilid */
.distance-presets {
    margin-top: var(--spacing-4);
    padding: var(--spacing-3);
    background: var(--gray-50);
    border-radius: var(--radius);
}

.speed-preview {
    margin-top: var(--spacing-3);
    padding: var(--spacing-2);
    text-align: right;
    font-size: var(--font-size-xs);
    color: var(--gray-500);
}

/* LISATUD: Täiesti tavaline kiiruse stiil ilma raamita */
.speed-subtle {
    font-family: 'Courier New', monospace;
    font-weight: 500;
    color: var(--gray-600);
    font-size: var(--font-size-sm);
}
</style>

<script>
// PARANDATUD: Takistussõidu aja JavaScript funktsioonid
document.addEventListener('DOMContentLoaded', function() {
    const jumpingTimeInput = document.getElementById('time_input_jumping');
    
    if (jumpingTimeInput) {
        // Real-time valideerimise ja formateerimine
        jumpingTimeInput.addEventListener('input', function() {
            let value = this.value;
            
            // Eemaldame 's' lõpust automaatselt
            value = value.replace(/s$/g, '');
            
            // Asendame koma punktiga
            value = value.replace(',', '.');
            
            // Eemalda kõik mis pole number või punkt
            value = value.replace(/[^0-9.]/g, '');
            
            // Luba ainult üks punkt
            const parts = value.split('.');
            if (parts.length > 2) {
                value = parts[0] + '.' + parts.slice(1).join('');
            }
            
            // Piira sajandikud 2 kohani
            if (parts.length === 2 && parts[1].length > 2) {
                value = parts[0] + '.' + parts[1].substring(0, 2);
            }
            
            // Piira sekundid 3 kohas
            if (parts[0].length > 3) {
                value = parts[0].substring(0, 3) + (parts[1] ? '.' + parts[1] : '');
            }
            
            this.value = value;
            
            // Visuaalne feedback
            validateJumpingTime(this);
        });
        
        jumpingTimeInput.addEventListener('blur', function() {
            validateJumpingTime(this, true);
        });
        
        jumpingTimeInput.addEventListener('focus', function() {
            this.classList.remove('error');
        });
    }
    
    // Vorm submiti valideerimine
    const resultForm = document.getElementById('resultForm');
    if (resultForm) {
        resultForm.addEventListener('submit', function(e) {
            const jumpingTimeInput = document.getElementById('time_input_jumping');
            const discipline = document.getElementById('modalDiscipline').value;
            
            if (discipline === 'takistussoit' && jumpingTimeInput && jumpingTimeInput.value) {
                if (!validateJumpingTimeFormat(jumpingTimeInput.value)) {
                    e.preventDefault();
                    jumpingTimeInput.focus();
                    alert('Palun sisesta takistussõidu aeg õiges formaadis: sekundid.sajandikud (nt. 65.42)');
                    return false;
                }
            }
        });
    }
    
    // LISATUD: Event listenerid kiiruse arvutamiseks
    const distanceInput = document.getElementById('distance');
    const timeInput = document.getElementById('time_input_endurance');
    
    if (distanceInput) {
        distanceInput.addEventListener('input', calculateSpeedPreview);
    }
    
    if (timeInput) {
        timeInput.addEventListener('input', calculateSpeedPreview);
    }
});

function validateJumpingTime(input, showAlert = false) {
    const value = input.value.trim();
    
    if (!value) {
        input.classList.remove('error');
        return true;
    }
    
    const isValid = validateJumpingTimeFormat(value);
    
    if (isValid) {
        input.classList.remove('error');
        if (showAlert) {
            const seconds = parseFloat(value);
            input.title = `${seconds.toFixed(2)} sekundit`;
        }
    } else {
        input.classList.add('error');
        if (showAlert) {
            input.title = 'Sisesta aeg formaadis: sekundid.sajandikud (nt. 65.42)';
        }
    }
    
    return isValid;
}

function validateJumpingTimeFormat(timeString) {
    if (!timeString) return true;
    
    const cleaned = timeString.replace(/s$/, '').replace(',', '.');
    
    if (!/^(\d{1,3})(\.\d{1,2})?$/.test(cleaned)) {
        return false;
    }
    
    const seconds = parseFloat(cleaned);
    return seconds >= 5 && seconds <= 600;
}

// LISATUD: Distantsi seadmise funktsioon
function setDistance(distance, buttonElement) {
    const distanceInput = document.getElementById('distance');
    if (distanceInput) {
        distanceInput.value = distance;
        distanceInput.focus();
        
        // Visual feedback
        const presetButtons = document.querySelectorAll('.distance-presets .btn-preset');
        presetButtons.forEach(btn => btn.classList.remove('active'));
        
        if (buttonElement) {
            buttonElement.classList.add('active');
            setTimeout(() => buttonElement.classList.remove('active'), 200);
        }
        
        // Arvuta kiirus kui aeg on sisestatud
        calculateSpeedPreview();
    }
}

// LISATUD: Kiiruse eelvaate arvutamine
function calculateSpeedPreview() {
    const distanceInput = document.getElementById('distance');
    const timeInput = document.getElementById('time_input_endurance');
    const speedPreview = document.getElementById('speed_preview');
    const calculatedSpeed = document.getElementById('calculated_speed');
    
    if (!distanceInput || !timeInput || !speedPreview || !calculatedSpeed) return;
    
    const distance = parseFloat(distanceInput.value);
    const timeString = timeInput.value.trim();
    
    if (distance > 0 && timeString) {
        // Parsi aeg sekunditeks
        const timeSeconds = parseTimeStringToSeconds(timeString);
        
        if (timeSeconds > 0) {
            // Arvuta kiirus
            const timeHours = timeSeconds / 3600;
            const speedKmh = distance / timeHours;
            
            calculatedSpeed.textContent = speedKmh.toFixed(2) + ' km/h';
            speedPreview.style.display = 'block';
        } else {
            speedPreview.style.display = 'none';
        }
    } else {
        speedPreview.style.display = 'none';
    }
}

// Helper funktsioon aja parsimiseks
function parseTimeStringToSeconds(timeString) {
    const parts = timeString.split(':');
    
    if (parts.length === 3) {
        // h:mm:ss
        const hours = parseInt(parts[0]) || 0;
        const minutes = parseInt(parts[1]) || 0;
        const seconds = parseInt(parts[2]) || 0;
        return hours * 3600 + minutes * 60 + seconds;
    } else if (parts.length === 2) {
        // mm:ss
        const minutes = parseInt(parts[0]) || 0;
        const seconds = parseInt(parts[1]) || 0;
        return minutes * 60 + seconds;
    }
    
    return 0;
}

// PARANDATUD: editResult funktsioon 
function editResult(result) {
    // Fill basic form data
    document.getElementById('result_id').value = result.id;
    document.getElementById('userId').value = result.userId;
    document.getElementById('modalCompetitionId').value = result.competitionId;
    document.getElementById('placement').value = result.placement || '';
    document.getElementById('finished').checked = result.finished == 1;
    document.getElementById('notes').value = result.notes || '';
    
    // Update competition disciplines
    updateCompetitionDisciplines();
    
    // Set discipline after delay
    setTimeout(() => {
        document.getElementById('modalDiscipline').value = result.discipline;
        toggleDisciplineFields();
        
        // Fill discipline-specific fields
        setTimeout(() => {
            if (result.discipline === 'koolisoit') {
                document.getElementById('percentage').value = result.percentage || '';
                document.getElementById('scheme').value = result.scheme || '';
            } else if (result.discipline === 'takistussoit') {
                document.getElementById('faultPoints').value = result.faultPoints || '';
                document.getElementById('height').value = result.height || '';
                
                // PARANDATUD: Takistussõidu aja täitmine
                if (result.time_seconds) {
                    const jumpingTimeInput = document.getElementById('time_input_jumping');
                    if (jumpingTimeInput) {
                        // Kuvame sekundites kahe kümnendkohaga
                        jumpingTimeInput.value = parseFloat(result.time_seconds).toFixed(2);
                    }
                }
            } else if (result.discipline === 'kestvusratsutamine') {
                document.getElementById('distance').value = result.distance || '';
                document.getElementById('pulse').value = result.pulse || '';
                
                // Kestvusratsutamise aeg jääb samaks
                if (result.time_seconds) {
                    const enduranceTimeInput = document.getElementById('time_input_endurance');
                    if (enduranceTimeInput) {
                        enduranceTimeInput.value = formatSecondsToInput(result.time_seconds, true);
                    }
                }
                
                // LISATUD: Arvuta kiirus eelvaatesse
                setTimeout(calculateSpeedPreview, 100);
            }
        }, 100);
    }, 200);
    
    // Update modal
    document.getElementById('modalTitle').textContent = 'Muuda tulemust';
    document.getElementById('saveButtonText').textContent = 'Salvesta muudatused';
    
    openModal('resultModal');
}

// Helper funktsioon kestvusratsutamise aja jaoks (jääb samaks)
function formatSecondsToInput(seconds, includeHours = false) {
    if (!seconds) return '';
    
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;
    
    if (includeHours) {
        return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    } else {
        return `${minutes}:${secs.toString().padStart(2, '0')}`;
    }
}

// Kõrguse seadmise funktsioon (jääb samaks)
function setHeight(height, buttonElement) {
    const heightInput = document.getElementById('height');
    if (heightInput) {
        heightInput.value = height;
        heightInput.focus();
        
        // Visual feedback
        const presetButtons = document.querySelectorAll('.btn-preset');
        presetButtons.forEach(btn => btn.classList.remove('active'));
        
        if (buttonElement) {
            buttonElement.classList.add('active');
            setTimeout(() => buttonElement.classList.remove('active'), 200);
        }
    }
}
</script>
<link rel="stylesheet" href="<?php echo url('assets/css/admin-results.css'); ?>">
<?php include '../includes/footer.php'; ?>