<?php
/**
 * Admin Role Helper Functions
 * Include this file at the top of any page that needs admin checks
 */

/**
 * Check if current user is logged in
 */
function isLoggedIn()
{
    return isset($_SESSION['login']) && !empty($_SESSION['login']);
}

/**
 * Check if current user is an admin
 */
function isAdmin()
{
    return isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
}

/**
 * Get current user role
 */
function getUserRole()
{
    return isset($_SESSION['role']) ? $_SESSION['role'] : 'guest';
}

/**
 * Redirect if not logged in
 * @param string $redirect_to Where to redirect (default: login.php)
 */
function requireLogin($redirect_to = 'login.php')
{
    if (!isLoggedIn()) {
        $_SESSION['redirect_after_login'] = $_SERVER['REQUEST_URI'];
        header("location: $redirect_to");
        exit();
    }
}

/**
 * Redirect if not admin
 * @param string $redirect_to Where to redirect (default: index.php)
 */
function requireAdmin($redirect_to = 'index.php')
{
    if (!isAdmin()) {
        header("location: $redirect_to");
        exit();
    }
}

/**
 * Check if user has permission
 * @param array $allowed_roles Array of allowed roles
 */
function hasRole($allowed_roles = [])
{
    $user_role = getUserRole();
    return in_array($user_role, $allowed_roles);
}

/**
 * Display admin badge HTML
 */
function showAdminBadge()
{
    if (isAdmin()) {
        echo '<span style="background: #f44336; color: white; padding: 4px 10px; border-radius: 12px; font-size: 11px; font-weight: 600; margin-left: 8px;">ADMIN</span>';
    }
}

/**
 * Get user info from session
 */
function getCurrentUser()
{
    if (!isLoggedIn()) {
        return null;
    }

    return [
        'id' => $_SESSION['id'] ?? null,
        'name' => $_SESSION['username'] ?? null,
        'email' => $_SESSION['login'] ?? null,
        'role' => $_SESSION['role'] ?? 'customer'
    ];
}

/**
 * Display role badge
 */
function getRoleBadge($role = null)
{
    if ($role === null) {
        $role = getUserRole();
    }

    $badges = [
        'admin' => '<span style="background: #f44336; color: white; padding: 3px 8px; border-radius: 3px; font-size: 12px;">ADMIN</span>',
        'customer' => '<span style="background: #2196f3; color: white; padding: 3px 8px; border-radius: 3px; font-size: 12px;">Customer</span>',
        'guest' => '<span style="background: #9e9e9e; color: white; padding: 3px 8px; border-radius: 3px; font-size: 12px;">Guest</span>'
    ];

    return $badges[$role] ?? $badges['guest'];
}
?>
