<?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/bitrix.php';
require_once __DIR__ . '/../src/crm.php';

$options = getopt('', ['deal-ids::']);
$dealIds = array_values(array_filter(array_map(
    static fn (string $value): string => trim($value),
    explode(',', (string) ($options['deal-ids'] ?? ''))
)));

$categoriesResponse = bitrixCall('crm.category.list', [
    'entityTypeId' => 2,
]);
$categories = (array) ($categoriesResponse['result']['categories'] ?? []);

$pipelineIds = array_values(array_unique(array_filter([
    (string) config('RETAIL_DEAL_CATEGORY_ID', '0'),
    (string) config('PARTS_DEAL_CATEGORY_ID', '26'),
    (string) config('SERVICE_DEAL_CATEGORY_ID', '30'),
])));

$stages = [];
foreach ($pipelineIds as $categoryId) {
    $entityId = $categoryId === '0' ? 'DEAL_STAGE' : 'DEAL_STAGE_' . $categoryId;
    $response = bitrixCall('crm.status.list', [
        'filter' => ['ENTITY_ID' => $entityId],
        'order' => ['SORT' => 'ASC'],
    ]);

    $stages[$categoryId] = array_map(
        static fn (array $stage): array => [
            'status_id' => (string) ($stage['STATUS_ID'] ?? ''),
            'name' => (string) ($stage['NAME'] ?? ''),
            'sort' => (int) ($stage['SORT'] ?? 0),
        ],
        (array) ($response['result'] ?? [])
    );
}

$deals = [];
$workflowInstances = [];
$assignedUsers = [];
$branchItems = getDealUserFieldEnumItems((string) config('DEAL_BRANCH_FIELD', 'UF_CRM_1764919997'));
foreach ($dealIds as $dealId) {
    $response = bitrixCallRaw('crm.deal.get', ['id' => $dealId]);
    if (isset($response['error'])) {
        $deals[$dealId] = [
            'error' => (string) $response['error'],
            'error_description' => (string) ($response['error_description'] ?? ''),
        ];
        continue;
    }

    $deal = (array) ($response['result'] ?? []);
    $assignedById = (string) ($deal['ASSIGNED_BY_ID'] ?? '');
    $branchValue = (string) ($deal[(string) config('DEAL_BRANCH_FIELD', 'UF_CRM_1764919997')] ?? '');
    $branchItem = null;
    foreach ($branchItems as $candidate) {
        if ((string) ($candidate['id'] ?? '') === $branchValue) {
            $branchItem = $candidate;
            break;
        }
    }

    $deals[$dealId] = [
        'title' => (string) ($deal['TITLE'] ?? ''),
        'category_id' => (string) ($deal['CATEGORY_ID'] ?? ''),
        'stage_id' => (string) ($deal['STAGE_ID'] ?? ''),
        'interest_group' => (string) ($deal[(string) config('DEAL_INTEREST_GROUP_FIELD', 'UF_CRM_1784809347681')] ?? ''),
        'phone' => (string) ($deal[(string) config('DEAL_PHONE_FIELD', 'UF_CRM_1783332070432')] ?? ''),
        'city' => $deal[(string) config('DEAL_CITY_FIELD', 'UF_CRM_1693995123245')] ?? '',
        'branch' => $branchValue,
        'branch_item' => $branchItem,
        'assigned_by_id' => $assignedById,
        'modified_at' => (string) ($deal['DATE_MODIFY'] ?? ''),
    ];

    if ($assignedById !== '' && !array_key_exists($assignedById, $assignedUsers)) {
        $assignedUsers[$assignedById] = bitrixCallRaw('user.get', ['ID' => $assignedById]);
    }

    $workflowInstances[$dealId] = bitrixCallRaw('bizproc.workflow.instances', [
        'select' => [
            'ID',
            'MODIFIED',
            'OWNED_UNTIL',
            'MODULE_ID',
            'ENTITY',
            'DOCUMENT_ID',
            'STARTED',
            'STARTED_BY',
            'TEMPLATE_ID',
        ],
        'order' => ['STARTED' => 'DESC'],
        'filter' => [
            'MODULE_ID' => 'crm',
            'ENTITY' => 'CCrmDocumentDeal',
            'DOCUMENT_ID' => 'DEAL_' . $dealId,
        ],
    ]);

}

echo json_encode([
    'configured_routes' => [
        'retail' => [
            'category_id' => (string) config('RETAIL_DEAL_CATEGORY_ID', '0'),
            'qualified_stage_id' => (string) config('TECHNIQUE_QUALIFIED_STAGE_ID', '37'),
        ],
        'parts' => [
            'category_id' => (string) config('PARTS_DEAL_CATEGORY_ID', '26'),
            'stage_id' => (string) config('PARTS_INITIAL_STAGE_ID', 'C26:NEW'),
        ],
        'service' => [
            'category_id' => (string) config('SERVICE_DEAL_CATEGORY_ID', '30'),
            'stage_id' => (string) config('SERVICE_INITIAL_STAGE_ID', 'C30:NEW'),
        ],
    ],
    'categories' => array_map(
        static fn (array $category): array => [
            'id' => (string) ($category['id'] ?? ''),
            'name' => (string) ($category['name'] ?? ''),
            'sort' => (int) ($category['sort'] ?? 0),
        ],
        $categories
    ),
    'stages' => $stages,
    'deals' => $deals,
    'assigned_users' => $assignedUsers,
    'active_workflow_instances' => $workflowInstances,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . PHP_EOL;
