<?php
require_once 'db_connection.php'; // Make sure this connects to your database
require_once 'includes/send_email.php';

$role = $_GET['role'] ?? '';
$errors = [];
$success = '';

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

    if (empty($email)) {
        $errors[] = "Email is required.";
    }

    // Define role-specific table
    switch ($role) {
    case 'student':
        $table = 'students';
        break;
    case 'instructor':
        $table = 'instructors';
        break;
    case 'admin':
        $table = 'admins';
        break;
    default:
        $table = '';
        break;
}

    if ($table === '') {
        $errors[] = "Invalid user role.";
    }

if (empty($errors)) {
    $stmt = $conn->prepare("SELECT * FROM $table WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 1) {
        $token = bin2hex(random_bytes(32));
        $expires_at = date("Y-m-d H:i:s", time() + 1800); // 30 minutes

        $stmt = $conn->prepare("INSERT INTO password_resets (email, token, role, expires_at) VALUES (?, ?, ?, ?)");
        $stmt->bind_param("ssss", $email, $token, $role, $expires_at);
        $stmt->execute();

        $reset_link = "https://bookings.tandddrivingacademy.com/reset-password.php?token=$token&role=$role";

        // Use the helper
        $subject = "Password Reset Request";
        $body_html = "
            <p>Hello,</p>
            <p>Click the link below to reset your password. This link will expire in 30 minutes:</p>
            <p><a href='$reset_link'>$reset_link</a></p>
            <p>If you did not request a reset, you can ignore this message.</p>
        ";

        if (send_email($email, '', $subject, $body_html)) {
            $success = "Password reset link has been sent to your email.";
        } else {
            $errors[] = "There was a problem sending the email. Please try again later.";
        }

    } else {
        $errors[] = "No user found with that email.";
    }
}

?>

<!DOCTYPE html>
<html>
<head>
    <title>Password Recovery</title>
</head>
<body>
    <h2>Password Recovery</h2>
