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

// 🔧 UTF-8 parandus
header('Content-Type: text/html; charset=UTF-8');

require_once 'config/database.php';
require_once 'includes/functions.php';

// Kui kasutaja on juba sisse logitud, suuna ümber
if (isLoggedIn()) {
    $redirect_url = isAdmin() ? url('admin/dashboard.php') : url('athlete/dashboard.php');
    header('Location: ' . $redirect_url);
    exit;
}

$error = '';

// Töötle sisselogimist
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = getPost('username');
    $password = getPost('password');
    $remember = isset($_POST['remember']);
    
    if (empty($username) || empty($password)) {
        $error = 'Kasutajanimi ja parool on kohustuslikud';
    } else {
        try {
            // Otsi kasutajat
            $stmt = $pdo->prepare("SELECT * FROM users WHERE (username = ? OR email = ?) AND isActive = 1");
            $stmt->execute([$username, $username]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($user && verifyPassword($password, $user['password'])) {
                // Kontrolli email kinnitust ainult kui väli eksisteerib JA on EKSPLITSIITSELT 0
                if (isset($user['email_verified']) && $user['email_verified'] === 0) {
                    $error = 'Palun kinnita esmalt oma e-maili aadress. Kontrolli oma postkasti või <a href="' . url('register.php') . '">registreeru uuesti</a>.';
                    
                    // Logi ebaõnnestunud sisselogimine
                    logActivity($user['id'], 'login_failed', 'Login failed - email not verified');
                } else {
                    // Edukas sisselogimine
                    $_SESSION['user_id'] = $user['id'];
                    $_SESSION['username'] = $user['username'];
                    $_SESSION['user_name'] = $user['firstName'] . ' ' . $user['lastName'];
                    $_SESSION['user_role'] = $user['role'];
                    
                    // Logi tegevus
                    logActivity($user['id'], 'login', 'User logged in');
                    
                    // Remember me funktsioon (kui vaja)
                    if ($remember) {
                        // TODO: Implement remember me functionality with tokens
                    }
                    
                    // Suuna õigesse kohta
                    $redirect_url = $user['role'] === 'admin' ? url('admin/dashboard.php') : url('athlete/dashboard.php');
                    header('Location: ' . $redirect_url);
                    exit;
                }
            } else {
                $error = 'Vale kasutajanimi või parool';
                // Logi ebaõnnestunud sisselogimine
                if ($user) {
                    logActivity($user['id'], 'login_failed', 'Failed login attempt - wrong password');
                }
            }
            
        } catch(PDOException $e) {
            $error = 'Sisselogimine ebaõnnestus. Palun proovi hiljem uuesti.';
            error_log('Login error: ' . $e->getMessage());
        }
    }
}

$page_title = 'Sisselogimine';
$page_description = 'Logi sisse oma Estreka Ratsaklubi kontole, et näha oma tulemusi ja statistikat.';
$body_class = 'login-page';

include 'includes/header.php';
?>

<main class="auth-main">
    <div class="auth-container">
        <div class="auth-card">
            <!-- Logo ja pealkiri -->
            <div class="auth-header">
                <div class="auth-logo">
                    <i class="icon-trophy"></i>
                    <h1>Estreka Ratsaklubi</h1>
                </div>
                <h2 class="auth-title">Tere tulemast tagasi!</h2>
                <p class="auth-subtitle">
                    Logi sisse, et näha oma tulemusi ja statistikat.
                    <br><a href="<?php echo url(); ?>">Tagasi avalehele</a>
                </p>
            </div>

            <!-- Sisselogimise vorm -->
            <div class="auth-form-container">
                <?php if ($error): ?>
                    <div class="alert alert-error">
                        <i class="icon-alert-circle"></i>
                        <span><?php echo $error; ?></span>
                    </div>
                <?php endif; ?>

                <form method="POST" class="auth-form">
                    <div class="form-group">
                        <label for="username" class="form-label">
                            <i class="icon-user"></i>
                            Kasutajanimi või e-mail
                        </label>
                        <input 
                            type="text" 
                            id="username" 
                            name="username" 
                            class="form-input"
                            placeholder="Sisesta kasutajanimi või e-mail"
                            value="<?php echo htmlspecialchars($username ?? ''); ?>"
                            required
                            autocomplete="username"
                        >
                    </div>

                    <div class="form-group">
                        <label for="password" class="form-label">
                            <i class="icon-lock"></i>
                            Parool
                        </label>
                        <div class="password-input-container">
                            <input 
                                type="password" 
                                id="password" 
                                name="password" 
                                class="form-input"
                                placeholder="Sisesta oma parool"
                                required
                                autocomplete="current-password"
                            >
                            <button type="button" class="password-toggle" onclick="togglePassword('password')">
                                <i class="icon-eye" id="password-toggle-icon"></i>
                            </button>
                        </div>
                    </div>

                    <div class="form-options">
                        <label class="checkbox-label">
                            <input type="checkbox" name="remember" class="checkbox-input">
                            <span class="checkbox-custom"></span>
                            <span class="checkbox-text">Jäta mind meelde</span>
                        </label>
                        
                        <a href="<?php echo url('forgot-password.php'); ?>" class="forgot-link">
                            Unustasid parooli?
                        </a>
                    </div>

                    <button type="submit" class="btn btn-primary btn-large">
                        <i class="icon-log-in"></i>
                        <span>Logi sisse</span>
                    </button>
                </form>
            </div>

            <!-- Registreerimise link -->
            <div class="auth-footer">
                <div class="auth-divider">
                    <span>Pole veel kontot?</span>
                </div>
                
                <a href="<?php echo url('register.php'); ?>" class="btn btn-outline btn-large">
                    <i class="icon-user"></i>
                    <span>Loo uus konto</span>
                </a>
            </div>
        </div>

        <!-- Lisainfo -->
        <div class="auth-info">
            <div class="info-card">
                <div class="info-icon">
                    <i class="icon-info"></i>
                </div>
                <h3>Miks registreeruda?</h3>
                <ul>
                    <li>Jälgi oma võistluste tulemusi</li>
                    <li>Vaata oma positsiooni hooaja tabelites</li>
                    <li>Pea treeningu päevikut</li>
                    <li>Saa ülevaade oma progressist</li>
                </ul>
            </div>
        </div>
    </div>
</main>

<style>
/* Login Page Base */
.login-page {
    background: linear-gradient(135deg, var(--gray-50) 0%, var(--gray-100) 100%);
    min-height: 100vh;
}

.auth-main {
    padding: var(--spacing-8) 0;
    min-height: 100vh;
    display: flex;
    align-items: center;
}

.auth-container {
    max-width: 1000px;
    margin: 0 auto;
    padding: 0 var(--spacing-4);
    display: grid;
    grid-template-columns: 1fr 300px;
    gap: var(--spacing-8);
    align-items: start;
}

/* Auth Card */
.auth-card {
    background: white;
    border-radius: var(--radius-2xl);
    box-shadow: var(--shadow-xl);
    padding: var(--spacing-8);
    width: 100%;
    border: 1px solid var(--gray-200);
}

/* Header */
.auth-header {
    text-align: center;
    margin-bottom: var(--spacing-8);
}

.auth-logo {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: var(--spacing-3);
    margin-bottom: var(--spacing-6);
}

.auth-logo i {
    font-size: 3rem;
    color: var(--primary-color);
    background: color-mix(in srgb, var(--primary-color) 10%, transparent);
    padding: var(--spacing-4);
    border-radius: var(--radius-full);
    width: 80px;
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.auth-logo h1 {
    font-size: var(--font-size-2xl);
    font-weight: 700;
    color: var(--gray-900);
    margin: 0;
}

.auth-title {
    font-size: var(--font-size-xl);
    font-weight: 600;
    margin-bottom: var(--spacing-3);
    color: var(--gray-900);
}

.auth-subtitle {
    color: var(--gray-600);
    margin: 0;
    line-height: 1.6;
}

.auth-subtitle a {
    color: var(--primary-color);
    font-weight: 500;
}

/* Form Container */
.auth-form-container {
    margin-bottom: var(--spacing-6);
}

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

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

.form-label {
    display: flex;
    align-items: center;
    gap: var(--spacing-2);
    font-weight: 500;
    color: var(--gray-700);
    font-size: var(--font-size-sm);
}

.form-label i {
    color: var(--primary-color);
}

.form-input {
    padding: var(--spacing-4);
    border: 2px solid var(--gray-200);
    border-radius: var(--radius-lg);
    font-size: var(--font-size-base);
    transition: all var(--transition-fast);
    background: var(--gray-50);
}

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

/* Password Input */
.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 Options */
.form-options {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: var(--spacing-4);
}

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

.checkbox-input {
    display: none;
}

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

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

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

.forgot-link {
    color: var(--primary-color);
    font-size: var(--font-size-sm);
    text-decoration: none;
}

.forgot-link:hover {
    text-decoration: underline;
}

/* Buttons */
.btn-large {
    padding: var(--spacing-4) var(--spacing-6);
    font-size: var(--font-size-base);
    font-weight: 600;
    justify-content: center;
    border-radius: var(--radius-lg);
    width: 100%;
    display: flex;
    align-items: center;
    gap: var(--spacing-2);
    border: none;
    cursor: pointer;
    transition: all var(--transition-fast);
}

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

.btn-primary:hover {
    background-color: var(--primary-dark);
    transform: translateY(-1px);
    box-shadow: var(--shadow-lg);
}

/* Auth Footer */
.auth-footer {
    text-align: center;
    margin-top: var(--spacing-6);
    padding-top: var(--spacing-6);
    border-top: 1px solid var(--gray-200);
}

.auth-divider {
    position: relative;
    margin-bottom: var(--spacing-6);
    color: var(--gray-500);
    font-size: var(--font-size-sm);
}

.auth-divider::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 0;
    right: 0;
    height: 1px;
    background-color: var(--gray-200);
    z-index: 1;
}

.auth-divider span {
    background: white;
    padding: 0 var(--spacing-4);
    position: relative;
    z-index: 2;
    display: inline-block;
}

/* "Loo uus konto" nupp */
.auth-footer .btn-outline {
    background-color: white;
    color: var(--primary-color);
    border: 2px solid var(--primary-color);
    padding: var(--spacing-4) var(--spacing-6);
    font-weight: 600;
    border-radius: var(--radius-lg);
    transition: all var(--transition-fast);
    width: 100%;
    justify-content: center;
    font-size: var(--font-size-base);
    display: flex;
    align-items: center;
    gap: var(--spacing-2);
    text-decoration: none;
    box-shadow: var(--shadow-sm);
}

.auth-footer .btn-outline:hover {
    background-color: var(--primary-color);
    color: white;
    transform: translateY(-1px);
    box-shadow: var(--shadow-lg);
}

/* 🔧 PARANDATUD Info Card - hästi loetav */
.auth-info {
    background: white;
    color: var(--gray-900);
    border-radius: var(--radius-lg);
    box-shadow: var(--shadow-lg);
    padding: var(--spacing-6);
    border: 1px solid var(--gray-200);
}

.info-icon {
    width: 48px;
    height: 48px;
    background: color-mix(in srgb, var(--primary-color) 10%, transparent);
    color: var(--primary-color);
    border-radius: var(--radius-lg);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    margin-bottom: var(--spacing-4);
}

.auth-info h3 {
    margin-bottom: var(--spacing-4);
    color: var(--gray-900);
    font-size: var(--font-size-lg);
}

.auth-info ul {
    list-style: none;
    display: flex;
    flex-direction: column;
    gap: var(--spacing-2);
}

.auth-info li {
    position: relative;
    padding-left: var(--spacing-4);
    color: var(--gray-700);
    font-size: var(--font-size-sm);
    line-height: 1.5;
}

.auth-info li::before {
    content: '✓';
    position: absolute;
    left: 0;
    color: var(--success-color);
    font-weight: bold;
}

/* Alerts */
.alert {
    padding: var(--spacing-4);
    border-radius: var(--radius);
    margin-bottom: var(--spacing-4);
    display: flex;
    align-items: center;
    gap: var(--spacing-3);
}

.alert-error {
    background-color: color-mix(in srgb, var(--danger-color) 10%, transparent);
    color: var(--danger-color);
    border: 1px solid color-mix(in srgb, var(--danger-color) 20%, transparent);
}

.alert-error a {
    color: inherit;
    text-decoration: underline;
    font-weight: 500;
}

.alert-error a:hover {
    text-decoration: none;
}

/* Responsive */
@media (max-width: 1024px) {
    .auth-container {
        grid-template-columns: 1fr;
        max-width: 500px;
    }
    
    .auth-info {
        order: -1;
    }
}

@media (max-width: 768px) {
    .auth-main {
        padding: var(--spacing-4) 0;
    }
    
    .auth-card {
        padding: var(--spacing-6);
    }
    
    .form-options {
        flex-direction: column;
        align-items: flex-start;
        gap: var(--spacing-3);
    }
}
</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';
    }
}

// Auto-focus username input
document.addEventListener('DOMContentLoaded', function() {
    const usernameInput = document.getElementById('username');
    if (usernameInput) {
        usernameInput.focus();
    }
});

// Handle form submission
document.querySelector('.auth-form').addEventListener('submit', function() {
    const submitBtn = this.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    
    submitBtn.innerHTML = '<i class="icon-loader animate-spin"></i><span>Sisselogimine...</span>';
    submitBtn.disabled = true;
    
    // Reset after 10 seconds if something goes wrong
    setTimeout(function() {
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
    }, 10000);
});
</script>

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