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

// Nõua sisselogimist ja sportlase õigusi
requireLogin();
if (!isAthlete()) {
    header('Location: ' . url());
    exit;
}

$user_id = $_SESSION['user_id'];
$current_year = date('Y');
$error = '';

// Lisa extra CSS head sektsiooni
$extra_head_content = '<link rel="stylesheet" href="' . url('assets/css/dashboard.css') . '">';

// Lae kasutaja andmed
try {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user) {
        throw new Exception('Kasutajat ei leitud');
    }
    
    $user['ageGroup'] = getAgeGroup($user['birthDate'], $current_year);
    
} catch(Exception $e) {
    $error = 'Kasutaja andmete laadimine ebaõnnestus';
    error_log('User data error: ' . $e->getMessage());
}

// Lae viimased tulemused
$recent_results = [];
try {
    $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 DESC
        LIMIT 5
    ");
    $stmt->execute([$user_id, $current_year]);
    $recent_results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch(PDOException $e) {
    error_log('Recent results error: ' . $e->getMessage());
}

// Lae hooaja statistika distsipliinide kaupa
$disciplines = ['koolisoit', 'takistussoit', 'kestvusratsutamine'];
$season_stats = [];
$positions = [];

foreach ($disciplines as $discipline) {
    try {
        // Lae sportlase tulemused selles distsipliinis
        $stmt = $pdo->prepare("
            SELECT r.points, r.finished, c.date, c.name as competitionName
            FROM results r
            JOIN competitions c ON r.competitionId = c.id
            WHERE r.userId = ? AND r.discipline = ? AND strftime('%Y', c.date) = ?
            ORDER BY c.date DESC
        ");
        $stmt->execute([$user_id, $discipline, $current_year]);
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Konverteeri punktid floatiks
        foreach ($results as &$result) {
            $result['points'] = (float)$result['points'];
        }
        
        $season_stats[$discipline] = calculateSeasonStandings($results, $discipline);
        
        // Leia positsioon tabelis
        $stmt = $pdo->prepare("
            SELECT 
                u.id,
                SUM(r.points) as totalPoints,
                COUNT(r.id) as resultsCount
            FROM users u
            JOIN results r ON u.id = r.userId
            JOIN competitions c ON r.competitionId = c.id
            WHERE u.role = 'athlete' AND u.isActive = 1 
                AND r.discipline = ? AND strftime('%Y', c.date) = ?
            GROUP BY u.id
            HAVING resultsCount > 0
            ORDER BY totalPoints DESC
        ");
        $stmt->execute([$discipline, $current_year]);
        $rankings = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $position = null;
        foreach ($rankings as $index => $ranking) {
            if ($ranking['id'] == $user_id) {
                $position = $index + 1;
                break;
            }
        }
        $positions[$discipline] = $position;
        
    } catch(PDOException $e) {
        error_log("Season stats error for $discipline: " . $e->getMessage());
        $season_stats[$discipline] = [
            'total_points' => 0,
            'counted_results' => [],
            'all_results' => [],
            'starts_count' => 0,
            'max_starts' => 0
        ];
        $positions[$discipline] = null;
    }
}

// Lae treeningu statistika (viimased 30 päeva)
$training_stats = [];
try {
    $stmt = $pdo->prepare("
        SELECT 
            COUNT(*) as totalSessions,
            SUM(duration) as totalMinutes,
            AVG(mood) as avgMood
        FROM training_log
        WHERE userId = ? AND date >= date('now', '-30 days')
    ");
    $stmt->execute([$user_id]);
    $training_stats = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$training_stats['totalSessions']) {
        $training_stats = [
            'totalSessions' => 0,
            'totalMinutes' => 0,
            'avgMood' => 0
        ];
    }
    
} catch(PDOException $e) {
    error_log('Training stats error: ' . $e->getMessage());
    $training_stats = ['totalSessions' => 0, 'totalMinutes' => 0, 'avgMood' => 0];
}

$page_title = 'Minu ala - Armatuurlaud';
$page_description = 'Sportlase isiklik armatuurlaud koos tulemuste, statistika ja kiire ülevaatega.';

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

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

        <!-- Tervituse sektsioon -->
        <div class="welcome-section">
            <div class="welcome-content">
                <h1 class="welcome-title">
                    Tere tulemast, <?php echo htmlspecialchars($user['firstName']); ?>!
                </h1>
                <p class="welcome-subtitle">
                    <?php echo getAgeGroupName($user['ageGroup']); ?> • Hooaeg <?php echo $current_year; ?>
                </p>
            </div>
            <div class="welcome-avatar">
                <div class="avatar-circle">
                    <i class="icon-user"></i>
                </div>
            </div>
        </div>

        <!-- Kiire statistika -->
        <div class="quick-stats">
            <div class="stats-grid">
                <?php foreach ($disciplines as $discipline): ?>
                    <div class="stat-card discipline-card">
                        <div class="stat-header">
                            <div class="stat-icon discipline-<?php echo $discipline; ?>">
                                <i class="icon-<?php echo $discipline === 'koolisoit' ? 'target' : ($discipline === 'takistussoit' ? 'zap' : 'map'); ?>"></i>
                            </div>
                            <div class="stat-info">
                                <h3 class="stat-title"><?php echo getDisciplineName($discipline); ?></h3>
                                <div class="stat-position">
                                    #<?php echo $positions[$discipline] ?? '-'; ?> koht
                                </div>
                            </div>
                        </div>
                        <div class="stat-content">
                            <div class="stat-points">
                                <?php echo formatPoints($season_stats[$discipline]['total_points']); ?>
                            </div>
                            <div class="stat-details">
                                <?php echo $season_stats[$discipline]['starts_count']; ?> stardist 
                                <?php echo count($season_stats[$discipline]['counted_results']); ?> arvestatud
                            </div>
                        </div>
                        <div class="stat-progress">
                            <div class="progress-bar">
                                <div class="progress-fill" style="width: <?php echo ($season_stats[$discipline]['max_starts'] > 0) ? (count($season_stats[$discipline]['counted_results']) / $season_stats[$discipline]['max_starts']) * 100 : 0; ?>%"></div>
                            </div>
                            <div class="progress-text">
                                <?php echo count($season_stats[$discipline]['counted_results']); ?> / <?php echo $season_stats[$discipline]['max_starts']; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Põhisisu grid -->
        <div class="dashboard-grid">
            <!-- Vasakpoolne veerg - Tulemused -->
            <div class="dashboard-left">
                <!-- Viimased tulemused -->
                <div class="dashboard-card">
                    <div class="card-header">
                        <div class="card-title">
                            <i class="icon-trophy"></i>
                            <h2>Viimased tulemused</h2>
                        </div>
                        <a href="<?php echo url('athlete/results.php'); ?>" class="card-link">Vaata kõiki</a>
                    </div>
                    <div class="card-content">
                        <?php if (empty($recent_results)): ?>
                            <div class="empty-results">
                                <i class="icon-trophy"></i>
                                <p>Tulemusi pole veel lisatud</p>
                                <span>Tulemused lisatakse administraatori poolt pärast võistlusi</span>
                            </div>
                        <?php else: ?>
                            <div class="results-list">
                                <?php foreach ($recent_results as $result): ?>
                                    <div class="result-item">
                                        <div class="result-main">
                                            <div class="result-competition">
                                                <?php echo htmlspecialchars($result['competitionName']); ?>
                                            </div>
                                            <div class="result-meta">
                                                <span class="result-date">
                                                    <?php echo formatDate($result['competitionDate']); ?>
                                                </span>
                                                <span class="result-discipline discipline-<?php echo $result['discipline']; ?>">
                                                    <?php echo getDisciplineName($result['discipline']); ?>
                                                </span>
                                            </div>
                                        </div>
                                        <div class="result-points">
                                            <div class="points-value">
                                                <?php echo formatPoints($result['points']); ?>
                                            </div>
                                            <?php if ($result['placement']): ?>
                                                <div class="placement-value">
                                                    <?php echo $result['placement']; ?>. koht
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Hooaja progress -->
                <div class="dashboard-card">
                    <div class="card-header">
                        <div class="card-title">
                            <i class="icon-trending-up"></i>
                            <h2>Hooaja progress</h2>
                        </div>
                    </div>
                    <div class="card-content">
                        <div class="progress-list">
                            <?php foreach ($disciplines as $discipline): ?>
                                <div class="progress-item">
                                    <div class="progress-header">
                                        <span class="progress-label">
                                            <?php echo getDisciplineName($discipline); ?>
                                        </span>
                                        <span class="progress-count">
                                            <?php echo count($season_stats[$discipline]['counted_results']); ?> / <?php echo $season_stats[$discipline]['max_starts']; ?>
                                        </span>
                                    </div>
                                    <div class="progress-bar full-width">
                                        <div class="progress-fill" style="width: <?php echo ($season_stats[$discipline]['max_starts'] > 0) ? (count($season_stats[$discipline]['counted_results']) / $season_stats[$discipline]['max_starts']) * 100 : 0; ?>%"></div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Parempoolne veerg - Toimingud ja statistika -->
            <div class="dashboard-right">
                <!-- Kiired toimingud -->
                <div class="dashboard-card">
                    <div class="card-header">
                        <div class="card-title">
                            <i class="icon-zap"></i>
                            <h2>Kiired toimingud</h2>
                        </div>
                    </div>
                    <div class="card-content">
                        <div class="quick-actions">
                            <a href="<?php echo url('athlete/results.php'); ?>" class="action-card primary">
                                <div class="action-icon">
                                    <i class="icon-plus"></i>
                                </div>
                                <div class="action-content">
                                    <div class="action-title">Lisa tulemus</div>
                                    <div class="action-subtitle">Lisa enda võistluse tulemus</div>
                                </div>
                            </a>
                            
                            <!-- 🌟 PARANDATUD MOTIVATSIOONI KIIRLINK - ÜKS VÄRV NAGU TEISED -->
                            <a href="<?php echo url('athlete/motivation.php'); ?>" class="action-card">
                                <div class="action-icon">
                                    <i class="icon-star"></i>
                                </div>
                                <div class="action-content">
                                    <div class="action-title">🌟 Minu edusammud</div>
                                    <div class="action-subtitle">Saavutused ja väljakutsed</div>
                                </div>
                                <?php 
                                // Kontrolli kas on uusi saavutusi
                                try {
                                    $stmt = $pdo->prepare("
                                        SELECT COUNT(*) as new_count 
                                        FROM user_achievements 
                                        WHERE userId = ? AND unlocked_at >= datetime('now', '-24 hours')
                                    ");
                                    $stmt->execute([$user_id]);
                                    $new_achievements = $stmt->fetch()['new_count'];
                                    
                                    if ($new_achievements > 0): ?>
                                        <div class="action-badge"><?php echo $new_achievements; ?></div>
                                    <?php endif;
                                } catch (Exception $e) {
                                    // Ignore errors
                                }
                                ?>
                            </a>
                            
                            <a href="<?php echo url('athlete/training.php'); ?>" class="action-card">
                                <div class="action-icon">
                                    <i class="icon-calendar"></i>
                                </div>
                                <div class="action-content">
                                    <div class="action-title">Treeningu päevik</div>
                                    <div class="action-subtitle">Märgi üles tänaune treening</div>
                                </div>
                            </a>
                            
                            <a href="<?php echo url('athlete/horses.php'); ?>" class="action-card">
                                <div class="action-icon">
                                    <i class="icon-star"></i>
                                </div>
                                <div class="action-content">
                                    <div class="action-title">Minu hobused</div>
                                    <div class="action-subtitle">Halda hobuste andmeid</div>
                                </div>
                            </a>
                            
                            <a href="<?php echo url('athlete/results.php'); ?>" class="action-card">
                                <div class="action-icon">
                                    <i class="icon-trophy"></i>
                                </div>
                                <div class="action-content">
                                    <div class="action-title">Vaata tulemusi</div>
                                    <div class="action-subtitle">Kõik hooaja tulemused</div>
                                </div>
                            </a>
                            
                            <a href="<?php echo url('athlete/stats.php'); ?>" class="action-card">
                                <div class="action-icon">
                                    <i class="icon-trending-up"></i>
                                </div>
                                <div class="action-content">
                                    <div class="action-title">Minu insights</div>
                                    <div class="action-subtitle">Isiklikud mustrid ja soovitused</div>
                                </div>
                            </a>
                            
                            <a href="<?php echo url('athlete/stats.php'); ?>" class="action-card">
                                <div class="action-icon">
                                    <i class="icon-bar-chart"></i>
                                </div>
                                <div class="action-content">
                                    <div class="action-title">Detailne statistika</div>
                                    <div class="action-subtitle">Graafikud ja analüüs</div>
                                </div>
                            </a>
                        </div>
                    </div>
                </div>

                <!-- Treeningu statistika -->
                <div class="dashboard-card">
                    <div class="card-header">
                        <div class="card-title">
                            <i class="icon-activity"></i>
                            <h2>Treening (30 päeva)</h2>
                        </div>
                    </div>
                    <div class="card-content">
                        <div class="training-stats">
                            <div class="training-stat">
                                <div class="training-icon">
                                    <i class="icon-calendar"></i>
                                </div>
                                <div class="training-info">
                                    <div class="training-label">Treeningu kordi</div>
                                    <div class="training-value"><?php echo $training_stats['totalSessions']; ?></div>
                                </div>
                            </div>
                            
                            <div class="training-stat">
                                <div class="training-icon">
                                    <i class="icon-clock"></i>
                                </div>
                                <div class="training-info">
                                    <div class="training-label">Tunde kokku</div>
                                    <div class="training-value">
                                        <?php echo $training_stats['totalMinutes'] ? round($training_stats['totalMinutes'] / 60) : 0; ?>h
                                    </div>
                                </div>
                            </div>
                            
                            <div class="training-stat">
                                <div class="training-icon">
                                    <i class="icon-smile"></i>
                                </div>
                                <div class="training-info">
                                    <div class="training-label">Keskmine meeleolu</div>
                                    <div class="training-value">
                                        <?php echo $training_stats['avgMood'] ? number_format($training_stats['avgMood'], 1) : '0.0'; ?>/5
                                        <?php echo getMoodEmoji(round($training_stats['avgMood'])); ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- PARANDATUD: Saavutused - SAFE PHP KOOD -->
                <div class="dashboard-card achievements-card">
                    <div class="card-header">
                        <div class="card-title">
                            <i class="icon-award"></i>
                            <h2>Saavutused</h2>
                        </div>
                    </div>
                    <div class="card-content">
                        <div class="achievements-list">
                            <?php if (count($recent_results) >= 1): ?>
                                <div class="achievement-item">
                                    <div class="achievement-icon success">✓</div>
                                    <span>Esimene tulemus sisestatud</span>
                                </div>
                            <?php endif; ?>
                            
                            <?php if (count($recent_results) >= 5): ?>
                                <div class="achievement-item">
                                    <div class="achievement-icon primary">⚡</div>
                                    <span>5 võistlust läbitud</span>
                                </div>
                            <?php endif; ?>
                            
                            <?php 
                            // PARANDATUD: Safe season points summa
                            $totalSeasonPoints = 0;
                            foreach ($season_stats as $stats) {
                                if (isset($stats['total_points']) && is_numeric($stats['total_points'])) {
                                    $totalSeasonPoints += $stats['total_points'];
                                }
                            }
                            if ($totalSeasonPoints > 50): ?>
                                <div class="achievement-item">
                                    <div class="achievement-icon warning">🏆</div>
                                    <span>Üle 50 punkti kogutud</span>
                                </div>
                            <?php endif; ?>
                            
                            <?php 
                            // PARANDATUD: Safe TOP 3 check
                            $hasTop3Position = false;
                            if (!empty($positions)) {
                                foreach ($positions as $position) {
                                    if ($position !== null && is_numeric($position) && $position <= 3) {
                                        $hasTop3Position = true;
                                        break;
                                    }
                                }
                            }
                            if ($hasTop3Position): ?>
                                <div class="achievement-item">
                                    <div class="achievement-icon gold">🥇</div>
                                    <span>TOP 3 jõudnud</span>
                                </div>
                            <?php endif; ?>
                            
                            <?php 
                            // PARANDATUD: Safe disciplines check
                            $disciplinesWithStarts = 0;
                            foreach ($season_stats as $stats) {
                                if (isset($stats['starts_count']) && $stats['starts_count'] > 0) {
                                    $disciplinesWithStarts++;
                                }
                            }
                            if ($disciplinesWithStarts === 3): ?>
                                <div class="achievement-item">
                                    <div class="achievement-icon rainbow">🌟</div>
                                    <span>Kõik distsipliinid proovitud</span>
                                </div>
                            <?php endif; ?>
                            
                            <?php 
                            // PARANDATUD: Safe empty state check
                            $hasAnyStarts = false;
                            foreach ($season_stats as $stats) {
                                if (isset($stats['starts_count']) && $stats['starts_count'] > 0) {
                                    $hasAnyStarts = true;
                                    break;
                                }
                            }
                            if (!$hasAnyStarts): ?>
                                <div class="achievement-placeholder">
                                    <i class="icon-star"></i>
                                    <p>Saavutused ilmuvad siia pärast esimesi tulemusi</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Eesmärgid -->
        <div class="goals-section">
            <div class="goals-card">
                <div class="goals-header">
                    <i class="icon-target"></i>
                    <h2>Hooaja eesmärgid</h2>
                </div>
                <div class="goals-content">
                    <div class="goals-grid">
                        <div class="goal-item">
                            <h3>Koolisõit</h3>
                            <div class="goal-current">Hetke koht: #<?php echo $positions['koolisoit'] ?? '-'; ?></div>
                            <div class="goal-target">Eesmärk: TOP 10</div>
                        </div>
                        <div class="goal-item">
                            <h3>Takistussõit</h3>
                            <div class="goal-current">Tehtud: <?php echo $season_stats['takistussoit']['starts_count']; ?> võistlust</div>
                            <div class="goal-target">Eesmärk: 8+ võistlust</div>
                        </div>
                        <div class="goal-item">
                            <h3>Kestvusratsutamine</h3>
                            <div class="goal-current">Tehtud: <?php echo $season_stats['kestvusratsutamine']['starts_count']; ?> distantsi</div>
                            <div class="goal-target">Eesmärk: 2+ distantsi</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<!-- DEBUG: Andmete kontroll ja dropdown testimine -->
<script>
console.log('🏇 Dashboard DEBUG - Data state and dropdown check:');
console.log('📊 Results count:', <?php echo count($recent_results); ?>);
console.log('🏆 Positions:', <?php echo json_encode($positions); ?>);
console.log('📈 Season stats:', <?php echo json_encode(array_map(function($s) { return ['total_points' => $s['total_points'], 'starts_count' => $s['starts_count']]; }, $season_stats)); ?>);
console.log('✅ User has results:', <?php echo !empty($recent_results) ? 'true' : 'false'; ?>);
console.log('🎯 Total season points:', <?php echo $totalSeasonPoints ?? 0; ?>);
console.log('🥇 Has TOP 3:', <?php echo isset($hasTop3Position) && $hasTop3Position ? 'true' : 'false'; ?>);
console.log('🌟 Disciplines with starts:', <?php echo $disciplinesWithStarts ?? 0; ?>);

// Kontrolli dropdown elementide olemasolu
setTimeout(function() {
    const userMenuToggle = document.querySelector('.user-menu-toggle');
    const userMenuDropdown = document.getElementById('userMenuDropdown');
    
    console.log('🔍 Dropdown elements check:');
    console.log('- Toggle button:', !!userMenuToggle);
    console.log('- Dropdown menu:', !!userMenuDropdown);
    
    if (userMenuToggle && userMenuDropdown) {
        console.log('✅ All dropdown elements present');
        
        // Test dropdown functionality
        userMenuToggle.addEventListener('click', function() {
            console.log('🖱️ Dropdown click detected');
        });
        
    } else {
        console.error('❌ Missing dropdown elements!');
    }
}, 500);

// Kontrolli JavaScript vigu
window.addEventListener('error', function(e) {
    console.error('🚨 JavaScript error detected:');
    console.error('Message:', e.message);
    console.error('File:', e.filename);
    console.error('Line:', e.lineno);
    console.error('Error object:', e.error);
});

// Kontrolli PHP vigu (kui on)
window.addEventListener('DOMContentLoaded', function() {
    const phpErrors = document.querySelectorAll('.alert-error');
    if (phpErrors.length > 0) {
        console.warn('⚠️ PHP errors detected on page:', phpErrors.length);
        phpErrors.forEach((error, index) => {
            console.warn(`PHP Error ${index + 1}:`, error.textContent.trim());
        });
    } else {
        console.log('✅ No PHP errors detected');
    }
    
    // 🌟 PARANDATUD: Motivatsiooni kaardi hover efekt - nüüd sama mis teistel
    const motivationAction = document.querySelector('.action-card[href*="motivation.php"]');
    if (motivationAction) {
        console.log('🌟 Motivatsiooni kiirlink leitud - sama stiil nagu teistel');
        
        // Sama hover efekt nagu teistel action-card'idel
        motivationAction.addEventListener('mouseenter', function() {
            // Kasutab dashboard.css-is määratletud .action-card:hover stiile
        });
        
        motivationAction.addEventListener('mouseleave', function() {
            // Kasutab dashboard.css-is määratletud stiile
        });
    }
});
</script>

<style>
/* PARANDATUD: Badge stiilid + fix action-card position */
.action-card {
    position: relative; /* VAJALIK badge'i jaoks */
}

.action-badge {
    position: absolute;
    top: var(--spacing-2);
    right: var(--spacing-2);
    background: var(--danger-color);
    color: white;
    font-size: var(--font-size-xs);
    font-weight: 600;
    padding: 4px 8px;
    border-radius: var(--radius-full);
    min-width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 2;
    animation: pulse 2s infinite;
}

@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.1); }
    100% { transform: scale(1); }
}

/* Kõik action-card'id kasutavad nüüd sama dashboard.css stiile */
</style>

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