<?php
// /forgot_password.php
require_once 'includes/functions.php';

$errors = [];
$success_message = '';

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

    if (empty($email)) {
        $errors[] = "Email address is required.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format.";
    } else {
        $stmt = $conn->prepare("SELECT id, username FROM users WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $result = $stmt->get_result();
        $user = $result->fetch_assoc();
        $stmt->close();

        if ($user) {
            $token = bin2hex(random_bytes(50));
            $expires = date("U") + 1800; // 30 minutes

            $stmt = $conn->prepare("DELETE FROM password_resets WHERE email = ?");
            $stmt->bind_param("s", $email);
            $stmt->execute();
            $stmt->close();

            $stmt = $conn->prepare("INSERT INTO password_resets (email, token, expires) VALUES (?, ?, ?)");
            $stmt->bind_param("ssi", $email, $token, $expires);
            $stmt->execute();
            $stmt->close();

            $reset_link = SITE_URL . "/reset_password.php?token=" . $token;

            $data = [
                'username' => $user['username'],
                'reset_link' => $reset_link,
            ];

            if (send_email('password_reset', $email, 'Password Reset Request', $data)) {
                $success_message = "A password reset link has been sent to your email address.";
            } else {
                $errors[] = "Could not send the password reset email. Please try again later.";
            }
        } else {
            // To prevent user enumeration, show the same message whether the user exists or not
            $success_message = "If an account with that email exists, a password reset link has been sent.";
        }
    }
}

$page_title = "Forgot Password";
require_once 'includes/header.php';
?>

<div class="container mx-auto px-4 py-12">
    <div class="max-w-md mx-auto bg-white p-8 rounded-lg shadow-md">
        <h1 class="text-3xl font-bold text-center mb-6">Forgot Your Password?</h1>
        <p class="text-center text-gray-600 mb-6">Enter your email address and we will send you a link to reset your password.</p>

        <?php if (!empty($errors)): ?>
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4" role="alert">
                <ul class="list-disc list-inside">
                    <?php foreach ($errors as $error): ?>
                        <li><?php echo escape($error); ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php endif; ?>

        <?php if ($success_message): ?>
            <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative mb-4" role="alert">
                <p><?php echo escape($success_message); ?></p>
            </div>
        <?php else: ?>
            <form action="/forgot_password.php" method="POST">
                <div class="mb-4">
                    <label for="email" class="block text-gray-700 font-semibold mb-2">Email Address</label>
                    <input type="email" id="email" name="email" class="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                </div>
                <div>
                    <button type="submit" class="w-full bg-blue-600 text-white font-semibold py-2 px-4 rounded-lg hover:bg-blue-700 transition duration-300">Send Reset Link</button>
                </div>
            </form>
        <?php endif; ?>

        <p class="text-center text-gray-600 mt-6">
            Remember your password? <a href="/login.php" class="text-blue-600 hover:underline font-semibold">Login here</a>
        </p>
    </div>
</div>

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