<?php
/**
 * TraderAlign — Forgot Password Page
 * Handles password reset requests with rate limiting and security measures
 */

require_once __DIR__ . '/../config/config.php';

// Start session for CSRF protection — session_name(SESSION_NAME) matters
// here: without it, a direct (router-bypassing) hit on this file would
// start a session under PHP's default name instead of the app's own
// cookie, splitting this page's session state from the rest of the app.
if (session_status() === PHP_SESSION_NONE) {
    session_name(SESSION_NAME);
    session_start();
}

// Generate CSRF token if not exists
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$error = $_GET['error'] ?? '';
$sent = $_GET['sent'] ?? '';
$errorType = $_GET['type'] ?? 'error'; // error, warning, info

// Map error types to CSS classes
$errorClass = match($errorType) {
    'warning' => 'warning-msg',
    'info' => 'info-msg',
    default => 'error-msg',
};

// Custom error messages for better UX
$errorMessages = [
    'invalid_email' => 'Please enter a valid email address.',
    'rate_limit' => 'Too many attempts. Please try again in 15 minutes.',
    'user_not_found' => 'If an account with that email exists, a reset link has been sent.',
    'send_failed' => 'Unable to send email. Please try again later.',
    'system_error' => 'A system error occurred. Please try again later.',
    'invalid_token' => 'Invalid or expired reset token. Please request a new one.',
    'token_expired' => 'Reset link has expired. Please request a new one.',
    'password_mismatch' => 'Passwords do not match.',
    'password_weak' => 'Password must be at least 8 characters with uppercase, lowercase, and numbers.',
];

$displayError = $errorMessages[$error] ?? $error;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="noindex, nofollow">
<title>Forgot Password - TraderAlign</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/traderalign/assets/tokens.css">
<link rel="icon" type="image/png" sizes="32x32" href="/traderalign/assets/favicon/favicon-32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/traderalign/assets/favicon/favicon-16.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/traderalign/assets/favicon/apple-touch-icon.png">
    <link rel="shortcut icon" href="/traderalign/assets/favicon/favicon.ico">
<link rel="stylesheet" href="/traderalign/assets/css/brand.css">
<style>
.auth-page{min-height:100vh;display:flex;align-items:center;justify-content:center;padding:2rem;background:var(--background)}
.auth-card{width:100%;max-width:26rem;background:var(--background-elevated);border:1px solid var(--border);border-radius:var(--radius-xl);padding:2.5rem;box-shadow:0 4px 6px -1px rgba(0,0,0,0.1),0 2px 4px -2px rgba(0,0,0,0.1)}
.auth-card h1{font-size:1.5rem;font-weight:700;color:var(--foreground);margin-bottom:.5rem}
.auth-card .sub{color:var(--foreground-muted);font-size:.9rem;margin-bottom:2rem;line-height:1.5}
.form-group{margin-bottom:1.25rem;position:relative}
.form-group label{display:block;font-size:.875rem;font-weight:500;color:var(--foreground);margin-bottom:.375rem}
.form-group input{width:100%;height:2.75rem;padding:0 .875rem;background:var(--background-surface);border:1px solid var(--border);border-radius:var(--radius-md);color:var(--foreground);font-family:inherit;font-size:.95rem;transition:border-color 0.2s ease,box-shadow 0.2s ease}
.form-group input:focus{outline:none;border-color:var(--primary);box-shadow:0 0 0 3px color-mix(in srgb,var(--primary) 15%,transparent)}
.form-group input.error{border-color:var(--negative)}
.form-group .field-error{display:none;font-size:.75rem;color:var(--negative);margin-top:.25rem}
.form-group .field-error.show{display:block}
.loading-spinner{display:none;width:1rem;height:1rem;border:2px solid rgba(255,255,255,0.3);border-top-color:#fff;border-radius:50%;animation:spin 0.6s linear infinite;margin-right:.5rem}
@keyframes spin{to{transform:rotate(360deg)}}
.success-msg{background:color-mix(in srgb,var(--positive) 12%,transparent);border:1px solid color-mix(in srgb,var(--positive) 25%,transparent);color:var(--positive);padding:.75rem 1rem;border-radius:var(--radius-md);font-size:.875rem;margin-bottom:1.5rem;line-height:1.5;display:flex;align-items:flex-start;gap:.5rem}
.success-msg .icon{flex-shrink:0;margin-top:2px}
.error-msg{background:color-mix(in srgb,var(--negative) 12%,transparent);border:1px solid var(--negative);color:var(--negative);padding:.75rem 1rem;border-radius:var(--radius-md);font-size:.875rem;margin-bottom:1.5rem;line-height:1.5}
.warning-msg{background:color-mix(in srgb,var(--warning) 12%,transparent);border:1px solid var(--warning);color:var(--warning);padding:.75rem 1rem;border-radius:var(--radius-md);font-size:.875rem;margin-bottom:1.5rem;line-height:1.5}
.info-msg{background:color-mix(in srgb,var(--primary) 12%,transparent);border:1px solid var(--primary);color:var(--primary);padding:.75rem 1rem;border-radius:var(--radius-md);font-size:.875rem;margin-bottom:1.5rem;line-height:1.5}
.footer-text{text-align:center;margin-top:1.5rem;font-size:.875rem;color:var(--foreground-muted)}
.footer-text a{color:var(--primary);font-weight:500;text-decoration:none;transition:opacity 0.2s ease}
.footer-text a:hover{opacity:0.8}
.btn-primary{position:relative;display:flex;align-items:center;justify-content:center;gap:.5rem;transition:all 0.2s ease}
.btn-primary:disabled{opacity:0.6;cursor:not-allowed}
.security-notice{font-size:.75rem;color:var(--foreground-dim);text-align:center;margin-top:1rem;line-height:1.4}
.auth-brand{display:flex;justify-content:center;margin-bottom:1.75rem}
</style>
</head>
<body class="auth-page">
<div class="auth-card">
    <div class="auth-brand"><a href="/traderalign/"><img src="/traderalign/images/logo.png" alt="TraderAlign" class="ta-logo ta-logo--xl"></a></div>
    <h1>Reset your password</h1>
    <p class="sub">Enter your email address and we'll send you a link to reset your password.</p>

    <?php if ($sent): ?>
    <div class="success-msg">
        <span class="icon">✓</span>
        <span>If an account with that email exists, a reset link has been sent. Please check your inbox and spam folder. The link expires in 1 hour.</span>
    </div>
    <?php endif; ?>

    <?php if ($error): ?>
    <div class="<?= $errorClass ?>">
        <?= htmlspecialchars($displayError) ?>
    </div>
    <?php endif; ?>

    <form id="forgotPasswordForm" method="POST" action="/traderalign/api/auth/forgot-password" novalidate>
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
        
        <div class="form-group">
            <label for="email">Email address</label>
            <input 
                type="email" 
                id="email" 
                name="email" 
                required 
                autocomplete="email" 
                placeholder="you@example.com"
                aria-describedby="emailError"
                <?= $error ? 'class="error"' : '' ?>
            >
            <div class="field-error" id="emailError">Please enter a valid email address.</div>
        </div>
        
        <button type="submit" class="btn btn-primary btn-lg" id="submitBtn" style="width:100%">
            <span class="loading-spinner" id="loadingSpinner"></span>
            <span id="btnText">Send Reset Link</span>
        </button>
    </form>
    
    <p class="footer-text">
        <a href="/traderalign/sign-in">← Back to sign in</a>
    </p>
    
    <p class="security-notice">
        For security, reset links expire after 1 hour and can only be used once.
    </p>
</div>

<script>
// Client-side form validation and UX improvements
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('forgotPasswordForm');
    const emailInput = document.getElementById('email');
    const submitBtn = document.getElementById('submitBtn');
    const loadingSpinner = document.getElementById('loadingSpinner');
    const btnText = document.getElementById('btnText');
    const emailError = document.getElementById('emailError');
    
    // Email validation regex
    const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    
    // Real-time email validation
    emailInput.addEventListener('input', function() {
        if (this.value.length > 0 && !emailRegex.test(this.value)) {
            this.classList.add('error');
            emailError.classList.add('show');
        } else {
            this.classList.remove('error');
            emailError.classList.remove('show');
        }
    });
    
    // Form submission with loading state
    form.addEventListener('submit', function(e) {
        const email = emailInput.value.trim();
        
        // Client-side validation
        if (!email) {
            e.preventDefault();
            emailInput.classList.add('error');
            emailError.textContent = 'Email address is required.';
            emailError.classList.add('show');
            emailInput.focus();
            return;
        }
        
        if (!emailRegex.test(email)) {
            e.preventDefault();
            emailInput.classList.add('error');
            emailError.textContent = 'Please enter a valid email address.';
            emailError.classList.add('show');
            emailInput.focus();
            return;
        }
        
        // Show loading state
        submitBtn.disabled = true;
        loadingSpinner.style.display = 'inline-block';
        btnText.textContent = 'Sending...';
        
        // Re-enable after 10 seconds if something goes wrong
        setTimeout(function() {
            if (submitBtn.disabled) {
                submitBtn.disabled = false;
                loadingSpinner.style.display = 'none';
                btnText.textContent = 'Send Reset Link';
            }
        }, 10000);
    });
    
    // Focus on email input if there's an error
    <?php if ($error && !$sent): ?>
    emailInput.focus();
    <?php endif; ?>
    
    // Prevent double submission
    let formSubmitted = false;
    form.addEventListener('submit', function(e) {
        if (formSubmitted) {
            e.preventDefault();
            return false;
        }
        formSubmitted = true;
    });
});
</script>
</body>
</html>