<?php

function resolveWorkspace(PDO $db, int $userId): array
{
    $workspace = $_GET['workspace'] ?? $_POST['workspace'] ?? 'personal';
    $requestedCompanyId = (int)($_GET['company_id'] ?? $_POST['company_id'] ?? 0);

    $result = [
        'workspace' => 'personal',
        'scope' => 'personal',
        'is_company' => false,
        'company_id' => null,
        'company_name' => ''
    ];

    if ($workspace === 'company' && $requestedCompanyId > 0) {
        $stmt = $db->prepare("
            SELECT c.id, c.company_name
            FROM company_users cu
            INNER JOIN companies c ON c.id = cu.company_id
            WHERE cu.user_id = :user_id
              AND cu.company_id = :company_id
            LIMIT 1
        ");
        $stmt->bindValue(':user_id', $userId, PDO::PARAM_INT);
        $stmt->bindValue(':company_id', $requestedCompanyId, PDO::PARAM_INT);
        $stmt->execute();

        $company = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($company) {
            $result['workspace'] = 'company';
            $result['scope'] = 'company';
            $result['is_company'] = true;
            $result['company_id'] = (int)$company['id'];
            $result['company_name'] = $company['company_name'];
        }
    }

    return $result;
}
function workspaceUrl(string $page, array $ctx, array $extra = []): string
{
    $params = array_merge([
        'workspace' => $ctx['workspace'],
        'scope' => $ctx['scope'],
    ], $extra);

    if ($ctx['is_company'] && !empty($ctx['company_id'])) {
        $params['company_id'] = $ctx['company_id'];
    }

    return $page . '?' . http_build_query($params);
}