<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');

$uri  = parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH) ?? '';
$path = rtrim($uri, '/');

/**
 * Helper: does the path end with a given suffix?
 */
function path_ends_with(string $path, string $suffix): bool
{
    return substr($path, -strlen($suffix)) === $suffix;
}

// 1) Tenant URL base: /scim/v2
// Entra may call this directly; MUST NOT 404
if (path_ends_with($path, '/scim/v2')) {
    echo json_encode([
        'schemas'      => ['urn:ietf:params:scim:api:messages:2.0:ListResponse'],
        'Resources'    => [],
        'totalResults' => 0,
        'startIndex'   => 1,
        'itemsPerPage' => 0,
    ]);
    exit;
}

// 2) ServiceProviderConfig
if (path_ends_with($path, '/scim/v2/ServiceProviderConfig')) {
    echo json_encode([
        'schemas' => ['urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig'],
        'patch'   => ['supported' => true],
        'bulk'    => ['supported' => false],
        'filter'  => ['supported' => true, 'maxResults' => 200],
        'changePassword' => ['supported' => false],
        'sort'    => ['supported' => true],
        'etag'    => ['supported' => false],
        'authenticationSchemes' => [[
            'type'        => 'oauthbearertoken',
            'name'        => 'OAuth Bearer Token',
            'description' => 'Bearer token as configured per company in TowLens.',
        ]],
    ]);
    exit;
}

// 3) Schemas
if (path_ends_with($path, '/scim/v2/Schemas')) {
    echo json_encode([
        'schemas'      => ['urn:ietf:params:scim:api:messages:2.0:ListResponse'],
        'totalResults' => 1,
        'startIndex'   => 1,
        'itemsPerPage' => 1,
        'Resources'    => [[
            'id'          => 'urn:ietf:params:scim:schemas:core:2.0:User',
            'name'        => 'User',
            'description' => 'User Account',
            'attributes'  => [
                ['name' => 'userName',   'type' => 'string',  'multiValued' => false],
                ['name' => 'externalId', 'type' => 'string',  'multiValued' => false],
                ['name' => 'name',       'type' => 'complex', 'multiValued' => false],
                ['name' => 'emails',     'type' => 'complex', 'multiValued' => true],
                ['name' => 'active',     'type' => 'boolean','multiValued' => false],
            ],
        ]],
    ]);
    exit;
}

// Anything else under scim_meta we don't know: 404 is fine here
http_response_code(404);
echo json_encode([
    'schemas' => ['urn:ietf:params:scim:api:messages:2.0:Error'],
    'detail'  => 'Not found',
    'status'  => '404',
]);