<?php
require_once 'config/database.php';
require_once 'config/auth.php';
require_once 'includes/functions.php';

if (isLoggedIn()) {
    header('Location: ' . getDashboardUrl());
    exit;
}

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $email = trim($_POST['email'] ?? '');

    if (empty($email)) {
        $error = 'Email address is required';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'Please enter a valid email address';
    } else {
        $token = generatePasswordResetToken($email);
        if ($token) {
            $success = 'Password reset instructions have been sent to your email address.';
            // In a real application, you would send an email here
            // For demo purposes, we'll show the reset link
            $resetLink = "http://" . $_SERVER['HTTP_HOST'] . "/reset-password.php?token=" . $token;
            $success .= " <br><small>Demo reset link: <a href='$resetLink'>$resetLink</a></small>";
        } else {
            $error = 'No account found with that email address.';
        }
    }
}

$page_title = 'Forgot Password - Mutalex Academy';
include 'includes/header.php';
?>

<section class="login-section">
    <div class="container">
        <div class="login-card">
            <div class="login-header">
                <h1>Reset Password</h1>
                <p>Enter your email address and we'll send you a link to reset your password</p>
            </div>

            <?php if ($error): ?>
                <div class="alert alert-error">
                    <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>

            <?php if ($success): ?>
                <div class="alert alert-success">
                    <?php echo $success; ?>
                </div>
            <?php endif; ?>

            <form method="POST" class="login-form">
                <div class="form-group">
                    <label for="email">Email Address</label>
                    <input type="email" id="email" name="email" required
                           value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>">
                </div>

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

            <div class="login-help">
                <p>Remember your password? <a href="login.php">Login here</a></p>
            </div>
        </div>
    </div>
</section>

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