<?php
require_once __DIR__ . '/auth.php';

function requireRole($allowed_roles) {
    if (!is_array($allowed_roles)) {
        $allowed_roles = [$allowed_roles];
    }

    if (!isLoggedIn()) {
        header('Location: /login.php');
        exit;
    }

    $user_role = $_SESSION['role'] ?? 'Guest';

    if (!in_array($user_role, $allowed_roles)) {
        // Redirect based on their actual role or to home
        switch ($user_role) {
            case 'Admin':
            case 'Super Admin':
                header('Location: /admin/index.php');
                break;
            case 'Dealer':
                header('Location: /dealer/index.php');
                break;
            case 'Customer':
            case 'Buyer': // Assuming 'Buyer' is the role name from prompt
                header('Location: /buyer/index.php');
                break;
            default:
                header('Location: /index.php');
        }
        exit;
    }
}

function hasRole($role) {
    return isset($_SESSION['role']) && $_SESSION['role'] === $role;
}

function isSuperAdmin() {
    return hasRole('Super Admin');
}
