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

// Redirect if already logged in
if (isLoggedIn()) {
    header('Location: ../');
    exit();
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['email'])) {
    $email = $_POST['email'];
    
    // Check if email exists
    $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();
    
    if ($user) {
        // Generate and store token
        $token = generatePasswordResetToken($email);
        
        // Send reset email
        if (sendPasswordResetEmail($email, $token)) {
            $_SESSION['success_message'] = "Password reset link sent to your email!";
        } else {
            $_SESSION['error_message'] = "Failed to send reset email. Please try again.";
        }
    } else {
        $_SESSION['error_message'] = "No account found with that email address.";
    }
    
    header("Location: forgot-password.php");
    exit();
}

include '../includes/header.php';
?>

<div class="container py-5">
    <div class="row justify-content-center">
        <div class="col-md-6 col-lg-5">
            <div class="card shadow-sm">
                <div class="card-body p-5">
                    <div class="text-center mb-4">
                        <img src="../assets/images/logo.png" alt="JV Overseas" style="height: 60px;">
                        <h3 class="mt-3">Forgot Password</h3>
                    </div>
                    
                    <?php displayMessages(); ?>
                    
                    <form method="post">
                        <div class="form-group">
                            <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 btn-block">Send Reset Link</button>
                        
                        <div class="text-center mt-3">
                            <a href="login.php">Back to Login</a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

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