<?php

if (! function_exists('session_company_ids')) {
    /**
     * Company IDs for the logged-in user (supports comma-separated session value).
     *
     * @return int[]
     */
    function session_company_ids(): array
    {
        $sessionCompanyId = session()->get('company_id');
        if ($sessionCompanyId === null || $sessionCompanyId === '') {
            return [];
        }

        return array_values(array_filter(array_map('intval', explode(',', (string) $sessionCompanyId))));
    }
}

if (! function_exists('is_global_admin_role')) {
    function is_global_admin_role(): bool
    {
        return (int) session()->get('role_id') === 1;
    }
}

if (! function_exists('apply_company_scope')) {
    /**
     * Restrict a query builder to the current user's company/companies.
     * Super admin (role 1) is not scoped.
     */
    function apply_company_scope($builder, string $column = 'company_id'): void
    {
        if (is_global_admin_role()) {
            return;
        }

        $companyIds = session_company_ids();
        if ($companyIds === []) {
            $builder->where($column, -1);

            return;
        }

        if (count($companyIds) === 1) {
            $builder->where($column, $companyIds[0]);

            return;
        }

        $builder->whereIn($column, $companyIds);
    }
}
