<?php
session_start();
require_once 'db/config.php';
require_once 'mail/MailService.php';

$page_title = "Forgot Password";
$message = '';

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['email'])) {
    $email = $_POST['email'];
    $db = db();

    // Check if user with that email exists
    $stmt = $db->prepare("SELECT * FROM users WHERE email = :email");
    $stmt->bindParam(':email', $email);
    $stmt->execute();
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user) {
        // Generate a unique token
        $token = bin2hex(random_bytes(50));

        // Store the token in the password_resets table
        $stmt = $db->prepare("DELETE FROM password_resets WHERE email = :email");
        $stmt->bindParam(':email', $email);
        $stmt->execute();
        
        $stmt = $db->prepare("INSERT INTO password_resets (email, token) VALUES (:email, :token)");
        $stmt->bindParam(':email', $email);
        $stmt->bindParam(':token', $token);
        $stmt->execute();

        // Send the password reset email
        $reset_link = "http://" . $_SERVER['HTTP_HOST'] . "/reset_password.php?token=" . $token;
        $subject = "Password Reset Request";
        $body = "Click on this link to reset your password: <a href=''' . $reset_link . '''>''' . $reset_link . '''</a>";
        
        MailService::sendMail($email, $subject, $body, strip_tags($body));

        $message = "If an account with that email exists, a password reset link has been sent.";
    } else {
        $message = "If an account with that email exists, a password reset link has been sent.";
    }
}

include 'header.php';
?>

<div class="container mt-5">
    <div class="row justify-content-center">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h4>Forgot Password</h4>
                </div>
                <div class="card-body">
                    <?php if ($message): ?>
                        <div class="alert alert-info"><?php echo $message; ?></div>
                    <?php endif; ?>
                    <p>Please enter your email address. You will receive a link to create a new password via email.</p>
                    <form action="forgot_password.php" method="post">
                        <div class="form-group mb-3">
                            <label for="email">Email address</label>
                            <input type="email" class="form-control" id="email" name="email" required>
                        </div>
                        <button type="submit" class="btn btn-primary">Send Password Reset Email</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

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