<?php
require_once 'config/config.php';
session_start();
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 = '';
$success = '';
$token = getGet('token');
$step = 'validate'; // validate, reset, success
$user = null;

// Kontrolli kas token on antud
if (empty($token)) {
    $error = 'Parooli taastamise link on kehtetu või puudub token.';
    $step = 'error';
} else {
    // Kontrolli token andmebaasist
    try {
        $stmt = $pdo->prepare("
            SELECT id, firstName, lastName, email, reset_token, reset_expires 
            FROM users 
            WHERE reset_token = ? AND reset_expires > datetime('now') AND isActive = 1
        ");
        $stmt->execute([$token]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$user) {
            $error = 'Parooli taastamise link on kehtetu või aegunud. Palun küsi uus link.';
            $step = 'error';
        } else {
            $step = 'reset';
        }
    } catch (PDOException $e) {
        $error = 'Andmebaasi viga. Palun proovi hiljem uuesti.';
        $step = 'error';
        error_log('Reset password token validation error: ' . $e->getMessage());
    }
}

// Töötle uue parooli seadmist
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['password']) && $user) {
    $password = getPost('password');
    $confirm_password = getPost('confirm_password');
    
    if (empty($password)) {
        $error = 'Sisesta uus parool';
    } elseif (strlen($password) < 6) {
        $error = 'Parool peab olema vähemalt 6 tähemärki pikk';
    } elseif ($password !== $confirm_password) {
        $error = 'Paroolid ei kattu';
    } else {
        try {
            // Uuenda parooli ja kustuta reset token
            $hashed_password = hashPassword($password);
            $stmt = $pdo->prepare("
                UPDATE users 
                SET password = ?, reset_token = NULL, reset_expires = NULL, updatedAt = CURRENT_TIMESTAMP 
                WHERE id = ?
            ");
            $stmt->execute([$hashed_password, $user['id']]);
            
            // Logi tegevus
            logActivity($user['id'], 'password_reset_completed', 'Password successfully reset');
            
            $success = 'Parool edukalt muudetud! Nüüd saad uue parooliga sisse logida.';
            $step = 'success';
            
        } catch (PDOException $e) {
            $error = 'Parooli muutmine ebaõnnestus. Palun proovi hiljem uuesti.';
            error_log('Password reset update error: ' . $e->getMessage());
        }
    }
}

$page_title = 'Uue parooli seadmine';
$page_description = 'Seadista oma Estreka Ratsaklubi konto uus parool.';
$body_class = 'reset-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>Uue parooli seadmine</h1>
                </div>
                
                <?php if ($step === 'reset'): ?>
                    <h2 class="auth-title">Seadista uus parool</h2>
                    <p class="auth-subtitle">
                        Kasutaja: <strong><?php echo htmlspecialchars($user['firstName'] . ' ' . $user['lastName']); ?></strong>
                        <br>Email: <strong><?php echo htmlspecialchars($user['email']); ?></strong>
                    </p>
                <?php elseif ($step === 'success'): ?>
                    <h2 class="auth-title">Parool muudetud!</h2>
                    <p class="auth-subtitle">
                        Sinu parool on edukalt uuendatud.
                    </p>
                <?php else: ?>
                    <h2 class="auth-title">Parooli taastamine</h2>
                    <p class="auth-subtitle">
                        Parooli taastamise link ei ole kehtiv.
                    </p>
                <?php endif; ?>
            </div>

            <!-- Parooli seadmise 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 === 'reset'): ?>
                    <!-- Parooli seadmise vorm -->
                    <form method="POST" class="auth-form" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'] . '?token=' . urlencode($token)); ?>">
                        <div class="form-group">
                            <label for="password" class="form-label">
                                <i class="icon-lock"></i>
                                Uus parool
                            </label>
                            <input 
                                type="password" 
                                id="password" 
                                name="password" 
                                class="form-input"
                                placeholder="Sisesta uus parool"
                                required
                                minlength="6"
                                autocomplete="new-password"
                            >
                            <div class="form-help">
                                Vähemalt 6 tähemärki
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="confirm_password" class="form-label">
                                <i class="icon-lock"></i>
                                Kinnita parool
                            </label>
                            <input 
                                type="password" 
                                id="confirm_password" 
                                name="confirm_password" 
                                class="form-input"
                                placeholder="Sisesta parool uuesti"
                                required
                                minlength="6"
                                autocomplete="new-password"
                            >
                        </div>

                        <button type="submit" class="btn btn-primary btn-large">
                            <i class="icon-save"></i>
                            <span>Salvesta uus parool</span>
                        </button>
                    </form>
                    
                <?php elseif ($step === 'success'): ?>
                    <!-- Parool muudetud -->
                    <div class="password-reset-success">
                        <div class="success-icon">
                            <i class="icon-check-circle"></i>
                        </div>
                        
                        <div class="success-content">
                            <h3>Parool edukalt muudetud!</h3>
                            <p>Sinu parool on edukalt uuendatud. Nüüd saad uue parooliga sisse logida.</p>
                            
                            <div class="success-actions">
                                <a href="<?php echo url('login.php'); ?>" class="btn btn-primary btn-large">
                                    <i class="icon-log-in"></i>
                                    <span>Logi sisse</span>
                                </a>
                            </div>
                        </div>
                    </div>
                    
                <?php else: ?>
                    <!-- Viga või kehtetu token -->
                    <div class="password-reset-error">
                        <div class="error-icon">
                            <i class="icon-alert-circle"></i>
                        </div>
                        
                        <div class="error-content">
                            <h3>Link ei ole kehtiv</h3>
                            <p>Parooli taastamise link on kehtetu, aegunud või juba kasutatud.</p>
                            
                            <div class="error-actions">
                                <a href="<?php echo url('forgot-password.php'); ?>" class="btn btn-primary">
                                    <i class="icon-mail"></i>
                                    <span>Küsi uus link</span>
                                </a>
                                <a href="<?php echo url('login.php'); ?>" class="btn btn-secondary">
                                    <i class="icon-log-in"></i>
                                    <span>Sisselogimislehele</span>
                                </a>
                            </div>
                        </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, võta ühendust 
                        <a href="mailto:<?php echo ADMIN_EMAIL; ?>"><?php echo ADMIN_EMAIL; ?></a>.
                    </p>
                </div>
            </div>
        </div>

        <!-- Parooli nõuanded -->
        <div class="auth-info">
            <div class="info-card">
                <div class="info-icon">
                    <i class="icon-info"></i>
                </div>
                <h3>Tugeva parooli nõuanded</h3>
                <ul>
                    <li>Kasuta vähemalt 8 tähemärki</li>
                    <li>Kombineeri suuri ja väikesi tähti</li>
                    <li>Lisa numbreid ja erimärke</li>
                    <li>Ära kasuta lihtsaid sõnu</li>
                    <li>Ära jaga parooli kellegagi</li>
                </ul>
            </div>
        </div>
    </div>
</main>

<style>
/* Reset Password Page Styles */
.reset-password-page .auth-logo i {
    color: var(--success-color);
}

/* Password reset success styles */
.password-reset-success {
    text-align: center;
    padding: var(--spacing-6) var(--spacing-4);
}

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

.success-content h3 {
    color: var(--gray-900);
    margin-bottom: var(--spacing-4);
}

.success-content p {
    color: var(--gray-700);
    margin-bottom: var(--spacing-6);
    line-height: 1.6;
}

.success-actions {
    display: flex;
    justify-content: center;
}

/* Password reset error styles */
.password-reset-error {
    text-align: center;
    padding: var(--spacing-6) var(--spacing-4);
}

.error-icon {
    width: 80px;
    height: 80px;
    background: linear-gradient(135deg, var(--danger-color), #dc2626);
    color: white;
    border-radius: var(--radius-full);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 2rem;
    margin: 0 auto var(--spacing-6);
}

.error-content h3 {
    color: var(--gray-900);
    margin-bottom: var(--spacing-4);
}

.error-content p {
    color: var(--gray-700);
    margin-bottom: var(--spacing-6);
    line-height: 1.6;
}

.error-actions {
    display: flex;
    gap: var(--spacing-4);
    justify-content: center;
    flex-wrap: wrap;
}

/* Form styles */
.form-help {
    font-size: var(--font-size-xs);
    color: var(--gray-500);
    margin-top: var(--spacing-2);
}

.help-divider {
    position: relative;
    margin: var(--spacing-6) 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;
}

/* Mobile responsive */
@media (max-width: 768px) {
    .error-actions {
        flex-direction: column;
    }
}
</style>

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

// Password confirmation validation
const form = document.querySelector('.auth-form');
if (form) {
    form.addEventListener('submit', function(e) {
        const password = document.getElementById('password').value;
        const confirmPassword = document.getElementById('confirm_password').value;
        
        if (password !== confirmPassword) {
            e.preventDefault();
            alert('Paroolid ei kattu!');
            return false;
        }
        
        // Show loading state
        const submitBtn = this.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;
        
        submitBtn.innerHTML = '<i class="icon-loader icon-spin"></i><span>Salvestamine...</span>';
        submitBtn.disabled = true;
        
        // Reset after 10 seconds if something goes wrong
        setTimeout(function() {
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
        }, 10000);
    });
    
    // Real-time password confirmation check
    const confirmInput = document.getElementById('confirm_password');
    if (confirmInput) {
        confirmInput.addEventListener('input', function() {
            const password = document.getElementById('password').value;
            const confirmPassword = this.value;
            
            if (confirmPassword && password !== confirmPassword) {
                this.setCustomValidity('Paroolid ei kattu');
            } else {
                this.setCustomValidity('');
            }
        });
    }
}
</script>

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