<?php

/**
 * Global helper functions for views (role checks, etc.)
 * These are intentionally very lightweight and rely on $_SESSION,
 * mirroring the old index.php behaviour for compatibility.
 */

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

/**
 * Returns true if current user is CRM specialist.
 */
function isCrmSpecialist(): bool
{
    return isset($_SESSION['role']) && $_SESSION['role'] === 'crm_specialist';
}

/**
 * Returns true if current user is admin.
 */
function isAdmin(): bool
{
    return isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
}

function isSystemRole(): bool
{
    return isset($_SESSION['role']) && $_SESSION['role'] === 'system';
}

/**
 * Returns true if current user is admin or CRM specialist.
 */
function isAdminOrCrmSpecialist(): bool
{
    $role = $_SESSION['role'] ?? '';
    return $role === 'admin' || $role === 'crm_specialist' || $role === 'system';
}

function isAccountant(): bool
{
    return isset($_SESSION['role']) && $_SESSION['role'] === 'accountant';
}

/**
 * Returns true if current user can edit phone numbers.
 * In the legacy system only admins could edit phone numbers.
 */
function canEditPhone(): bool
{
    $role = $_SESSION['role'] ?? '';
    return $role === 'admin';
}

/**
 * Returns true if current user can access satisfaction features.
 * Only admin and CRM specialist have access.
 */
function canAccessSatisfaction(): bool
{
    return isAdminOrCrmSpecialist();
}

/**
 * Returns true if current user can access support module.
 * Only admin and CRM specialist have access.
 */
function canAccessSupport(): bool
{
    return isAdminOrCrmSpecialist();
}

/**
 * Returns true if current user can create customer-access requests
 * from a lead card (sales experts + CRM + management + admin).
 */
function canRequestCustomerAccess(): bool
{
    $role = $_SESSION['role'] ?? '';
    return in_array($role, ['agent', 'crm_specialist', 'sales_manager', 'management', 'system', 'admin'], true);
}

/**
 * Returns true if current user can see/resolve the support inbox of
 * customer-access requests (support team + management + admin).
 */
function canManageCustomerAccess(): bool
{
    $role = $_SESSION['role'] ?? '';
    return in_array($role, ['support', 'management', 'system', 'admin'], true);
}

/**
 * Returns true if current user can edit support entries.
 * Only admin can edit support entries (CRM specialist can only create).
 */
function canEditSupport(): bool
{
    return isAdmin();
}


