<?php
declare(strict_types=1);

require_once __DIR__ . '/response.php';
require_once __DIR__ . '/auth.php';

function requireCompanyContext(?int $companyId): void
{
    $user = getAuthenticatedUser();

    if (!$companyId) {
        jsonResponse([
            'error' => 'Company required',
            'code'  => 'COMPANY_REQUIRED'
        ], 400);
    }

    // Global roles bypass company restriction
    foreach ($user['roles'] as $role) {
        if (in_array($role, ['super_admin', 'support'], true)) {
            return;
        }
    }

    if ((int)$user['company_id'] !== (int)$companyId) {
        jsonResponse([
            'error' => 'Forbidden',
            'code'  => 'INVALID_COMPANY_CONTEXT'
        ], 403);
    }
}
