<?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'];
$error = '';
$success = '';

// Töötle treeningu lisamist
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_training'])) {
    $date = getPost('date');
    $duration = getPost('duration');
    $horse = getPost('horse');
    $training_type = getPost('training_type');
    $goal = getPost('goal');
    $achievement = getPost('achievement');
    $mood = getPost('mood');
    $notes = getPost('notes');
    
    if (empty($date) || empty($training_type)) {
        $error = 'Kuupäev ja treeningu tüüp on kohustuslikud';
    } else {
        try {
            $stmt = $pdo->prepare("
                INSERT INTO training_log 
                (userId, date, duration, horse, trainingType, goal, achievement, mood, notes)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $user_id, $date, $duration, $horse, $training_type, 
                $goal, $achievement, $mood, $notes
            ]);
            
            $success = 'Treeningu kirje edukalt lisatud!';
            
            // Logi tegevus
            logActivity($user_id, 'training_added', "Training entry added for $date");
            
        } catch(PDOException $e) {
            $error = 'Treeningu lisamine ebaõnnestus: ' . $e->getMessage();
            error_log('Training add error: ' . $e->getMessage());
        }
    }
}

// Töötle treeningu kustutamist
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_training'])) {
    $training_id = getPost('training_id');
    
    try {
        $stmt = $pdo->prepare("DELETE FROM training_log WHERE id = ? AND userId = ?");
        $stmt->execute([$training_id, $user_id]);
        
        $success = 'Treeningu kirje kustutatud!';
        
    } catch(PDOException $e) {
        $error = 'Kustutamine ebaõnnestus: ' . $e->getMessage();
    }
}

// Lae treeningu kirjed
$month = getGet('month', date('Y-m'));
$training_logs = [];
$monthly_stats = [];

try {
    // Lae selle kuu treeningud
    $stmt = $pdo->prepare("
        SELECT * FROM training_log 
        WHERE userId = ? AND strftime('%Y-%m', date) = ?
        ORDER BY date DESC
    ");
    $stmt->execute([$user_id, $month]);
    $training_logs = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Lae kuu statistika
    $stmt = $pdo->prepare("
        SELECT 
            COUNT(*) as total_sessions,
            SUM(duration) as total_minutes,
            AVG(mood) as avg_mood,
            trainingType,
            COUNT(*) as type_count
        FROM training_log 
        WHERE userId = ? AND strftime('%Y-%m', date) = ?
        GROUP BY trainingType
    ");
    $stmt->execute([$user_id, $month]);
    $type_stats = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Üldstatistika
    $stmt = $pdo->prepare("
        SELECT 
            COUNT(*) as total_sessions,
            SUM(duration) as total_minutes,
            AVG(mood) as avg_mood
        FROM training_log 
        WHERE userId = ? AND strftime('%Y-%m', date) = ?
    ");
    $stmt->execute([$user_id, $month]);
    $monthly_stats = $stmt->fetch(PDO::FETCH_ASSOC);
    
} catch(PDOException $e) {
    $error = 'Andmete laadimine ebaõnnestus: ' . $e->getMessage();
    error_log('Training load error: ' . $e->getMessage());
}

$page_title = 'Treeningu päevik';
$page_description = 'Pea treeningu päevikut, jälgi progressi ja märgi üles saavutusi.';

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

<main class="training-main">
    <div class="container">
        <!-- Header -->
        <div class="page-header">
            <div class="page-header-content">
                <h1 class="page-title">Treeningu päevik</h1>
                <p class="page-subtitle">
                    Jälgi oma treeningu progressi ja saavutusi
                </p>
            </div>
            <div class="page-actions">
                <button onclick="openModal('addTrainingModal')" class="btn btn-primary">
                    <i class="icon-plus"></i>
                    <span>Lisa treening</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; ?>

        <!-- Kuu filter -->
        <div class="month-filter">
            <form method="GET" class="month-form">
                <div class="month-selector">
                    <label for="month" class="month-label">Vali kuu:</label>
                    <input type="month" id="month" name="month" value="<?php echo $month; ?>" class="month-input">
                    <button type="submit" class="btn btn-secondary">
                        <i class="icon-filter"></i>
                        <span>Filtreeri</span>
                    </button>
                </div>
            </form>
        </div>

        <!-- Kuu statistika -->
        <div class="month-stats">
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="icon-calendar"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-number"><?php echo $monthly_stats['total_sessions'] ?? 0; ?></div>
                        <div class="stat-label">Treeningu korda</div>
                    </div>
                </div>

                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="icon-clock"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-number">
                            <?php echo $monthly_stats['total_minutes'] ? round($monthly_stats['total_minutes'] / 60, 1) : 0; ?>h
                        </div>
                        <div class="stat-label">Tunde kokku</div>
                    </div>
                </div>

                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="icon-smile"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-number">
                            <?php echo $monthly_stats['avg_mood'] ? number_format($monthly_stats['avg_mood'], 1) : '0.0'; ?>/5
                        </div>
                        <div class="stat-label">Keskmine meeleolu</div>
                    </div>
                </div>

                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="icon-trending-up"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-number">
                            <?php echo ($monthly_stats['total_sessions'] ?? 0) > 0 ? round(($monthly_stats['total_minutes'] ?? 0) / ($monthly_stats['total_sessions'] ?? 1)) : 0; ?>min
                        </div>
                        <div class="stat-label">Keskmine pikkus</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Treeningu kirjed -->
        <div class="training-section">
            <div class="section-header">
                <h2 class="section-title">
                    Treeningu kirjed - <?php echo date('F Y', strtotime($month . '-01')); ?>
                </h2>
            </div>

            <?php if (empty($training_logs)): ?>
                <div class="empty-state">
                    <div class="empty-icon">
                        <i class="icon-calendar"></i>
                    </div>
                    <h3>Treeningu kirjeid pole</h3>
                    <p>Lisa oma esimene treeningu kirje!</p>
                    <button onclick="openModal('addTrainingModal')" class="btn btn-primary">
                        <i class="icon-plus"></i>
                        <span>Lisa treening</span>
                    </button>
                </div>
            <?php else: ?>
                <div class="training-list">
                    <?php foreach ($training_logs as $log): ?>
                        <div class="training-card">
                            <div class="training-header">
                                <div class="training-date">
                                    <div class="date-day"><?php echo date('d', strtotime($log['date'])); ?></div>
                                    <div class="date-month"><?php echo date('M', strtotime($log['date'])); ?></div>
                                </div>
                                <div class="training-type">
                                    <span class="type-badge <?php echo $log['trainingType']; ?>">
                                        <?php 
                                        $type_names = [
                                            'koolisoit' => 'Koolisõit',
                                            'takistussoit' => 'Takistussõit',
                                            'ratsastus' => 'Ratsastus',
                                            'kestvusratsutamine' => 'Kestvusratsutamine',
                                            'muu' => 'Muu'
                                        ];
                                        echo $type_names[$log['trainingType']] ?? $log['trainingType'];
                                        ?>
                                    </span>
                                </div>
                                <div class="training-actions">
                                    <form method="POST" style="display: inline;" 
                                          onsubmit="return confirm('Kas oled kindel, et tahad selle kirje kustutada?')">
                                        <input type="hidden" name="training_id" value="<?php echo $log['id']; ?>">
                                        <button type="submit" name="delete_training" class="btn-icon btn-danger">
                                            <i class="icon-trash"></i>
                                        </button>
                                    </form>
                                </div>
                            </div>

                            <div class="training-content">
                                <div class="training-details">
                                    <?php if ($log['duration']): ?>
                                        <div class="detail-item">
                                            <div class="detail-icon">
                                                <i class="icon-clock"></i>
                                            </div>
                                            <div class="detail-text">
                                                <?php echo $log['duration']; ?> minutit
                                            </div>
                                        </div>
                                    <?php endif; ?>

                                    <?php if ($log['horse']): ?>
                                        <div class="detail-item">
                                            <div class="detail-icon">
                                                <i class="icon-star"></i>
                                            </div>
                                            <div class="detail-text">
                                                <?php echo htmlspecialchars($log['horse']); ?>
                                            </div>
                                        </div>
                                    <?php endif; ?>

                                    <?php if ($log['mood']): ?>
                                        <div class="detail-item">
                                            <div class="detail-icon">
                                                <?php echo getMoodEmoji($log['mood']); ?>
                                            </div>
                                            <div class="detail-text">
                                                Meeleolu: <?php echo $log['mood']; ?>/5
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                </div>

                                <?php if ($log['goal']): ?>
                                    <div class="training-section-item">
                                        <div class="section-label">Eesmärk:</div>
                                        <div class="section-content">
                                            <?php echo htmlspecialchars($log['goal']); ?>
                                        </div>
                                    </div>
                                <?php endif; ?>

                                <?php if ($log['achievement']): ?>
                                    <div class="training-section-item">
                                        <div class="section-label">Saavutus:</div>
                                        <div class="section-content">
                                            <?php echo htmlspecialchars($log['achievement']); ?>
                                        </div>
                                    </div>
                                <?php endif; ?>

                                <?php if ($log['notes']): ?>
                                    <div class="training-section-item">
                                        <div class="section-label">Märkused:</div>
                                        <div class="section-content">
                                            <?php echo htmlspecialchars($log['notes']); ?>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Lisa treeningu modal -->
    <div id="addTrainingModal" class="modal">
        <div class="modal-overlay">
            <div class="modal-content">
                <div class="modal-header">
                    <h3 class="modal-title">Lisa treeningu kirje</h3>
                    <button class="modal-close" onclick="closeModal('addTrainingModal')">
                        <i class="icon-x"></i>
                    </button>
                </div>

                <form method="POST" class="modal-form">
                    <div class="form-grid">
                        <div class="form-group">
                            <label for="date" class="form-label">Kuupäev *</label>
                            <input type="date" id="date" name="date" class="form-input" 
                                   value="<?php echo date('Y-m-d'); ?>" required>
                        </div>

                        <div class="form-group">
                            <label for="duration" class="form-label">Kestus (minutites)</label>
                            <input type="number" id="duration" name="duration" class="form-input" 
                                   min="1" max="300" placeholder="60">
                        </div>

                        <div class="form-group">
                            <label for="training_type" class="form-label">Treeningu tüüp *</label>
                            <select id="training_type" name="training_type" class="form-select" required>
                                <option value="">Vali tüüp</option>
                                <option value="koolisoit">Koolisõit</option>
                                <option value="takistussoit">Takistussõit</option>
                                <option value="ratsastus">Ratsastus</option>
                                <option value="kestvusratsutamine">Kestvusratsutamine</option>
                                <option value="muu">Muu</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="horse" class="form-label">Hobune</label>
                            <input type="text" id="horse" name="horse" class="form-input" 
                                   placeholder="Hobuse nimi">
                        </div>

                        <div class="form-group">
                            <label for="mood" class="form-label">Meeleolu</label>
                            <select id="mood" name="mood" class="form-select">
                                <option value="">Vali meeleolu</option>
                                <option value="1">1 - Väga halb 😤</option>
                                <option value="2">2 - Halb 😕</option>
                                <option value="3">3 - Keskmine 😐</option>
                                <option value="4">4 - Hea 😊</option>
                                <option value="5">5 - Suurepärane 😍</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="goal" class="form-label">Eesmärk</label>
                        <textarea id="goal" name="goal" class="form-textarea" rows="2" 
                                  placeholder="Mida soovisid saavutada?"></textarea>
                    </div>

                    <div class="form-group">
                        <label for="achievement" class="form-label">Saavutus</label>
                        <textarea id="achievement" name="achievement" class="form-textarea" rows="2" 
                                  placeholder="Mida saavutasid?"></textarea>
                    </div>

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

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

<style>
/* Training Page Styles */
.training-main {
    padding: var(--spacing-6) 0;
    min-height: 100vh;
}

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

/* Month Filter */
.month-filter {
    background: white;
    border-radius: var(--radius-lg);
    box-shadow: var(--shadow);
    padding: var(--spacing-4) var(--spacing-6);
    margin-bottom: var(--spacing-6);
}

.month-selector {
    display: flex;
    align-items: center;
    gap: var(--spacing-4);
}

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

.month-input {
    padding: var(--spacing-2) var(--spacing-3);
    border: 1px solid var(--gray-300);
    border-radius: var(--radius);
    font-size: var(--font-size-sm);
}

/* Month Stats */
.month-stats {
    margin-bottom: var(--spacing-8);
}

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

.stat-card {
    background: white;
    border-radius: var(--radius-lg);
    box-shadow: var(--shadow);
    padding: var(--spacing-5);
    display: flex;
    align-items: center;
    gap: var(--spacing-3);
}

.stat-icon {
    width: 48px;
    height: 48px;
    background: linear-gradient(135deg, var(--success-color), #047857);
    color: white;
    border-radius: var(--radius-lg);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
}

.stat-number {
    font-size: var(--font-size-2xl);
    font-weight: 700;
    color: var(--gray-900);
}

.stat-label {
    color: var(--gray-600);
    font-size: var(--font-size-sm);
}

/* Training Section */
.training-section {
    background: white;
    border-radius: var(--radius-lg);
    box-shadow: var(--shadow);
    overflow: hidden;
}

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

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

/* Training Cards */
.training-list {
    padding: var(--spacing-4);
    display: flex;
    flex-direction: column;
    gap: var(--spacing-4);
}

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

.training-card:hover {
    border-color: var(--success-color);
    box-shadow: var(--shadow);
}

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

.training-date {
    display: flex;
    flex-direction: column;
    align-items: center;
    min-width: 60px;
}

.date-day {
    font-size: var(--font-size-xl);
    font-weight: 700;
    color: var(--success-color);
}

.date-month {
    font-size: var(--font-size-xs);
    color: var(--gray-600);
    text-transform: uppercase;
}

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

.type-badge.koolisoit { background: var(--primary-color); }
.type-badge.takistussoit { background: var(--success-color); }
.type-badge.ratsastus { background: var(--warning-color); }
.type-badge.kestvusratsutamine { background: #8b5cf6; }
.type-badge.muu { background: var(--gray-600); }

.btn-icon {
    width: 32px;
    height: 32px;
    border: none;
    border-radius: var(--radius);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all var(--transition-fast);
}

.btn-danger {
    background: var(--danger-color);
    color: white;
}

.btn-danger:hover {
    background: #dc2626;
}

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

.training-details {
    display: flex;
    gap: var(--spacing-4);
    margin-bottom: var(--spacing-4);
    flex-wrap: wrap;
}

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

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

.training-section-item {
    margin-bottom: var(--spacing-3);
}

.section-label {
    font-weight: 500;
    color: var(--gray-700);
    margin-bottom: var(--spacing-1);
    font-size: var(--font-size-sm);
}

.section-content {
    color: var(--gray-600);
    line-height: 1.5;
}

/* 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;
}

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

.form-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: var(--spacing-4);
    margin-bottom: 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(--success-color);
    box-shadow: 0 0 0 3px color-mix(in srgb, var(--success-color) 10%, transparent);
}

.form-textarea {
    resize: vertical;
    min-height: 80px;
    font-family: inherit;
}

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

.empty-state p {
    color: var(--gray-600);
    margin-bottom: var(--spacing-6);
}

/* Responsive */
@media (max-width: 768px) {
    .page-header {
        flex-direction: column;
        align-items: stretch;
        gap: var(--spacing-4);
    }
    
    .month-selector {
        flex-direction: column;
        align-items: stretch;
        gap: var(--spacing-3);
    }
    
    .stats-grid {
        grid-template-columns: repeat(2, 1fr);
    }
    
    .training-header {
        flex-direction: column;
        align-items: flex-start;
        gap: var(--spacing-3);
    }
    
    .training-details {
        flex-direction: column;
        gap: var(--spacing-2);
    }
    
    .form-grid {
        grid-template-columns: 1fr;
    }
    
    .modal-actions {
        flex-direction: column;
    }
}
</style>

<script>
// Global modal functions are defined in main.js
// Additional training-specific functions can be added here

document.addEventListener('DOMContentLoaded', function() {
    // Auto-focus date input when modal opens
    const modal = document.getElementById('addTrainingModal');
    if (modal) {
        modal.addEventListener('show', function() {
            setTimeout(() => {
                const dateInput = document.getElementById('date');
                if (dateInput) {
                    dateInput.focus();
                }
            }, 100);
        });
    }
});
</script>

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