<?php
define('SECURE_ACCESS', true);
require_once __DIR__ . '/config.php';
require_once 'includes/password_reset_helper.php';

// Rate limiting for password reset requests
if (!isset($_SESSION['reset_attempts'])) {
    $_SESSION['reset_attempts'] = 0;
    $_SESSION['last_reset_attempt'] = time();
}

// Reset attempts after 15 minutes
if (time() - $_SESSION['last_reset_attempt'] > 900) {
    $_SESSION['reset_attempts'] = 0;
}

$success = false;
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Check rate limiting
    if ($_SESSION['reset_attempts'] >= 3) {
        $time_remaining = 900 - (time() - $_SESSION['last_reset_attempt']);
        if ($time_remaining > 0) {
            $minutes = ceil($time_remaining / 60);
            $error = "Too many password reset attempts. Please try again in {$minutes} minute(s).";
        } else {
            $_SESSION['reset_attempts'] = 0;
        }
    }
    
    if (empty($error)) {
        $email = trim($_POST['email']);
        
        if (empty($email)) {
            $error = 'Please enter your email address.';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Please enter a valid email address.';
        } else {
            try {
                $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
                $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                
                // Check if user exists
                $stmt = $pdo->prepare("SELECT id, email, firstName, username FROM members WHERE email = ? AND suspended = 0");
                $stmt->execute([$email]);
                $user = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($user) {
                    // Generate secure reset token
                    $token = bin2hex(random_bytes(32));
                    $expires_at = date('Y-m-d H:i:s', strtotime('+1 hour'));
                    
                    // Get client info
                    $ip_address = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
                    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
                    
                    // Mark any existing unused tokens as used
                    $markUsed = $pdo->prepare("UPDATE password_resets SET used = 1 WHERE member_id = ? AND used = 0");
                    $markUsed->execute([$user['id']]);
                    
                    // Insert new reset token
                    $insertStmt = $pdo->prepare("
                        INSERT INTO password_resets (member_id, email, token, expires_at, ip_address, user_agent) 
                        VALUES (?, ?, ?, ?, ?, ?)
                    ");
                    $insertStmt->execute([
                        $user['id'],
                        $email,
                        $token,
                        $expires_at,
                        $ip_address,
                        $user_agent
                    ]);
                    
                    // Build reset URL
                    $resetUrl = BASE_URL . 'reset_password.php?token=' . $token;
                    
                    // Send email
                    $emailSent = sendPasswordResetEmail($email, $user['firstName'], $token, $resetUrl);
                    
                    if ($emailSent) {
                        $success = true;
                        $_SESSION['reset_attempts'] = 0; // Reset on success
                    } else {
                        $error = 'Failed to send reset email. Please try again or contact support.';
                        $_SESSION['reset_attempts']++;
                        $_SESSION['last_reset_attempt'] = time();
                    }
                } else {
                    // Don't reveal if email exists or not (security best practice)
                    // Show success message even if email doesn't exist
                    $success = true;
                }
                
            } catch (PDOException $e) {
                error_log("Password reset error: " . $e->getMessage());
                $error = 'Database error. Please try again later.';
                $_SESSION['reset_attempts']++;
                $_SESSION['last_reset_attempt'] = time();
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Forgot Password - <?php echo BRAND_NAME; ?></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@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="/includes/css/login.css">
</head>
<body>
    <div class="login-container">
        <div class="login-card">
            <div class="logo">
                <div class="logo-text"><?php echo BRAND_NAME; ?></div>
                <div class="logo-subtitle">AI-Powered Fantasy Creation</div>
            </div>

            <h1 class="login-title">Forgot Password?</h1>
            <p class="login-subtitle">Enter your email to reset your password</p>

            <?php if ($success): ?>
                <div class="success-message" style="background-color: #d4edda; color: #155724; padding: 15px; border-radius: 8px; margin-bottom: 20px; border: 1px solid #c3e6cb;">
                    <strong>✓ Check your email!</strong><br>
                    If an account exists with that email address, we've sent password reset instructions. Please check your inbox and spam folder.
                </div>
                <div class="footer" style="text-align: center;">
                    <p><a href="index.php">← Back to Login</a></p>
                </div>
            <?php else: ?>
                <?php if (!empty($error)): ?>
                    <div class="error-message">
                        <?php echo htmlspecialchars($error); ?>
                    </div>
                <?php endif; ?>

                <form method="POST" action="">
                    <div class="form-group">
                        <label class="form-label" for="email">Email Address</label>
                        <input
                            type="email"
                            id="email"
                            name="email"
                            class="form-input"
                            required
                            autocomplete="email"
                            placeholder="Enter your email address"
                            value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>"
                        >
                        <small style="color: #666; font-size: 0.85rem; display: block; margin-top: 8px;">
                            We'll send you a link to reset your password
                        </small>
                    </div>

                    <button type="submit" class="login-btn">Send Reset Link</button>
                </form>

                <div class="footer">
                    <p>Remember your password? <a href="index.php">Back to Login</a></p>
                </div>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>
