<?php

declare(strict_types=1);

if (PHP_SAPI !== 'cli') {
    http_response_code(403);
    exit(1);
}

require_once __DIR__ . '/../src/config.php';
require_once __DIR__ . '/../src/logger.php';
require_once __DIR__ . '/../src/storage.php';
require_once __DIR__ . '/../src/bitrix.php';

$options = getopt('', ['query::', 'type::', 'compact']);
$query = trim((string) ($options['query'] ?? 'филиал'));
$type = trim((string) ($options['type'] ?? ''));
$compact = isset($options['compact']);
$response = bitrixCall('crm.deal.fields');
$matched = [];

foreach ((array) ($response['result'] ?? []) as $fieldCode => $field) {
    $field = (array) $field;
    $haystack = implode(' ', [
        (string) $fieldCode,
        (string) ($field['title'] ?? ''),
        (string) ($field['listLabel'] ?? ''),
        (string) ($field['formLabel'] ?? ''),
        (string) ($field['filterLabel'] ?? ''),
    ]);
    $matches = $query === '' || (function_exists('mb_stripos')
        ? mb_stripos($haystack, $query, 0, 'UTF-8') !== false
        : stripos($haystack, $query) !== false);
    if ($matches && ($type === '' || (string) ($field['type'] ?? '') === $type)) {
        $matched[$fieldCode] = $compact ? [
            'type' => (string) ($field['type'] ?? ''),
            'label' => (string) ($field['listLabel'] ?? $field['formLabel'] ?? ''),
            'item_count' => count((array) ($field['items'] ?? [])),
            'items' => array_slice((array) ($field['items'] ?? []), 0, 15),
        ] : $field;
    }
}

echo json_encode([
    'query' => $query,
    'count' => count($matched),
    'fields' => $matched,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . PHP_EOL;
