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

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

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

// Töötle võistluse lisamist/muutmist
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_competition'])) {
    $competition_id = getPost('competition_id');
    $name = getPost('name');
    $location = getPost('location');
    $selected_disciplines = $_POST['disciplines'] ?? [];
    $description = getPost('description');
    
    // UUENDATUD: Multi-day toe lisamine
    $is_multi_day = isset($_POST['is_multi_day']) ? 1 : 0;
    $start_date = null;
    $end_date = null;
    $legacy_date = null; // Tagasiühilduvus
    
    if ($is_multi_day) {
        $start_date = getPost('start_date');
        $end_date = getPost('end_date');
        
        if (empty($start_date) || empty($end_date)) {
            $error = 'Mitme päeva pikkuse võistluse puhul on algus- ja lõppkuupäev kohustuslikud';
        } elseif ($start_date > $end_date) {
            $error = 'Alguskuupäev ei saa olla hilisem kui lõppkuupäev';
        } else {
            $legacy_date = $start_date; // Vana süsteemi tugi
        }
    } else {
        $legacy_date = getPost('date');
        $start_date = $legacy_date;
        $end_date = $legacy_date;
    }
    
    if (empty($name) || empty($legacy_date) || empty($selected_disciplines)) {
        $error = 'Nimi, kuupäev ja vähemalt üks distsipliin on kohustuslikud';
    } else {
        // Kontrolli et kõik valitud distsipliinid on kehtivad
        $valid_disciplines = ['koolisoit', 'takistussoit', 'kestvusratsutamine'];
        foreach ($selected_disciplines as $disc) {
            if (!in_array($disc, $valid_disciplines)) {
                $error = 'Kehtetu distsipliin: ' . $disc;
                break;
            }
        }
        
        if (!$error) {
            try {
                // Valmista ette andmed
                $disciplines_json = json_encode($selected_disciplines);
                $primary_discipline = $selected_disciplines[0]; // Esimene on peamine (tagasiühilduvuseks)
                
                if ($competition_id) {
                    // Uuenda olemasolevat võistlust
                    $stmt = $pdo->prepare("
                        UPDATE competitions SET
                            name = ?, date = ?, start_date = ?, end_date = ?, is_multi_day = ?,
                            location = ?, discipline = ?, disciplines = ?, description = ?, updatedAt = CURRENT_TIMESTAMP
                        WHERE id = ?
                    ");
                    $stmt->execute([
                        $name, $legacy_date, $start_date, $end_date, $is_multi_day,
                        $location, $primary_discipline, $disciplines_json, $description, $competition_id
                    ]);
                    $success = 'Võistluse andmed edukalt uuendatud!';
                    logActivity($_SESSION['user_id'], 'competition_updated', "Competition '$name' updated with disciplines: " . implode(', ', $selected_disciplines));
                } else {
                    // Lisa uus võistlus
                    $stmt = $pdo->prepare("
                        INSERT INTO competitions (name, date, start_date, end_date, is_multi_day, location, discipline, disciplines, description)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ");
                    $stmt->execute([
                        $name, $legacy_date, $start_date, $end_date, $is_multi_day,
                        $location, $primary_discipline, $disciplines_json, $description
                    ]);
                    $success = 'Uus võistlus edukalt lisatud!';
                    logActivity($_SESSION['user_id'], 'competition_created', "Competition '$name' created with disciplines: " . implode(', ', $selected_disciplines));
                }
                
            } catch(PDOException $e) {
                $error = 'Võistluse salvestamine ebaõnnestus: ' . $e->getMessage();
                error_log('Competition save error: ' . $e->getMessage());
            }
        }
    }
}

// Töötle võistluse kustutamist
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_competition'])) {
    $competition_id = getPost('competition_id');
    
    try {
        // Kontrolli kas võistlusel on tulemusi
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM results WHERE competitionId = ?");
        $stmt->execute([$competition_id]);
        $results_count = $stmt->fetch()['count'];
        
        if ($results_count > 0) {
            $error = "Võistlust ei saa kustutada, kuna sellel on $results_count tulemust. Kustuta esmalt tulemused.";
        } else {
            $stmt = $pdo->prepare("DELETE FROM competitions WHERE id = ?");
            $stmt->execute([$competition_id]);
            $success = 'Võistlus edukalt kustutatud!';
            logActivity($_SESSION['user_id'], 'competition_deleted', "Competition deleted (ID: $competition_id)");
        }
        
    } catch(PDOException $e) {
        $error = 'Võistluse kustutamine ebaõnnestus: ' . $e->getMessage();
    }
}

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

// Lae võistlused
$competitions = [];
try {
    $where_conditions = ["strftime('%Y', COALESCE(start_date, date)) = ?"];
    $params = [$year];
    
    // UUENDATUD: otsing disciplines JSON väljast
    if ($discipline_filter !== 'all') {
        $where_conditions[] = "(discipline = ? OR disciplines LIKE ?)";
        $params[] = $discipline_filter;
        $params[] = "%\"$discipline_filter\"%";
    }
    
    if (!empty($search)) {
        $where_conditions[] = "(name LIKE ? OR location LIKE ?)";
        $search_param = "%$search%";
        $params[] = $search_param;
        $params[] = $search_param;
    }
    
    $where_clause = implode(' AND ', $where_conditions);
    
    $stmt = $pdo->prepare("
        SELECT c.*, 
        (SELECT COUNT(*) FROM results WHERE competitionId = c.id) as results_count,
        (SELECT COUNT(DISTINCT userId) FROM results WHERE competitionId = c.id) as participants_count
        FROM competitions c
        WHERE $where_clause
        ORDER BY COALESCE(c.start_date, c.date) DESC
    ");
    $stmt->execute($params);
    $competitions = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Parsi disciplines JSON
    foreach ($competitions as &$competition) {
        if ($competition['disciplines']) {
            $competition['disciplines_array'] = json_decode($competition['disciplines'], true) ?: [$competition['discipline']];
        } else {
            $competition['disciplines_array'] = [$competition['discipline']];
        }
    }
    
} catch(PDOException $e) {
    $error = 'Võistluste laadimine ebaõnnestus: ' . $e->getMessage();
    error_log('Competitions load error: ' . $e->getMessage());
}

$page_title = 'Admin - Võistluste haldamine';
$page_description = 'Halda võistlusi ja nende detaile.';

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

<main class="admin-competitions-main">
    <div class="container">
        <!-- Header -->
        <div class="page-header">
            <div class="page-header-content">
                <h1 class="page-title">Võistluste haldamine</h1>
                <p class="page-subtitle">
                    Loo ja halda võistlusi ning vaata osalejaid
                </p>
            </div>
            <div class="page-actions">
                <button onclick="openModal('competitionModal')" class="btn btn-primary">
                    <i class="icon-plus"></i>
                    <span>Lisa võistlus</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 ja otsing -->
        <div class="filters-section">
            <form method="GET" class="filters-form">
                <div class="filters-grid">
                    <div class="filter-group">
                        <label for="search" class="filter-label">Otsing</label>
                        <input type="text" id="search" name="search" class="filter-input" 
                               placeholder="Otsi võistluse nime või asukoha järgi..."
                               value="<?php echo htmlspecialchars($search); ?>">
                    </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="year" class="filter-label">Aasta</label>
                        <select name="year" id="year" class="filter-select">
                            <?php for ($y = date('Y') + 1; $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-search"></i>
                            <span>Otsi</span>
                        </button>
                    </div>
                </div>
            </form>
        </div>

        <!-- Võistluste loend -->
        <div class="competitions-container">
            <div class="competitions-header">
                <h2 class="competitions-title">
                    Võistlused <?php echo $year; ?> (<?php echo count($competitions); ?>)
                </h2>
            </div>

            <?php if (empty($competitions)): ?>
                <div class="empty-state">
                    <div class="empty-icon">
                        <i class="icon-calendar"></i>
                    </div>
                    <h3>Võistlusi ei leitud</h3>
                    <p>Valitud kriteeriumide järgi ei leitud ühtegi võistlust.</p>
                    <button onclick="openModal('competitionModal')" class="btn btn-primary">
                        <i class="icon-plus"></i>
                        <span>Lisa esimene võistlus</span>
                    </button>
                </div>
            <?php else: ?>
                <div class="competitions-grid">
                    <?php foreach ($competitions as $competition): ?>
                        <div class="competition-card">
                            <div class="competition-header">
                                <!-- UUENDATUD: Multi-day kuupäeva kuvamine -->
                                <div class="competition-date">
                                    <?php if ($competition['is_multi_day'] && $competition['start_date'] !== $competition['end_date']): ?>
                                        <!-- Multi-day display -->
                                        <div class="date-range">
                                            <div class="date-start"><?php echo date('d.m', strtotime($competition['start_date'])); ?></div>
                                            <div class="date-separator">-</div>
                                            <div class="date-end"><?php echo date('d.m', strtotime($competition['end_date'])); ?></div>
                                        </div>
                                        <div class="date-year"><?php echo date('Y', strtotime($competition['start_date'])); ?></div>
                                        <div class="date-duration"><?php echo getCompetitionDays($competition); ?> päeva</div>
                                    <?php else: ?>
                                        <!-- Single day display -->
                                        <div class="date-day"><?php echo date('d', strtotime($competition['start_date'] ?: $competition['date'])); ?></div>
                                        <div class="date-month"><?php echo date('M', strtotime($competition['start_date'] ?: $competition['date'])); ?></div>
                                        <div class="date-year"><?php echo date('Y', strtotime($competition['start_date'] ?: $competition['date'])); ?></div>
                                    <?php endif; ?>
                                </div>
                                <div class="competition-status">
                                    <?php 
                                    $today = date('Y-m-d');
                                    $comp_start = $competition['start_date'] ?: $competition['date'];
                                    $comp_end = $competition['end_date'] ?: $competition['date'];
                                    
                                    if ($comp_start > $today) {
                                        echo '<span class="status-badge upcoming">Tulekul</span>';
                                    } elseif ($comp_start <= $today && $comp_end >= $today) {
                                        echo '<span class="status-badge today">Toimub</span>';
                                    } else {
                                        echo '<span class="status-badge past">Toimunud</span>';
                                    }
                                    ?>
                                </div>
                            </div>

                            <div class="competition-content">
                                <h3 class="competition-name">
                                    <?php echo htmlspecialchars($competition['name']); ?>
                                </h3>
                                
                                <div class="competition-details">
                                    <div class="detail-item">
                                        <i class="icon-map-pin"></i>
                                        <span><?php echo htmlspecialchars($competition['location'] ?: 'Asukoht määramata'); ?></span>
                                    </div>
                                    
                                    <!-- UUENDATUD: kuvab kõik distsipliinid -->
                                    <div class="detail-item disciplines-item">
                                        <i class="icon-target"></i>
                                        <div class="disciplines-list">
                                            <?php foreach ($competition['disciplines_array'] as $disc): ?>
                                                <span class="discipline-badge <?php echo $disc; ?>">
                                                    <?php echo getDisciplineName($disc); ?>
                                                </span>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                    
                                    <div class="detail-item">
                                        <i class="icon-users"></i>
                                        <span><?php echo $competition['participants_count']; ?> osalejat</span>
                                    </div>
                                    
                                    <div class="detail-item">
                                        <i class="icon-trophy"></i>
                                        <span><?php echo $competition['results_count']; ?> tulemust</span>
                                    </div>
                                </div>

                                <?php if ($competition['description']): ?>
                                    <div class="competition-description">
                                        <?php echo nl2br(htmlspecialchars($competition['description'])); ?>
                                    </div>
                                <?php endif; ?>
                            </div>

                            <div class="competition-actions">
                                <button onclick="editCompetition(<?php echo htmlspecialchars(json_encode($competition)); ?>)" 
                                        class="btn btn-outline btn-sm">
                                    <i class="icon-edit"></i>
                                    <span>Muuda</span>
                                </button>
                                
                                <a href="<?php echo url('admin/results.php?competition=' . $competition['id']); ?>" 
                                   class="btn btn-primary btn-sm">
                                    <i class="icon-trophy"></i>
                                    <span>Tulemused</span>
                                </a>
                                
                                <?php if ($competition['results_count'] == 0): ?>
                                    <form method="POST" style="display: inline;" 
                                          onsubmit="return confirm('Kas oled kindel, et tahad selle võistluse kustutada?')">
                                        <input type="hidden" name="competition_id" value="<?php echo $competition['id']; ?>">
                                        <button type="submit" name="delete_competition" class="btn btn-danger btn-sm">
                                            <i class="icon-trash"></i>
                                            <span>Kustuta</span>
                                        </button>
                                    </form>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Võistluse modal -->
    <div id="competitionModal" class="modal">
        <div class="modal-overlay">
            <div class="modal-content">
                <div class="modal-header">
                    <h3 class="modal-title" id="modalTitle">Lisa võistlus</h3>
                    <button class="modal-close" onclick="closeModal('competitionModal')">
                        <i class="icon-x"></i>
                    </button>
                </div>

                <form method="POST" class="modal-form" id="competitionForm">
                    <input type="hidden" name="competition_id" id="competition_id">
                    
                    <div class="form-group">
                        <label for="name" class="form-label">Võistluse nimi *</label>
                        <input type="text" id="name" name="name" class="form-input" 
                               placeholder="Sisesta võistluse nimi" required>
                    </div>

                    <!-- UUENDATUD: Multi-day kuupäevade valik -->
                    <div class="form-group">
                        <label class="checkbox-label">
                            <input type="checkbox" id="is_multi_day" name="is_multi_day" class="checkbox-input">
                            <span class="checkbox-custom"></span>
                            <span class="checkbox-text">Mitme päeva pikkune võistlus</span>
                        </label>
                    </div>

                    <div id="single-date-field" class="form-group">
                        <label for="date" class="form-label">Kuupäev *</label>
                        <input type="date" id="date" name="date" class="form-input" required>
                    </div>

                    <div id="multi-date-fields" class="form-grid" style="display: none;">
                        <div class="form-group">
                            <label for="start_date" class="form-label">Alguskuupäev *</label>
                            <input type="date" id="start_date" name="start_date" class="form-input">
                        </div>
                        <div class="form-group">
                            <label for="end_date" class="form-label">Lõppkuupäev *</label>
                            <input type="date" id="end_date" name="end_date" class="form-input">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="location" class="form-label">Asukoht</label>
                        <input type="text" id="location" name="location" class="form-input" 
                               placeholder="Sisesta võistluse asukoht">
                    </div>

                    <!-- Mitme distsipliini valik -->
                    <div class="form-group">
                        <label class="form-label">Distsipliinid * <span class="label-help">(vali vähemalt üks)</span></label>
                        <div class="disciplines-selector">
                            <label class="discipline-checkbox">
                                <input type="checkbox" name="disciplines[]" value="koolisoit" class="checkbox-input">
                                <span class="checkbox-custom"></span>
                                <span class="discipline-badge koolisoit">Koolisõit</span>
                            </label>
                            
                            <label class="discipline-checkbox">
                                <input type="checkbox" name="disciplines[]" value="takistussoit" class="checkbox-input">
                                <span class="checkbox-custom"></span>
                                <span class="discipline-badge takistussoit">Takistussõit</span>
                            </label>
                            
                            <label class="discipline-checkbox">
                                <input type="checkbox" name="disciplines[]" value="kestvusratsutamine" class="checkbox-input">
                                <span class="checkbox-custom"></span>
                                <span class="discipline-badge kestvusratsutamine">Kestvusratsutamine</span>
                            </label>
                        </div>
                        <div class="form-help">Vali kõik distsipliinid, mis sellel võistlusel toimuvad</div>
                    </div>

                    <div class="form-group">
                        <label for="description" class="form-label">Kirjeldus</label>
                        <textarea id="description" name="description" class="form-textarea" rows="4" 
                                  placeholder="Võistluse kirjeldus, reeglid, lisainfo..."></textarea>
                    </div>

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

<style>
/* Admin Competitions Page Styles */
.admin-competitions-main {
    padding: var(--spacing-8) 0;
    min-height: 100vh;
    background: var(--gray-50);
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    margin-bottom: var(--spacing-8);
    gap: var(--spacing-4);
}

.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: 2fr repeat(2, 1fr) auto;
    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-input,
.filter-select {
    padding: var(--spacing-3);
    border: 1px solid var(--gray-300);
    border-radius: var(--radius);
    font-size: var(--font-size-sm);
    transition: border-color var(--transition-fast);
}

.filter-input:focus,
.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);
}

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

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

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

/* Competitions Grid */
.competitions-grid {
    padding: var(--spacing-6);
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
    gap: var(--spacing-6);
}

.competition-card {
    border: 1px solid var(--gray-200);
    border-radius: var(--radius-lg);
    overflow: hidden;
    transition: all var(--transition-fast);
    background: white;
}

.competition-card:hover {
    border-color: var(--primary-color);
    box-shadow: var(--shadow-md);
    transform: translateY(-2px);
}

.competition-header {
    padding: var(--spacing-4);
    background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
    color: white;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.competition-date {
    text-align: center;
}

/* UUENDATUD: Multi-day kuupäeva kuvamise stiilid */
.date-range {
    display: flex;
    align-items: center;
    gap: 2px;
    font-weight: 700;
    line-height: 1;
}

.date-separator {
    font-size: 0.8em;
    opacity: 0.8;
}

.date-duration {
    font-size: var(--font-size-xs);
    opacity: 0.8;
    text-align: center;
}

.date-day {
    font-size: var(--font-size-2xl);
    font-weight: 700;
    line-height: 1;
}

.date-month {
    font-size: var(--font-size-sm);
    text-transform: uppercase;
    opacity: 0.9;
}

.date-year {
    font-size: var(--font-size-xs);
    opacity: 0.8;
}

.status-badge {
    padding: var(--spacing-1) var(--spacing-2);
    border-radius: var(--radius-sm);
    font-size: var(--font-size-xs);
    font-weight: 500;
}

.status-badge.upcoming {
    background: rgba(255, 255, 255, 0.2);
    color: white;
}

.status-badge.today {
    background: var(--warning-color);
    color: white;
}

.status-badge.past {
    background: rgba(255, 255, 255, 0.15);
    color: rgba(255, 255, 255, 0.8);
}

.competition-content {
    padding: var(--spacing-5);
}

.competition-name {
    margin: 0 0 var(--spacing-4);
    font-size: var(--font-size-lg);
    font-weight: 600;
    color: var(--gray-900);
}

.competition-details {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: var(--spacing-3);
    margin-bottom: var(--spacing-4);
}

.detail-item {
    display: flex;
    align-items: center;
    gap: var(--spacing-2);
    font-size: var(--font-size-sm);
    color: var(--gray-600);
}

.detail-item i {
    color: var(--primary-color);
    width: 16px;
}

/* Mitme distsipliini kuvamine */
.disciplines-item {
    grid-column: 1 / -1; /* Võta kogu laius */
    align-items: flex-start;
}

.disciplines-list {
    display: flex;
    gap: var(--spacing-2);
    flex-wrap: wrap;
}

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

.discipline-badge.koolisoit { background: var(--primary-color); }
.discipline-badge.takistussoit { background: var(--success-color); }
.discipline-badge.kestvusratsutamine { background: #8b5cf6; }

.competition-description {
    font-size: var(--font-size-sm);
    color: var(--gray-600);
    line-height: 1.5;
    margin-bottom: var(--spacing-4);
    padding: var(--spacing-3);
    background: var(--gray-50);
    border-radius: var(--radius);
}

.competition-actions {
    padding: var(--spacing-4);
    border-top: 1px solid var(--gray-200);
    display: flex;
    gap: var(--spacing-2);
    justify-content: flex-end;
}

.btn-sm {
    padding: var(--spacing-2) var(--spacing-3);
    font-size: var(--font-size-sm);
}

/* FIX: Make "Muuda" button more readable */
.btn-outline {
    background: white;
    color: var(--primary-color);
    border: 1px solid var(--primary-color);
}

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

/* Modal Styles */
.modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1000;
    display: none;
}

.modal.show {
    display: flex;
}

.modal-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    padding: var(--spacing-4);
}

.modal-content {
    background: white;
    border-radius: var(--radius-lg);
    box-shadow: var(--shadow-xl);
    width: 100%;
    max-width: 600px;
    max-height: 90vh;
    overflow-y: auto;
}

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

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

/* FIX: Make modal close button more visible, especially on mobile */
.modal-close {
    width: 32px;
    height: 32px;
    border: none;
    background: rgba(0, 0, 0, 0.1);
    border-radius: var(--radius);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: var(--gray-700);
    transition: all var(--transition-fast);
    z-index: 1010;
}

.modal-close:hover {
    background: rgba(0, 0, 0, 0.2);
    color: var(--gray-900);
}

.modal-close i {
    font-size: 18px;
}

.modal-form {
    padding: var(--spacing-6);
}

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

.form-group {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-2);
    margin-bottom: var(--spacing-4);
}

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

.label-help {
    font-weight: 400;
    color: var(--gray-500);
    font-size: var(--font-size-xs);
}

.form-input,
.form-select,
.form-textarea {
    padding: var(--spacing-3);
    border: 1px solid var(--gray-300);
    border-radius: var(--radius);
    font-size: var(--font-size-sm);
    transition: border-color var(--transition-fast);
}

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

.form-textarea {
    resize: vertical;
    font-family: inherit;
}

.form-help {
    font-size: var(--font-size-xs);
    color: var(--gray-500);
    margin-top: var(--spacing-1);
}

/* Distsipliinide valik */
.disciplines-selector {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-3);
    padding: var(--spacing-4);
    background: var(--gray-50);
    border-radius: var(--radius);
    border: 1px solid var(--gray-200);
}

.discipline-checkbox {
    display: flex;
    align-items: center;
    gap: var(--spacing-3);
    cursor: pointer;
    padding: var(--spacing-2);
    border-radius: var(--radius);
    transition: background-color var(--transition-fast);
}

.discipline-checkbox:hover {
    background: white;
}

.checkbox-input {
    display: none;
}

.checkbox-custom {
    width: 18px;
    height: 18px;
    border: 2px solid var(--gray-300);
    border-radius: var(--radius-sm);
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all var(--transition-fast);
    flex-shrink: 0;
}

.checkbox-input:checked + .checkbox-custom {
    background-color: var(--primary-color);
    border-color: var(--primary-color);
}

.checkbox-input:checked + .checkbox-custom::after {
    content: '✓';
    color: white;
    font-size: 12px;
    font-weight: bold;
}

.checkbox-label {
    display: flex;
    align-items: center;
    gap: var(--spacing-2);
    cursor: pointer;
    font-size: var(--font-size-sm);
    margin-bottom: var(--spacing-4);
}

.modal-actions {
    display: flex;
    justify-content: flex-end;
    gap: var(--spacing-3);
    margin-top: var(--spacing-6);
    padding-top: var(--spacing-4);
    border-top: 1px solid var(--gray-200);
}

/* Empty State */
.empty-state {
    text-align: center;
    padding: var(--spacing-16) var(--spacing-8);
}

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

/* Responsive */
@media (max-width: 1024px) {
    .filters-grid {
        grid-template-columns: 1fr;
    }
    
    .competitions-grid {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 768px) {
    .page-header {
        flex-direction: column;
        align-items: stretch;
        gap: var(--spacing-4);
    }
    
    .competition-details {
        grid-template-columns: 1fr;
    }
    
    .competition-actions {
        flex-direction: column;
    }
    
    .form-grid {
        grid-template-columns: 1fr;
    }
    
    .modal-actions {
        flex-direction: column;
    }
    
    /* FIX: Ensure better visibility for modal close button on mobile */
    .modal-close {
        width: 40px;
        height: 40px;
        background: rgba(0, 0, 0, 0.15);
        color: black;
        position: absolute;
        right: 10px;
        top: 10px;
    }
    
    .modal-close i {
        font-size: 22px;
    }
}
</style>

<script>
// Multi-day kuupäevade toggle
function toggleDateFields() {
    const isMultiDay = document.getElementById('is_multi_day').checked;
    const singleField = document.getElementById('single-date-field');
    const multiFields = document.getElementById('multi-date-fields');
    
    if (isMultiDay) {
        singleField.style.display = 'none';
        multiFields.style.display = 'grid';
        
        // Eemalda required single date väljalt
        document.getElementById('date').removeAttribute('required');
        
        // Lisa required multi date väljadele
        document.getElementById('start_date').setAttribute('required', 'required');
        document.getElementById('end_date').setAttribute('required', 'required');
    } else {
        singleField.style.display = 'block';
        multiFields.style.display = 'none';
        
        // Lisa required single date väljale
        document.getElementById('date').setAttribute('required', 'required');
        
        // Eemalda required multi date väljadelt
        document.getElementById('start_date').removeAttribute('required');
        document.getElementById('end_date').removeAttribute('required');
    }
}

function editCompetition(competition) {
    // Fill form with competition data
    document.getElementById('competition_id').value = competition.id;
    document.getElementById('name').value = competition.name;
    document.getElementById('location').value = competition.location || '';
    document.getElementById('description').value = competition.description || '';
    
    // UUENDATUD: Multi-day toe lisamine
    const isMultiDay = competition.is_multi_day == 1;
    document.getElementById('is_multi_day').checked = isMultiDay;
    
    if (isMultiDay) {
        document.getElementById('start_date').value = competition.start_date || '';
        document.getElementById('end_date').value = competition.end_date || '';
        toggleDateFields();
    } else {
        document.getElementById('date').value = competition.start_date || competition.date || '';
        toggleDateFields();
    }
    
    // Täida distsipliinide checkboxid
    const disciplineCheckboxes = document.querySelectorAll('input[name="disciplines[]"]');
    disciplineCheckboxes.forEach(checkbox => {
        checkbox.checked = false;
    });
    
    // Märgi valitud distsipliinid
    if (competition.disciplines_array) {
        competition.disciplines_array.forEach(discipline => {
            const checkbox = document.querySelector(`input[name="disciplines[]"][value="${discipline}"]`);
            if (checkbox) {
                checkbox.checked = true;
            }
        });
    } else {
        // Tagasiühilduvus
        const checkbox = document.querySelector(`input[name="disciplines[]"][value="${competition.discipline}"]`);
        if (checkbox) {
            checkbox.checked = true;
        }
    }
    
    // Update modal title and button
    document.getElementById('modalTitle').textContent = 'Muuda võistlust';
    document.getElementById('saveButtonText').textContent = 'Salvesta muudatused';
    
    openModal('competitionModal');
}

function resetForm() {
    document.getElementById('competitionForm').reset();
    document.getElementById('competition_id').value = '';
    document.getElementById('modalTitle').textContent = 'Lisa võistlus';
    document.getElementById('saveButtonText').textContent = 'Lisa võistlus';
    
    // Eemalda kõik distsipliinide valikud
    const disciplineCheckboxes = document.querySelectorAll('input[name="disciplines[]"]');
    disciplineCheckboxes.forEach(checkbox => {
        checkbox.checked = false;
    });
    
    // Reset multi-day fields
    document.getElementById('is_multi_day').checked = false;
    toggleDateFields();
}

// Vormi valideerimine
function validateCompetitionForm() {
    const selectedDisciplines = document.querySelectorAll('input[name="disciplines[]"]:checked');
    
    if (selectedDisciplines.length === 0) {
        alert('Palun vali vähemalt üks distsipliin!');
        return false;
    }
    
    return true;
}

// Event listeners
document.addEventListener('DOMContentLoaded', function() {
    // Multi-day checkbox listener
    const multiDayCheckbox = document.getElementById('is_multi_day');
    if (multiDayCheckbox) {
        multiDayCheckbox.addEventListener('change', toggleDateFields);
    }
    
    // Reset form when opening modal for new competition
    const addButton = document.querySelector('button[onclick="openModal(\'competitionModal\')"]');
    if (addButton) {
        addButton.addEventListener('click', resetForm);
    }
    
    // Auto-focus name input when modal opens
    const modal = document.getElementById('competitionModal');
    if (modal) {
        modal.addEventListener('show', function() {
            setTimeout(() => {
                const nameInput = document.getElementById('name');
                if (nameInput) {
                    nameInput.focus();
                }
            }, 100);
        });
    }
    
    // Auto-submit form when filters change
    const filterSelects = document.querySelectorAll('.filter-select');
    filterSelects.forEach(select => {
        select.addEventListener('change', function() {
            setTimeout(() => this.closest('form').submit(), 100);
        });
    });
    
    // Vormi valideerimise lisamine
    const competitionForm = document.getElementById('competitionForm');
    if (competitionForm) {
        competitionForm.addEventListener('submit', function(e) {
            if (!validateCompetitionForm()) {
                e.preventDefault();
            }
        });
    }
});
</script>

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