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

// Nõua sisselogimist
requireLogin();

$user_id = $_SESSION['user_id'];
$error = '';
$success = '';

// 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');
    }
    
} catch(Exception $e) {
    $error = 'Kasutaja andmete laadimine ebaõnnestus';
    error_log('Profile load error: ' . $e->getMessage());
    header('Location: ' . url());
    exit;
}

// Töötle profiili uuendamist
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {
    $firstName = getPost('firstName');
    $lastName = getPost('lastName');
    $email = getPost('email');
    $phone = getPost('phone');
    $birthDate = getPost('birthDate');
    
    if (empty($firstName) || empty($lastName) || empty($email) || empty($birthDate)) {
        $error = 'Eesnimi, perekonnanimi, e-mail ja sünniaeg on kohustuslikud';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'Palun sisesta kehtiv e-maili aadress';
    } elseif (strtotime($birthDate) > strtotime('-10 years')) {
        $error = 'Sünniaeg peab olema vähemalt 10 aastat tagasi';
    } elseif (strtotime($birthDate) < strtotime('-100 years')) {
        $error = 'Sünniaeg ei saa olla üle 100 aasta tagasi';
    } else {
        try {
            // Kontrolli kas e-mail on juba kasutusel (välja arvatud praegune kasutaja)
            $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
            $stmt->execute([$email, $user_id]);
            if ($stmt->fetch()) {
                $error = 'See e-maili aadress on juba kasutusel';
            } else {
                // Uuenda kasutaja andmed
                $stmt = $pdo->prepare("
                    UPDATE users 
                    SET firstName = ?, lastName = ?, email = ?, phone = ?, birthDate = ?, updatedAt = CURRENT_TIMESTAMP
                    WHERE id = ?
                ");
                $stmt->execute([$firstName, $lastName, $email, $phone, $birthDate, $user_id]);
                
                // Uuenda sessiooni nime
                $_SESSION['user_name'] = $firstName . ' ' . $lastName;
                
                $success = 'Profiil edukalt uuendatud!';
                
                // Logi tegevus
                logActivity($user_id, 'profile_updated', 'Profile information updated');
                
                // Uuenda $user muutujat
                $user['firstName'] = $firstName;
                $user['lastName'] = $lastName;
                $user['email'] = $email;
                $user['phone'] = $phone;
                $user['birthDate'] = $birthDate;
            }
            
        } catch(PDOException $e) {
            $error = 'Profiili uuendamine ebaõnnestus: ' . $e->getMessage();
            error_log('Profile update error: ' . $e->getMessage());
        }
    }
}

// Töötle parooli muutmist
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_password'])) {
    $current_password = getPost('current_password');
    $new_password = getPost('new_password');
    $confirm_password = getPost('confirm_password');
    
    if (empty($current_password) || empty($new_password) || empty($confirm_password)) {
        $error = 'Kõik parooli väljad on kohustuslikud';
    } elseif ($new_password !== $confirm_password) {
        $error = 'Uued paroolid ei ühti';
    } elseif (strlen($new_password) < 6) {
        $error = 'Uus parool peab olema vähemalt 6 tähemärki pikk';
    } elseif (strlen($new_password) > 100) {
        $error = 'Parool on liiga pikk (max 100 tähemärki)';
    } elseif ($new_password === $current_password) {
        $error = 'Uus parool ei tohi olla sama mis vana parool';
    } else {
        try {
            // Kontrolli praegust parooli
            if (!verifyPassword($current_password, $user['password'])) {
                $error = 'Praegune parool on vale';
            } else {
                // Uuenda parooli
                $hashed_password = hashPassword($new_password);
                $stmt = $pdo->prepare("UPDATE users SET password = ?, updatedAt = CURRENT_TIMESTAMP WHERE id = ?");
                $stmt->execute([$hashed_password, $user_id]);
                
                $success = 'Parool edukalt muudetud!';
                
                // Logi tegevus
                logActivity($user_id, 'password_changed', 'Password changed');
            }
            
        } catch(PDOException $e) {
            $error = 'Parooli muutmine ebaõnnestus: ' . $e->getMessage();
            error_log('Password change error: ' . $e->getMessage());
        }
    }
}

// Töötle konto kustutamise taotlust (UUS)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['request_deletion'])) {
    $confirm_deletion = getPost('confirm_deletion');
    $deletion_reason = getPost('deletion_reason');
    
    if ($confirm_deletion !== 'KUSTUTA') {
        $error = 'Konto kustutamiseks sisesta "KUSTUTA"';
    } else {
        try {
            // Märgi kasutaja mitteaktiivseks (ei kustuta andmeid täielikult)
            $stmt = $pdo->prepare("UPDATE users SET isActive = 0, updatedAt = CURRENT_TIMESTAMP WHERE id = ?");
            $stmt->execute([$user_id]);
            
            // Logi tegevus
            logActivity($user_id, 'account_deactivated', "Account deactivated. Reason: $deletion_reason");
            
            // Logi välja
            session_destroy();
            
            // Suuna teatega avalehele
            session_start();
            $_SESSION['flash_message'] = 'Konto on deaktiveeritud. Võid taotleda taasaktiveerimist adminilt.';
            $_SESSION['flash_type'] = 'info';
            
            header('Location: ' . url());
            exit;
            
        } catch(PDOException $e) {
            $error = 'Konto deaktiveerimine ebaõnnestus: ' . $e->getMessage();
            error_log('Account deactivation error: ' . $e->getMessage());
        }
    }
}

// Lae kasutaja statistika
$user_stats = [];
try {
    // Üldstatistika
    $stmt = $pdo->prepare("
        SELECT 
            COUNT(DISTINCT r.competitionId) as competitions_count,
            COUNT(r.id) as results_count,
            AVG(r.points) as avg_points,
            MAX(r.points) as best_points,
            MIN(r.points) as worst_points,
            SUM(r.points) as total_points
        FROM results r
        JOIN competitions c ON r.competitionId = c.id
        WHERE r.userId = ?
    ");
    $stmt->execute([$user_id]);
    $user_stats = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Distsipliinide statistika
    $stmt = $pdo->prepare("
        SELECT 
            r.discipline,
            COUNT(r.id) as count,
            AVG(r.points) as avg_points,
            MAX(r.points) as best_points,
            SUM(r.points) as total_points
        FROM results r
        JOIN competitions c ON r.competitionId = c.id
        WHERE r.userId = ?
        GROUP BY r.discipline
        ORDER BY count DESC
    ");
    $stmt->execute([$user_id]);
    $discipline_stats = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Hooaja statistika (UUS)
    $current_year = date('Y');
    $stmt = $pdo->prepare("
        SELECT 
            COUNT(DISTINCT r.competitionId) as season_competitions,
            COUNT(r.id) as season_results,
            AVG(r.points) as season_avg_points,
            MAX(r.points) as season_best_points
        FROM results r
        JOIN competitions c ON r.competitionId = c.id
        WHERE r.userId = ? AND strftime('%Y', c.date) = ?
    ");
    $stmt->execute([$user_id, $current_year]);
    $season_stats = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Viimased 5 tulemust (UUS)
    $stmt = $pdo->prepare("
        SELECT r.*, c.name as competitionName, c.date as competitionDate
        FROM results r
        JOIN competitions c ON r.competitionId = c.id
        WHERE r.userId = ?
        ORDER BY c.date DESC, r.createdAt DESC
        LIMIT 5
    ");
    $stmt->execute([$user_id]);
    $recent_results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch(PDOException $e) {
    error_log('Profile stats error: ' . $e->getMessage());
    $user_stats = ['competitions_count' => 0, 'results_count' => 0, 'avg_points' => 0, 'best_points' => 0, 'worst_points' => 0, 'total_points' => 0];
    $discipline_stats = [];
    $season_stats = ['season_competitions' => 0, 'season_results' => 0, 'season_avg_points' => 0, 'season_best_points' => 0];
    $recent_results = [];
}

$page_title = 'Minu profiil';
$page_description = 'Halda oma profiili andmeid ja vaata statistikat.';

include 'includes/header.php';
?>

<main class="profile-main">
    <div class="container">
        <!-- Header -->
        <div class="page-header">
            <div class="page-header-content">
                <h1 class="page-title">Minu profiil</h1>
                <p class="page-subtitle">
                    Halda oma andmeid ja vaata statistikat
                </p>
            </div>
            <div class="profile-avatar">
                <div class="avatar-circle">
                    <i class="icon-user"></i>
                </div>
                <div class="avatar-info">
                    <div class="avatar-name"><?php echo htmlspecialchars($user['firstName'] . ' ' . $user['lastName']); ?></div>
                    <div class="avatar-role"><?php echo getAgeGroupName(getAgeGroup($user['birthDate'])); ?></div>
                </div>
            </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; ?>

        <!-- Profiili grid -->
        <div class="profile-grid">
            <!-- Vasakpoolne veerg - Profiili andmed -->
            <div class="profile-left">
                <!-- Profiili info -->
                <div class="profile-card">
                    <div class="card-header">
                        <h2 class="card-title">
                            <i class="icon-user"></i>
                            Profiili andmed
                        </h2>
                    </div>
                    <div class="card-content">
                        <form method="POST" class="profile-form">
                            <div class="form-grid">
                                <div class="form-group">
                                    <label for="firstName" class="form-label">Eesnimi *</label>
                                    <input type="text" id="firstName" name="firstName" class="form-input"
                                           value="<?php echo htmlspecialchars($user['firstName']); ?>" required>
                                </div>

                                <div class="form-group">
                                    <label for="lastName" class="form-label">Perekonnanimi *</label>
                                    <input type="text" id="lastName" name="lastName" class="form-input"
                                           value="<?php echo htmlspecialchars($user['lastName']); ?>" required>
                                </div>

                                <div class="form-group">
                                    <label for="email" class="form-label">E-mail *</label>
                                    <input type="email" id="email" name="email" class="form-input"
                                           value="<?php echo htmlspecialchars($user['email']); ?>" required>
                                </div>

                                <div class="form-group">
                                    <label for="phone" class="form-label">Telefon</label>
                                    <input type="tel" id="phone" name="phone" class="form-input"
                                           value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>"
                                           placeholder="+372 5xxxxxxx">
                                </div>

                                <div class="form-group">
                                    <label for="birthDate" class="form-label">Sünniaeg *</label>
                                    <input type="date" id="birthDate" name="birthDate" class="form-input"
                                           value="<?php echo $user['birthDate']; ?>" required>
                                    <div class="form-help">Vanus: <?php echo date('Y') - date('Y', strtotime($user['birthDate'])); ?> aastat</div>
                                </div>

                                <div class="form-group">
                                    <label for="username" class="form-label">Kasutajanimi</label>
                                    <input type="text" id="username" class="form-input"
                                           value="<?php echo htmlspecialchars($user['username']); ?>" disabled>
                                    <div class="form-help">Kasutajanime ei saa muuta</div>
                                </div>
                            </div>

                            <div class="form-actions">
                                <button type="submit" name="update_profile" class="btn btn-primary">
                                    <i class="icon-save"></i>
                                    <span>Salvesta muudatused</span>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Parooli muutmine -->
                <div class="profile-card">
                    <div class="card-header">
                        <h2 class="card-title">
                            <i class="icon-lock"></i>
                            Parooli muutmine
                        </h2>
                    </div>
                    <div class="card-content">
                        <form method="POST" class="password-form">
                            <div class="form-group">
                                <label for="current_password" class="form-label">Praegune parool *</label>
                                <div class="password-input-container">
                                    <input type="password" id="current_password" name="current_password" 
                                           class="form-input" required>
                                    <button type="button" class="password-toggle" onclick="togglePassword('current_password')">
                                        <i class="icon-eye" id="current_password-toggle-icon"></i>
                                    </button>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="new_password" class="form-label">Uus parool *</label>
                                <div class="password-input-container">
                                    <input type="password" id="new_password" name="new_password" 
                                           class="form-input" minlength="6" maxlength="100" required>
                                    <button type="button" class="password-toggle" onclick="togglePassword('new_password')">
                                        <i class="icon-eye" id="new_password-toggle-icon"></i>
                                    </button>
                                </div>
                                <div class="form-help">6-100 tähemärki, peab erinema vanast paroolist</div>
                            </div>

                            <div class="form-group">
                                <label for="confirm_password" class="form-label">Korda uus parool *</label>
                                <div class="password-input-container">
                                    <input type="password" id="confirm_password" name="confirm_password" 
                                           class="form-input" minlength="6" maxlength="100" required>
                                    <button type="button" class="password-toggle" onclick="togglePassword('confirm_password')">
                                        <i class="icon-eye" id="confirm_password-toggle-icon"></i>
                                    </button>
                                </div>
                                <div id="password-match-indicator" class="form-help"></div>
                            </div>

                            <div class="form-actions">
                                <button type="submit" name="change_password" class="btn btn-secondary">
                                    <i class="icon-lock"></i>
                                    <span>Muuda parooli</span>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Konto kustutamine (UUS) -->
                <div class="profile-card danger-card">
                    <div class="card-header">
                        <h2 class="card-title">
                            <i class="icon-alert-circle"></i>
                            Ohtlik tsoon
                        </h2>
                    </div>
                    <div class="card-content">
                        <div class="danger-warning">
                            <h4>Konto deaktiveerimine</h4>
                            <p>Konto deaktiveerimise korral:</p>
                            <ul>
                                <li>Sa ei saa enam sisse logida</li>
                                <li>Sinu tulemused jäävad alles, kuid muutuvad anonüümseks</li>
                                <li>Admin saab taotluse korral konto taasaktiveerida</li>
                            </ul>
                        </div>
                        
                        <button onclick="openModal('deleteModal')" class="btn btn-danger">
                            <i class="icon-trash"></i>
                            <span>Deaktiveeri konto</span>
                        </button>
                    </div>
                </div>
            </div>

            <!-- Parempoolne veerg - Statistika -->
            <div class="profile-right">
                <!-- Kasutaja info -->
                <div class="profile-card">
                    <div class="card-header">
                        <h2 class="card-title">
                            <i class="icon-info"></i>
                            Kasutaja info
                        </h2>
                    </div>
                    <div class="card-content">
                        <div class="info-list">
                            <div class="info-item">
                                <div class="info-label">Roll:</div>
                                <div class="info-value">
                                    <span class="role-badge <?php echo $user['role']; ?>">
                                        <?php echo $user['role'] === 'admin' ? 'Administraator' : 'Sportlane'; ?>
                                    </span>
                                </div>
                            </div>

                            <div class="info-item">
                                <div class="info-label">Vanusegrupp:</div>
                                <div class="info-value">
                                    <?php echo getAgeGroupName(getAgeGroup($user['birthDate'])); ?>
                                </div>
                            </div>

                            <div class="info-item">
                                <div class="info-label">Liitunud:</div>
                                <div class="info-value">
                                    <?php echo formatDate($user['createdAt']); ?>
                                </div>
                            </div>

                            <div class="info-item">
                                <div class="info-label">Viimati uuendatud:</div>
                                <div class="info-value">
                                    <?php echo formatDate($user['updatedAt']); ?>
                                </div>
                            </div>

                            <div class="info-item">
                                <div class="info-label">Staatus:</div>
                                <div class="info-value">
                                    <span class="status-badge <?php echo $user['isActive'] ? 'active' : 'inactive'; ?>">
                                        <?php echo $user['isActive'] ? 'Aktiivne' : 'Mitteaktiivne'; ?>
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Üldstatistika -->
                <div class="profile-card">
                    <div class="card-header">
                        <h2 class="card-title">
                            <i class="icon-bar-chart"></i>
                            Kogu karjääri statistika
                        </h2>
                    </div>
                    <div class="card-content">
                        <div class="stats-grid">
                            <div class="stat-item">
                                <div class="stat-number"><?php echo $user_stats['competitions_count'] ?? 0; ?></div>
                                <div class="stat-label">Võistlust kokku</div>
                            </div>

                            <div class="stat-item">
                                <div class="stat-number"><?php echo $user_stats['results_count'] ?? 0; ?></div>
                                <div class="stat-label">Tulemust</div>
                            </div>

                            <div class="stat-item">
                                <div class="stat-number">
                                    <?php echo $user_stats['total_points'] ? formatPoints($user_stats['total_points']) : '0.0'; ?>
                                </div>
                                <div class="stat-label">Punkte kokku</div>
                            </div>

                            <div class="stat-item">
                                <div class="stat-number">
                                    <?php echo $user_stats['avg_points'] ? formatPoints($user_stats['avg_points']) : '0.0'; ?>
                                </div>
                                <div class="stat-label">Keskmine punktid</div>
                            </div>

                            <div class="stat-item">
                                <div class="stat-number">
                                    <?php echo $user_stats['best_points'] ? formatPoints($user_stats['best_points']) : '0.0'; ?>
                                </div>
                                <div class="stat-label">Parim tulemus</div>
                            </div>

                            <div class="stat-item">
                                <div class="stat-number">
                                    <?php echo $user_stats['worst_points'] ? formatPoints($user_stats['worst_points']) : '0.0'; ?>
                                </div>
                                <div class="stat-label">Halvim tulemus</div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Hooaja statistika (UUS) -->
                <div class="profile-card">
                    <div class="card-header">
                        <h2 class="card-title">
                            <i class="icon-calendar"></i>
                            <?php echo date('Y'); ?>. aasta hooaeg
                        </h2>
                    </div>
                    <div class="card-content">
                        <div class="stats-grid">
                            <div class="stat-item">
                                <div class="stat-number"><?php echo $season_stats['season_competitions'] ?? 0; ?></div>
                                <div class="stat-label">Võistlust</div>
                            </div>

                            <div class="stat-item">
                                <div class="stat-number"><?php echo $season_stats['season_results'] ?? 0; ?></div>
                                <div class="stat-label">Tulemust</div>
                            </div>

                            <div class="stat-item">
                                <div class="stat-number">
                                    <?php echo $season_stats['season_avg_points'] ? formatPoints($season_stats['season_avg_points']) : '0.0'; ?>
                                </div>
                                <div class="stat-label">Keskmine</div>
                            </div>

                            <div class="stat-item">
                                <div class="stat-number">
                                    <?php echo $season_stats['season_best_points'] ? formatPoints($season_stats['season_best_points']) : '0.0'; ?>
                                </div>
                                <div class="stat-label">Parim</div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Distsipliinide statistika -->
                <?php if (!empty($discipline_stats)): ?>
                <div class="profile-card">
                    <div class="card-header">
                        <h2 class="card-title">
                            <i class="icon-trophy"></i>
                            Distsipliinide kaupa
                        </h2>
                    </div>
                    <div class="card-content">
                        <div class="discipline-stats">
                            <?php foreach ($discipline_stats as $stat): ?>
                                <div class="discipline-stat">
                                    <div class="discipline-header">
                                        <div class="discipline-name">
                                            <?php echo getDisciplineName($stat['discipline']); ?>
                                        </div>
                                        <div class="discipline-count">
                                            <?php echo $stat['count']; ?> tulemust
                                        </div>
                                    </div>
                                    <div class="discipline-details">
                                        <div class="detail-item">
                                            <span class="detail-label">Kokku:</span>
                                            <span class="detail-value"><?php echo formatPoints($stat['total_points']); ?>p</span>
                                        </div>
                                        <div class="detail-item">
                                            <span class="detail-label">Keskmine:</span>
                                            <span class="detail-value"><?php echo formatPoints($stat['avg_points']); ?>p</span>
                                        </div>
                                        <div class="detail-item">
                                            <span class="detail-label">Parim:</span>
                                            <span class="detail-value best"><?php echo formatPoints($stat['best_points']); ?>p</span>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Viimased tulemused (UUS) -->
                <?php if (!empty($recent_results)): ?>
                <div class="profile-card">
                    <div class="card-header">
                        <h2 class="card-title">
                            <i class="icon-clock"></i>
                            Viimased tulemused
                        </h2>
                    </div>
                    <div class="card-content">
                        <div class="recent-results">
                            <?php foreach ($recent_results as $result): ?>
                                <div class="recent-result">
                                    <div class="result-date"><?php echo formatDate($result['competitionDate']); ?></div>
                                    <div class="result-name"><?php echo htmlspecialchars($result['competitionName']); ?></div>
                                    <div class="result-points"><?php echo formatPoints($result['points']); ?>p</div>
                                    <div class="result-discipline">
                                        <span class="discipline-badge <?php echo $result['discipline']; ?>">
                                            <?php echo getDisciplineName($result['discipline']); ?>
                                        </span>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <div class="card-footer">
                            <a href="<?php echo url('athlete/results.php'); ?>" class="view-all-link">
                                Vaata kõiki tulemusi →
                            </a>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Kiired lingid -->
                <div class="profile-card">
                    <div class="card-header">
                        <h2 class="card-title">
                            <i class="icon-zap"></i>
                            Kiired toimingud
                        </h2>
                    </div>
                    <div class="card-content">
                        <div class="quick-actions">
                            <?php if (isAthlete()): ?>
                                <a href="<?php echo url('athlete/add_result.php'); ?>" class="action-link featured">
                                    <i class="icon-plus"></i>
                                    <span>Lisa tulemus</span>
                                </a>
                                <a href="<?php echo url('athlete/results.php'); ?>" class="action-link">
                                    <i class="icon-trophy"></i>
                                    <span>Minu tulemused</span>
                                </a>
                                <a href="<?php echo url('athlete/training.php'); ?>" class="action-link">
                                    <i class="icon-calendar"></i>
                                    <span>Treeningu päevik</span>
                                </a>
                                <a href="<?php echo url('athlete/stats.php'); ?>" class="action-link">
                                    <i class="icon-bar-chart"></i>
                                    <span>Minu statistika</span>
                                </a>
                                <a href="<?php echo url('athlete/dashboard.php'); ?>" class="action-link">
                                    <i class="icon-user"></i>
                                    <span>Armatuurlaud</span>
                                </a>
                            <?php endif; ?>
                            
                            <?php if (isAdmin()): ?>
                                <a href="<?php echo url('admin/dashboard.php'); ?>" class="action-link">
                                    <i class="icon-settings"></i>
                                    <span>Admin paneel</span>
                                </a>
                            <?php endif; ?>
                            
                            <a href="<?php echo url('public/rankings.php'); ?>" class="action-link">
                                <i class="icon-list"></i>
                                <span>Hooaja tabelid</span>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Konto kustutamise modal (UUS) -->
    <div id="deleteModal" class="modal">
        <div class="modal-overlay">
            <div class="modal-content danger-modal">
                <div class="modal-header">
                    <h3 class="modal-title">⚠️ Konto deaktiveerimine</h3>
                    <button class="modal-close" onclick="closeModal('deleteModal')">
                        <i class="icon-x"></i>
                    </button>
                </div>

                <form method="POST" class="modal-form">
                    <div class="danger-content">
                        <div class="danger-icon">
                            <i class="icon-alert-circle"></i>
                        </div>
                        <h4>Oled kindel, et tahad konto deaktiveerida?</h4>
                        <p>See tegevus:</p>
                        <ul>
                            <li>Deaktiveerib su konto kohe</li>
                            <li>Sa ei saa enam sisse logida</li>
                            <li>Sinu tulemused jäävad alles</li>
                            <li>Admin saab konto taasaktiveerida</li>
                        </ul>
                    </div>

                    <div class="form-group">
                        <label for="deletion_reason" class="form-label">Põhjus (valikuline)</label>
                        <textarea id="deletion_reason" name="deletion_reason" class="form-textarea" rows="3"
                                  placeholder="Miks tahad konto deaktiveerida?"></textarea>
                    </div>

                    <div class="form-group">
                        <label for="confirm_deletion" class="form-label">
                            Kinnitamiseks sisesta: <strong>KUSTUTA</strong>
                        </label>
                        <input type="text" id="confirm_deletion" name="confirm_deletion" class="form-input"
                               placeholder="Sisesta KUSTUTA" required>
                    </div>

                    <div class="modal-actions">
                        <button type="button" onclick="closeModal('deleteModal')" class="btn btn-secondary">
                            Tühista
                        </button>
                        <button type="submit" name="request_deletion" class="btn btn-danger">
                            <i class="icon-trash"></i>
                            <span>Deaktiveeri konto</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</main>

<style>
/* Profile Page Styles - Enhanced */
.profile-main {
    padding: var(--spacing-6) 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;
}

/* Enhanced Avatar */
.profile-avatar {
    display: flex;
    align-items: center;
    gap: var(--spacing-4);
    flex-shrink: 0;
}

.avatar-circle {
    width: 80px;
    height: 80px;
    background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
    color: white;
    border-radius: var(--radius-full);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 2rem;
}

.avatar-info {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-1);
}

.avatar-name {
    font-weight: 600;
    color: var(--gray-900);
    font-size: var(--font-size-lg);
}

.avatar-role {
    color: var(--gray-600);
    font-size: var(--font-size-sm);
}

/* Profile Grid */
.profile-grid {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: var(--spacing-8);
}

/* Profile Cards */
.profile-card {
    background: white;
    border-radius: var(--radius-lg);
    box-shadow: var(--shadow);
    margin-bottom: var(--spacing-6);
    overflow: hidden;
}

.danger-card {
    border: 1px solid var(--danger-color);
}

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

.danger-card .card-header {
    background: #fef2f2;
    border-bottom-color: var(--danger-color);
}

.card-title {
    display: flex;
    align-items: center;
    gap: var(--spacing-3);
    margin: 0;
    font-size: var(--font-size-lg);
    font-weight: 600;
}

.card-title i {
    color: var(--primary-color);
}

.danger-card .card-title i {
    color: var(--danger-color);
}

.card-content {
    padding: var(--spacing-6);
}

.card-footer {
    padding: var(--spacing-4) var(--spacing-6);
    border-top: 1px solid var(--gray-200);
    background: var(--gray-50);
}

/* Forms */
.profile-form,
.password-form {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-4);
}

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

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

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

.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-input:disabled {
    background-color: var(--gray-100);
    color: var(--gray-500);
    cursor: not-allowed;
}

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

.form-help.success {
    color: var(--success-color);
}

.form-help.error {
    color: var(--danger-color);
}

.password-input-container {
    position: relative;
}

.password-toggle {
    position: absolute;
    right: var(--spacing-3);
    top: 50%;
    transform: translateY(-50%);
    background: none;
    border: none;
    color: var(--gray-400);
    cursor: pointer;
    padding: var(--spacing-2);
    border-radius: var(--radius-sm);
    transition: color var(--transition-fast);
}

.password-toggle:hover {
    color: var(--gray-600);
}

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

/* Danger Warning */
.danger-warning {
    background: #fef2f2;
    border: 1px solid #fecaca;
    border-radius: var(--radius);
    padding: var(--spacing-4);
    margin-bottom: var(--spacing-4);
}

.danger-warning h4 {
    color: var(--danger-color);
    margin-bottom: var(--spacing-2);
}

.danger-warning p {
    color: #991b1b;
    margin-bottom: var(--spacing-2);
}

.danger-warning ul {
    color: #991b1b;
    margin-left: var(--spacing-4);
}

/* Info List */
.info-list {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-3);
}

.info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: var(--spacing-3);
    background: var(--gray-50);
    border-radius: var(--radius);
}

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

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

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

.role-badge.admin {
    background: var(--danger-color);
    color: white;
}

.role-badge.athlete {
    background: var(--primary-color);
    color: white;
}

.status-badge.active {
    background: var(--success-color);
    color: white;
}

.status-badge.inactive {
    background: var(--gray-400);
    color: white;
}

/* Stats Grid */
.stats-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: var(--spacing-4);
}

.stat-item {
    text-align: center;
    padding: var(--spacing-4);
    background: var(--gray-50);
    border-radius: var(--radius);
    transition: all var(--transition-fast);
}

.stat-item:hover {
    background: var(--gray-100);
}

.stat-number {
    font-size: var(--font-size-2xl);
    font-weight: 700;
    color: var(--primary-color);
    display: block;
}

.stat-label {
    font-size: var(--font-size-xs);
    color: var(--gray-600);
    margin-top: var(--spacing-1);
}

/* Discipline Stats */
.discipline-stats {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-4);
}

.discipline-stat {
    padding: var(--spacing-4);
    border: 1px solid var(--gray-200);
    border-radius: var(--radius);
    transition: all var(--transition-fast);
}

.discipline-stat:hover {
    border-color: var(--primary-color);
    background: var(--gray-50);
}

.discipline-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: var(--spacing-3);
}

.discipline-name {
    font-weight: 500;
    color: var(--gray-900);
}

.discipline-count {
    font-size: var(--font-size-sm);
    color: var(--gray-600);
}

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

.detail-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: var(--font-size-sm);
}

.detail-label {
    color: var(--gray-600);
}

.detail-value {
    color: var(--gray-900);
    font-weight: 500;
}

.detail-value.best {
    color: var(--success-color);
}

/* Recent Results */
.recent-results {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-3);
}

.recent-result {
    display: grid;
    grid-template-columns: auto 1fr auto auto;
    gap: var(--spacing-2);
    align-items: center;
    padding: var(--spacing-3);
    background: var(--gray-50);
    border-radius: var(--radius);
    font-size: var(--font-size-sm);
}

.result-date {
    color: var(--gray-600);
    white-space: nowrap;
}

.result-name {
    color: var(--gray-900);
    font-weight: 500;
}

.result-points {
    color: var(--primary-color);
    font-weight: 600;
}

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

.view-all-link {
    color: var(--primary-color);
    font-weight: 500;
    text-decoration: none;
    font-size: var(--font-size-sm);
}

.view-all-link:hover {
    text-decoration: underline;
}

/* Quick Actions */
.quick-actions {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-2);
}

.action-link {
    display: flex;
    align-items: center;
    gap: var(--spacing-3);
    padding: var(--spacing-3) var(--spacing-4);
    color: var(--gray-700);
    text-decoration: none;
    border-radius: var(--radius);
    transition: all var(--transition-fast);
}

.action-link:hover {
    background: var(--gray-100);
    color: var(--primary-color);
}

.action-link.featured {
    background: color-mix(in srgb, var(--primary-color) 10%, transparent);
    color: var(--primary-color);
    border: 1px solid color-mix(in srgb, var(--primary-color) 20%, transparent);
}

.action-link.featured:hover {
    background: color-mix(in srgb, var(--primary-color) 15%, transparent);
}

.action-link i {
    color: var(--primary-color);
    width: 20px;
}

/* 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: 500px;
    max-height: 90vh;
    overflow-y: auto;
}

.danger-modal {
    border: 2px solid var(--danger-color);
}

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

.danger-modal .modal-header {
    background: #fef2f2;
    border-bottom-color: var(--danger-color);
}

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

.modal-close {
    width: 32px;
    height: 32px;
    border: none;
    background: none;
    border-radius: var(--radius);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: var(--gray-400);
    transition: all var(--transition-fast);
}

.modal-close:hover {
    background: var(--gray-100);
    color: var(--gray-600);
}

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

.danger-content {
    text-align: center;
    margin-bottom: var(--spacing-6);
}

.danger-icon {
    width: 64px;
    height: 64px;
    background: var(--danger-color);
    color: white;
    border-radius: var(--radius-full);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    margin: 0 auto var(--spacing-4);
}

.danger-content h4 {
    color: var(--danger-color);
    margin-bottom: var(--spacing-3);
}

.danger-content p {
    color: var(--gray-700);
    margin-bottom: var(--spacing-2);
}

.danger-content ul {
    text-align: left;
    color: var(--gray-700);
    margin-left: 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);
}

/* Responsive */
@media (max-width: 1024px) {
    .profile-grid {
        grid-template-columns: 1fr;
        gap: var(--spacing-6);
    }
}

@media (max-width: 768px) {
    .page-header {
        flex-direction: column;
        align-items: stretch;
        text-align: center;
        gap: var(--spacing-4);
    }
    
    .profile-avatar {
        justify-content: center;
    }
    
    .form-grid {
        grid-template-columns: 1fr;
    }
    
    .stats-grid {
        grid-template-columns: 1fr;
    }
    
    .form-actions {
        flex-direction: column;
    }
    
    .recent-result {
        grid-template-columns: 1fr;
        gap: var(--spacing-1);
        text-align: center;
    }
    
    .modal-actions {
        flex-direction: column;
    }
}
</style>

<script>
function togglePassword(inputId) {
    const input = document.getElementById(inputId);
    const icon = document.getElementById(inputId + '-toggle-icon');
    
    if (input.type === 'password') {
        input.type = 'text';
        icon.className = 'icon-eye-off';
    } else {
        input.type = 'password';
        icon.className = 'icon-eye';
    }
}

// Enhanced form validation
document.addEventListener('DOMContentLoaded', function() {
    const passwordForm = document.querySelector('.password-form');
    if (passwordForm) {
        const newPassword = document.getElementById('new_password');
        const confirmPassword = document.getElementById('confirm_password');
        const currentPassword = document.getElementById('current_password');
        const indicator = document.getElementById('password-match-indicator');
        
        function validatePasswords() {
            if (confirmPassword.value && newPassword.value) {
                if (confirmPassword.value === newPassword.value) {
                    indicator.textContent = '✓ Paroolid ühtivad';
                    indicator.className = 'form-help success';
                    confirmPassword.setCustomValidity('');
                } else {
                    indicator.textContent = '✗ Paroolid ei ühti';
                    indicator.className = 'form-help error';
                    confirmPassword.setCustomValidity('Paroolid ei ühti');
                }
            } else {
                indicator.textContent = '';
                indicator.className = 'form-help';
            }
        }
        
        function validateNewPassword() {
            if (newPassword.value && currentPassword.value && newPassword.value === currentPassword.value) {
                newPassword.setCustomValidity('Uus parool peab erinema vanast paroolist');
            } else {
                newPassword.setCustomValidity('');
            }
        }
        
        newPassword.addEventListener('input', function() {
            validateNewPassword();
            validatePasswords();
        });
        
        confirmPassword.addEventListener('input', validatePasswords);
        currentPassword.addEventListener('input', validateNewPassword);
        
        passwordForm.addEventListener('submit', function(e) {
            if (newPassword.value !== confirmPassword.value) {
                e.preventDefault();
                alert('Uued paroolid ei ühti!');
                return false;
            }
            
            if (newPassword.value.length < 6) {
                e.preventDefault();
                alert('Parool peab olema vähemalt 6 tähemärki pikk!');
                return false;
            }
            
            if (newPassword.value === currentPassword.value) {
                e.preventDefault();
                alert('Uus parool peab erinema vanast paroolist!');
                return false;
            }
        });
    }
    
    // Enhanced age calculation
    const birthDateInput = document.getElementById('birthDate');
    if (birthDateInput) {
        birthDateInput.addEventListener('change', function() {
            const birthDate = new Date(this.value);
            const today = new Date();
            const age = today.getFullYear() - birthDate.getFullYear();
            const monthDiff = today.getMonth() - birthDate.getMonth();
            
            if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
                age--;
            }
            
            const helpElement = this.nextElementSibling;
            if (helpElement && helpElement.classList.contains('form-help')) {
                helpElement.textContent = `Vanus: ${age} aastat`;
            }
        });
    }
});

// Global modal functions from main.js
// Additional profile-specific modal handling
function confirmDeletion() {
    return confirm('Oled kindel, et tahad oma konto deaktiveerida? See tegevus ei ole tagasipööratav!');
}
</script>

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