<?php
// --- LOGIC BLOCK: All PHP processing must happen before any HTML is sent ---
require_once 'includes/db.php';
$message = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['send_reset_link'])) {
    $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);

    if (!$email) {
        $message = '<div class="alert alert-danger">Please enter a valid email address.</div>';
    } else {
        // Find any active user with this email, regardless of role.
        $stmt = $conn->prepare("SELECT id, full_name FROM users WHERE email = ? AND status = 'active'");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 1) {
            $user = $result->fetch_assoc();
            
            // Generate a secure, random token for the reset link.
            $token = bin2hex(random_bytes(32));
            $token_hash = hash('sha256', $token);
            
            // Set the token to expire in 1 hour.
            $expires_at = date("Y-m-d H:i:s", time() + 3600); 

            // Store the HASH of the token in the database, not the raw token.
            $stmt_update = $conn->prepare("UPDATE users SET reset_token_hash = ?, reset_token_expires_at = ? WHERE id = ?");
            $stmt_update->bind_param("ssi", $token_hash, $expires_at, $user['id']);
            $stmt_update->execute();
            
            // Create the reset link containing the RAW token.
            $reset_link = "http://" . $_SERVER['HTTP_HOST'] . "/reset-password.php?token=" . $token;
            
            // Send the email to the user.
            $subject = "Password Reset Request";
            $email_body = "Hello " . htmlspecialchars($user['full_name']) . ",<br><br>A password reset was requested for your account. Please click the link below to set a new password. This link is valid for one hour.<br><br><a href='" . $reset_link . "' style='padding:10px 15px; background-color:#0d6efd; color:white; text-decoration:none; border-radius:5px;'>Reset Your Password</a><br><br>If you did not request this, please ignore this email.";
            
            $headers = "MIME-Version: 1.0\r\n";
            $headers .= "Content-type:text/html;charset=UTF-8\r\n";
            $headers .= "From: DXP Support <noreply@" . $_SERVER['HTTP_HOST'] . ">\r\n";
            
            mail($email, $subject, $email_body, $headers);
        }

        // IMPORTANT: Always show a generic success message.
        // This prevents attackers from guessing valid email addresses on your platform.
        $message = '<div class="alert alert-success">If an account with that email exists, a password reset link has been sent to it. Please check your inbox and spam folder.</div>';
    }
}

// --- PRESENTATION BLOCK: Now we include the header and display the page ---
include 'includes/header.php';
?>
<main class="container my-5">
    <div class="row justify-content-center">
        <div class="col-lg-6">
            <div class="card shadow-sm">
                <div class="card-body p-5">
                    <h2 class="text-center mb-4">Forgot Password</h2>
                    <p class="text-center text-muted mb-4">Enter your account's email address and we will send you a link to reset your password.</p>
                    <?php echo $message; ?>
                    <form method="POST" action="forgot-password.php">
                        <div class="mb-3">
                            <label for="email" class="form-label">Your Email Address</label>
                            <input type="email" class="form-control" name="email" id="email" required>
                        </div>
                        <div class="d-grid">
                            <button type="submit" name="send_reset_link" class="btn btn-primary">Send Reset Link</button>
                        </div>
                         <p class="text-center mt-3"><a href="login.php">Back to Login</a></p>
                    </form>
                </div>
            </div>
        </div>
    </div>
</main>
<?php include 'includes/footer.php'; ?>
