<?php
include 'includes/db.php';
include 'includes/header.php';

$message = "";
$error = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = $conn->real_escape_string($_POST['email']);
    
    // Check if email exists
    $sql = "SELECT id, full_name FROM users WHERE email = '$email'";
    $result = $conn->query($sql);
    
    if ($result->num_rows > 0) {
        $user = $result->fetch_assoc();
        $token = bin2hex(random_bytes(32));
        $expires_at = date('Y-m-d H:i:s', strtotime('+1 hour'));
        
        $update_sql = "UPDATE users SET reset_token = '$token', reset_expires_at = '$expires_at' WHERE id = " . $user['id'];
        
        if ($conn->query($update_sql) === TRUE) {
            // In a real application, you would send an email here.
            // For this local setup, we will display the link directly.
            $reset_link = "http://localhost/admission_portal/reset_password.php?token=$token";
            $message = "Password reset link has been generated (Simulated Email): <br><a href='$reset_link'>$reset_link</a>";
        } else {
            $error = "Something went wrong. Please try again.";
        }
    } else {
        $error = "No account found with that email address.";
    }
}
?>

<div class="auth-wrapper">
    <div class="auth-box">
        <h2>Forgot Password</h2>
        <p class="text-center" style="color: #666; margin-bottom: 20px;">Enter your email address to receive a password reset link.</p>
        
        <?php if($message): ?>
            <div class="alert alert-success" style="word-break: break-all;"><?php echo $message; ?></div>
        <?php endif; ?>
        
        <?php if($error): ?>
            <div class="alert alert-danger"><?php echo $error; ?></div>
        <?php endif; ?>
        
        <form method="POST" action="">
            <div class="form-group">
                <label>Email Address</label>
                <input type="email" name="email" class="form-control" required>
            </div>
            <button type="submit" class="btn-primary btn-block">Send Reset Link</button>
        </form>
        
        <p class="text-center" style="margin-top: 15px;">
            <a href="login.php" style="text-decoration: none;">&larr; Back to Login</a>
        </p>
    </div>
</div>

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