<?php
// --- LOGIC BLOCK ---
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 {
        $stmt = $conn->prepare("SELECT id, full_name FROM users WHERE email = ? AND role = 'admin'");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows === 1) {
            $user = $result->fetch_assoc();
            
            // Generate a secure token
            $token = bin2hex(random_bytes(32));
            $token_hash = hash('sha256', $token);
            $expires_at = date("Y-m-d H:i:s", time() + 3600); // Token is valid for 1 hour

            // Store the hashed token in the database
            $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 with the raw token
            $reset_link = "http://" . $_SERVER['HTTP_HOST'] . "/reset-password.php?token=" . $token;
            
            // Send the email
            $subject = "Password Reset Request for your Admin Account";
            $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 . "'>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: No Reply <noreply@" . $_SERVER['HTTP_HOST'] . ">\r\n";
            
            mail($email, $subject, $email_body, $headers);
        }
        // Always show a generic success message to prevent email enumeration
        $message = '<div class="alert alert-success">If an admin account with that email exists, a password reset link has been sent to it.</div>';
    }
}
// --- PRESENTATION BLOCK ---
include 'includes/header.php';
?>
<main class="container my-5">
    <div class="row justify-content-center">
        <div class="col-md-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 admin email address and we will send you a link to reset your password.</p>
                    <?php echo $message; ?>
                    <form method="POST">
                        <div class="mb-3"><label class="form-label">Email Address</label><input type="email" class="form-control" name="email" required></div>
                        <div class="d-grid"><button type="submit" name="send_reset_link" class="btn btn-primary">Send Reset Link</button></div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</main>
<?php include 'includes/footer.php'; ?>
