<?php

declare(strict_types=1);

if (PHP_SAPI !== 'cli') {
    http_response_code(403);
    echo "This script can be run only from CLI.\n";
    exit(1);
}

require_once __DIR__ . '/../src/config.php';
require_once __DIR__ . '/../src/bitrix.php';
require_once __DIR__ . '/../src/crm.php';

$options = getopt('', ['field-name::', 'help']);
if (isset($options['help'])) {
    echo "Usage: php tools/deal_userfield_enum.php [--field-name=UF_CRM_1693995123245]\n";
    exit(0);
}

$fieldName = trim((string) ($options['field-name'] ?? 'UF_CRM_1693995123245'));
if ($fieldName === '') {
    fwrite(STDERR, "Field name must not be empty.\n");
    exit(1);
}

try {
    $field = findDealUserFieldByName($fieldName);
    $items = getDealUserFieldEnumItems($fieldName);

    echo json_encode([
        'field_name' => $fieldName,
        'field_id' => $field['ID'] ?? null,
        'field_type' => $field['USER_TYPE_ID'] ?? null,
        'items' => $items,
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . PHP_EOL;
} catch (Throwable $exception) {
    fwrite(STDERR, $exception->getMessage() . PHP_EOL);
    exit(1);
}
