<?php
require_once 'config/config.php';
session_start();
require_once 'config/database.php';
require_once 'includes/functions.php';
require_once 'config/email.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 = '';
$success = '';
$step = 'request'; // request, success

// PARANDATUD: Kontrollime POST ja email olemasolu
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['email'])) {
    $email = getPost('email');
    
    if (empty($email)) {
        $error = 'Sisesta oma e-maili aadress';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'Sisesta kehtiv e-maili aadress';
    } else {
        try {
            // Otsi kasutajat
            $stmt = $pdo->prepare("SELECT id, firstName, lastName, email FROM users WHERE email = ? AND isActive = 1 AND email_verified = 1");
            $stmt->execute([$email]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($user) {
                // Genereeri reset token
                $reset_token = generateResetToken();
                $reset_expires = date('Y-m-d H:i:s', strtotime('+1 hour'));
                
                // Salvesta token andmebaasi
                $stmt = $pdo->prepare("
                    UPDATE users 
                    SET reset_token = ?, reset_expires = ?, updatedAt = CURRENT_TIMESTAMP 
                    WHERE id = ?
                ");
                $stmt->execute([$reset_token, $reset_expires, $user['id']]);
                
                // Saada taastamismail
                $full_name = $user['firstName'] . ' ' . $user['lastName'];
                $email_sent = sendPasswordResetEmail($user['email'], $full_name, $reset_token);
                
                if ($email_sent) {
                    // Logi email saatmine
                    try {
                        $stmt = $pdo->prepare("
                            INSERT INTO email_logs (user_id, email_type, recipient_email, subject, success)
                            VALUES (?, 'password_reset', ?, 'Parooli taastamine - Estreka Ratsaklubi', 1)
                        ");
                        $stmt->execute([$user['id'], $user['email']]);
                    } catch (Exception $e) {
                        error_log('Email log error: ' . $e->getMessage());
                    }
                    
                    // Logi tegevus
                    logActivity($user['id'], 'password_reset_requested', 'Password reset email sent');
                } else {
                    // Kustuta token kui mail ei läinud
                    $stmt = $pdo->prepare("UPDATE users SET reset_token = NULL, reset_expires = NULL WHERE id = ?");
                    $stmt->execute([$user['id']]);
                    
                    $error = 'Parooli taastamise maili saatmine ebaõnnestus. Palun proovi hiljem uuesti või võta ühendust administraatoriga.';
                }
            }
            
            // Turvalisuse mõttes näitame alati sama teadet
            if (!$error) {
                $success = 'Kui see e-maili aadress on meie süsteemis registreeritud, saadame parooli taastamise juhised.';
                $step = 'success';
            }
            
        } catch(PDOException $e) {
            $error = 'Parooli taastamine ebaõnnestus. Palun proovi hiljem uuesti.';
            error_log('Password reset error: ' . $e->getMessage());
        }
    }
}

$page_title = 'Parooli taastamine';
$page_description = 'Taasta oma Estreka Ratsaklubi konto parool.';
$body_class = 'forgot-password-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-lock"></i>
                    <h1>Parooli taastamine</h1>
                </div>
                <?php if ($step === 'request'): ?>
                    <h2 class="auth-title">Unustasid parooli?</h2>
                    <p class="auth-subtitle">
                        Sisesta oma e-mail ja me saadame sulle parooli taastamise juhised.
                        <br><a href="<?php echo url('login.php'); ?>">Tagasi sisselogimislehele</a>
                    </p>
                <?php else: ?>
                    <h2 class="auth-title">Kontrolli oma e-maili</h2>
                    <p class="auth-subtitle">
                        Saatsime sulle parooli taastamise juhised!
                    </p>
                <?php endif; ?>
            </div>

            <!-- Parooli taastamise vorm või tulemus -->
            <div class="auth-form-container">
                <?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; ?>

                <?php if ($step === 'request'): ?>
                    <!-- PARANDATUD VORM -->
                    <form method="POST" class="auth-form" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
                        <div class="form-group">
                            <label for="email" class="form-label">
                                <i class="icon-mail"></i>
                                E-maili aadress
                            </label>
                            <input 
                                type="email" 
                                id="email" 
                                name="email" 
                                class="form-input"
                                placeholder="Sisesta oma e-mail"
                                value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>"
                                required
                                autocomplete="email"
                            >
                        </div>

                        <!-- PARANDATUD NUPP -->
                        <button type="submit" class="btn btn-primary btn-large">
                            <i class="icon-mail"></i>
                            <span>Saada taastamislink</span>
                        </button>
                        
                        <!-- Peidetud field turvalisuse jaoks -->
                        <input type="hidden" name="form_action" value="reset_password">
                    </form>
                    
                <?php elseif ($step === 'success'): ?>
                    <!-- Email saadetud -->
                    <div class="reset-email-sent">
                        <div class="email-sent-icon">
                            <i class="icon-mail"></i>
                        </div>
                        
                        <div class="email-sent-content">
                            <h3>Parooli taastamislink saadetud!</h3>
                            <p>Kui sisestatud e-maili aadress on meie süsteemis registreeritud, saatsime sellele aadressile parooli taastamise juhised.</p>
                            
                            <div class="email-instructions">
                                <h4>Järgmised sammud:</h4>
                                <ol>
                                    <li>Kontrolli oma postkasti (ka rämpspost kausta)</li>
                                    <li>Kliki parooli taastamise lingile meilos</li>
                                    <li>Loo uus parool</li>
                                    <li>Logi sisse uue parooliga</li>
                                </ol>
                            </div>
                            
                            <div class="security-note">
                                <div class="security-icon">
                                    <i class="icon-info"></i>
                                </div>
                                <div class="security-text">
                                    <p><strong>Turvalisuse märkus:</strong></p>
                                    <p>Parooli taastamise link kehtib ainult 1 tund. Kui sa ei küsinud parooli taastamist, võid selle e-maili ignoreerida.</p>
                                </div>
                            </div>
                            
                            <div class="email-help">
                                <p><strong>Ei saanud maili?</strong></p>
                                <ul>
                                    <li>Kontrolli rämpspost (spam) kausta</li>
                                    <li>Oota mõni minut - meil võib aega võtta</li>
                                    <li>Veendu, et kasutasid õiget e-maili aadressi</li>
                                    <li>Kontrolli, et konto on kinnitatud</li>
                                </ul>
                            </div>
                        </div>
                        
                        <div class="email-actions">
                            <a href="<?php echo url('forgot-password.php'); ?>" class="btn btn-secondary">
                                <i class="icon-mail"></i>
                                <span>Saada uuesti</span>
                            </a>
                            <a href="<?php echo url('login.php'); ?>" class="btn btn-primary">
                                <i class="icon-log-in"></i>
                                <span>Tagasi sisselogimislehele</span>
                            </a>
                        </div>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Abi informatsioon -->
            <div class="auth-help">
                <div class="help-divider">
                    <span>Vajad abi?</span>
                </div>
                
                <div class="help-content">
                    <p>
                        Kui sul on endiselt probleeme sisselogimisega, võta ühendust 
                        <a href="mailto:<?php echo ADMIN_EMAIL; ?>"><?php echo ADMIN_EMAIL; ?></a>.
                    </p>
                    <?php if ($step === 'request'): ?>
                    <p>
                        <strong>Mäletad parooli?</strong> 
                        <a href="<?php echo url('login.php'); ?>">Logi sisse</a>
                    </p>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Lisainfo -->
        <div class="auth-info">
            <div class="info-card">
                <div class="info-icon">
                    <i class="icon-info"></i>
                </div>
                <h3>Turvalisuse nõuanded</h3>
                <ul>
                    <li>Kasuta tugevat parooli (vähemalt 8 tähemärki)</li>
                    <li>Ära jaga oma parooli kellegagi</li>
                    <li>Logi välja avalikest arvutitest</li>
                    <li>Muuda parooli regulaarselt</li>
                    <li>Ära kliki kahtlastele linkidele e-mailides</li>
                </ul>
            </div>
        </div>
    </div>
</main>

<style>
/* PARANDATUD CSS forgot-password.php jaoks - asenda kogu <style> sektsioon */

/* 🔧 PARANDUS 3: Forgot Password lehe täielik ümberkujundamine */

/* Üldine layout */
.forgot-password-page .auth-main {
    background: linear-gradient(135deg, var(--gray-50) 0%, var(--gray-100) 100%);
    min-height: 100vh;
    display: flex;
    align-items: center;
    padding: var(--spacing-6) 0;
}

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

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

/* Logo ja header */
.forgot-password-page .auth-logo {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: var(--spacing-3);
    margin-bottom: var(--spacing-6);
}

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

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

.forgot-password-page .auth-title {
    font-size: var(--font-size-xl);
    font-weight: 600;
    margin-bottom: var(--spacing-3);
    color: var(--gray-900);
    text-align: center;
}

.forgot-password-page .auth-subtitle {
    color: var(--gray-600);
    margin: 0 0 var(--spacing-6);
    line-height: 1.6;
    text-align: center;
}

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

/* Form stiilid */
.forgot-password-page .auth-form {
    margin-bottom: var(--spacing-6);
}

.forgot-password-page .form-group {
    margin-bottom: var(--spacing-5);
}

.forgot-password-page .form-label {
    display: flex;
    align-items: center;
    gap: var(--spacing-2);
    font-weight: 600;
    color: var(--gray-700);
    font-size: var(--font-size-sm);
    margin-bottom: var(--spacing-2);
}

.forgot-password-page .form-label i {
    color: var(--warning-color);
    width: 16px;
}

.forgot-password-page .form-input {
    width: 100%;
    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);
}

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

.forgot-password-page .btn-large {
    width: 100%;
    padding: var(--spacing-4) var(--spacing-6);
    font-size: var(--font-size-lg);
    font-weight: 600;
    border-radius: var(--radius-lg);
    background: var(--warning-color);
    color: white;
    border: none;
    cursor: pointer;
    transition: all var(--transition-fast);
    display: flex;
    align-items: center;
    justify-content: center;
    gap: var(--spacing-2);
}

.forgot-password-page .btn-large:hover {
    background: #d97706;
    transform: translateY(-1px);
    box-shadow: var(--shadow-lg);
}

/* Success states */
.email-sent-icon,
.success-icon {
    width: 80px;
    height: 80px;
    background: linear-gradient(135deg, var(--success-color), #059669);
    color: white;
    border-radius: var(--radius-full);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 2rem;
    margin: 0 auto var(--spacing-6);
}

.email-sent-content,
.success-content {
    text-align: center;
}

.email-sent-content h3,
.success-content h3 {
    color: var(--gray-900);
    margin-bottom: var(--spacing-4);
    font-size: var(--font-size-xl);
}

.email-instructions,
.help-box {
    text-align: left;
    background: var(--gray-50);
    padding: var(--spacing-5);
    border-radius: var(--radius-lg);
    margin: var(--spacing-6) 0;
    border: 1px solid var(--gray-200);
}

.email-instructions h4 {
    margin-bottom: var(--spacing-3);
    color: var(--gray-900);
}

.email-instructions ol,
.help-box ul {
    padding-left: var(--spacing-5);
    color: var(--gray-700);
}

.email-instructions li,
.help-box li {
    margin-bottom: var(--spacing-2);
    line-height: 1.5;
}

.security-note {
    display: flex;
    align-items: flex-start;
    gap: var(--spacing-3);
    text-align: left;
    background: color-mix(in srgb, var(--warning-color) 10%, transparent);
    border: 1px solid color-mix(in srgb, var(--warning-color) 20%, transparent);
    padding: var(--spacing-4);
    border-radius: var(--radius-lg);
    margin: var(--spacing-6) 0;
}

.security-icon {
    color: var(--warning-color);
    font-size: 1.2rem;
    flex-shrink: 0;
    margin-top: 2px;
}

.email-actions,
.success-actions {
    display: flex;
    gap: var(--spacing-4);
    justify-content: center;
    flex-wrap: wrap;
    margin-top: var(--spacing-8);
}

.email-actions .btn,
.success-actions .btn {
    padding: var(--spacing-3) var(--spacing-5);
    border-radius: var(--radius-lg);
    font-weight: 600;
    text-decoration: none;
    display: flex;
    align-items: center;
    gap: var(--spacing-2);
    transition: all var(--transition-fast);
}

.email-actions .btn-primary,
.success-actions .btn-primary {
    background: var(--primary-color);
    color: white;
    border: 2px solid var(--primary-color);
}

.email-actions .btn-primary:hover,
.success-actions .btn-primary:hover {
    background: var(--primary-dark);
    transform: translateY(-1px);
}

.email-actions .btn-secondary,
.success-actions .btn-secondary {
    background: white;
    color: var(--gray-700);
    border: 2px solid var(--gray-300);
}

.email-actions .btn-secondary:hover,
.success-actions .btn-secondary:hover {
    background: var(--gray-50);
    border-color: var(--gray-400);
}

/* Help section */
.help-divider {
    position: relative;
    margin: var(--spacing-8) 0 var(--spacing-4);
    color: var(--gray-500);
    font-size: var(--font-size-sm);
    text-align: center;
}

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

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

.help-content {
    text-align: center;
}

.help-content p {
    color: var(--gray-600);
    font-size: var(--font-size-sm);
    line-height: 1.5;
    margin-bottom: var(--spacing-3);
}

.help-content a {
    color: var(--primary-color);
    font-weight: 500;
}

/* Info card (parempoolne külg) */
.auth-info {
    background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
    color: white;
    border-radius: var(--radius-xl);
    padding: var(--spacing-8);
    box-shadow: var(--shadow-lg);
}

.auth-info .info-icon {
    width: 64px;
    height: 64px;
    background: rgba(255, 255, 255, 0.2);
    border-radius: var(--radius-full);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    margin-bottom: var(--spacing-6);
}

.auth-info h3 {
    margin-bottom: var(--spacing-4);
    font-size: var(--font-size-xl);
    font-weight: 600;
}

.auth-info ul {
    list-style: none;
}

.auth-info li {
    position: relative;
    padding-left: var(--spacing-4);
    margin-bottom: var(--spacing-3);
    opacity: 0.9;
    line-height: 1.5;
}

.auth-info li::before {
    content: '✓';
    position: absolute;
    left: 0;
    color: rgba(255, 255, 255, 0.8);
    font-weight: bold;
}

/* 🔧 RESPONSIVE PARANDUSED */
@media (max-width: 1024px) {
    .forgot-password-page .auth-container {
        grid-template-columns: 1fr;
        gap: var(--spacing-6);
        max-width: 600px;
    }
    
    .auth-info {
        order: -1;
    }
}

@media (max-width: 768px) {
    .forgot-password-page .auth-main {
        padding: var(--spacing-4) 0;
    }
    
    .forgot-password-page .auth-card {
        padding: var(--spacing-6);
    }
    
    .auth-info {
        padding: var(--spacing-6);
    }
    
    .email-actions,
    .success-actions {
        flex-direction: column;
    }
    
    .email-actions .btn,
    .success-actions .btn {
        width: 100%;
        justify-content: center;
    }
    
    .security-note {
        flex-direction: column;
        text-align: center;
    }
}

@media (max-width: 480px) {
    .forgot-password-page .auth-logo {
        margin-bottom: var(--spacing-4);
    }
    
    .forgot-password-page .auth-logo i {
        width: 64px;
        height: 64px;
        font-size: 2rem;
    }
    
    .forgot-password-page .auth-logo h1 {
        font-size: var(--font-size-xl);
    }
}
</style>

<script>
// Auto-focus email input
document.addEventListener('DOMContentLoaded', function() {
    const emailInput = document.getElementById('email');
    if (emailInput) {
        emailInput.focus();
    }
});

// Handle form submission
const form = document.querySelector('.auth-form');
if (form) {
    form.addEventListener('submit', function() {
        const submitBtn = this.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;
        
        submitBtn.innerHTML = '<i class="icon-loader icon-spin"></i><span>Saadan...</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'; ?>