<?php
/**
 * ASL BELGISI – Отчет об агрегации (public/api/v1/doc/aggregation)
 * Token va TIN/INN shu yerda turadi.
 */

$API_TOKEN = '4e0d9f49-0eec-4a05-93ec-45eed1f3cc62'; // sen bergan token
$TIN       = '204083198';                            // sening INN/TIN
$SERVER    = 'https://xtrace.aslbelgisi.uz';         // kerak bo'lsa stage: https://xtrace.stage.aslbelgisi.uz

// Sening MОД (businessPlaceId) ID – LК ichidan olasan
$BUSINESS_PLACE_ID = 17800; // TODO: o'z raqaming bilan almashtir

/**
 * Aggregatsiya hisobotini jo'natish funksiyasi
 *
 * @param array  $codes            Aggregatsiyaga kiradigan KМ/KИ lar ro'yxati
 * @param string $unitSerialNumber Agressiya qutisining kodi (parent package code)
 * @param int    $capacity         Qutining reja bo'yicha sig'imi (aggregationUnitCapacity)
 * @param string|null $productionOrderId Ishlab chiqarish buyrug'i raqami (ixtiyoriy)
 *
 * @return array ['httpCode' => int, 'raw' => string, 'json' => mixed|null]
 */
function sendAggregationReport(
    array $codes,
    string $unitSerialNumber,
    int $capacity,
    ?string $productionOrderId = null
) {
    global $API_TOKEN, $SERVER, $BUSINESS_PLACE_ID;

    if (empty($codes)) {
        throw new InvalidArgumentException('codes bo\'sh bo\'lishi mumkin emas');
    }

    // API talabi bo‘yicha: aggregationItemsCount = haqiqiy ichki kodlar soni :contentReference[oaicite:1]{index=1}
    $aggregationItemsCount = count($codes);

    // Aggregatsiya JSON (documentBody ichidagi haqiqiy JSON)
    $documentBody = [
        'aggregationUnits' => [
            [
                'aggregationItemsCount'   => $aggregationItemsCount, // nechta kod ichida
                'aggregationUnitCapacity' => $capacity,              // quti reja sig‘imi
                'codes'                   => array_values($codes),   // ichki KИ/KМ lar
                // shouldBeUnbundled – faqat mavjud agregatsiyani yangilaganda kerak, shuning uchun yubormasak ham bo'ladi
                'unitSerialNumber'        => $unitSerialNumber,      // ota (parent) quti kodi
            ],
        ],
        'businessPlaceId' => $BUSINESS_PLACE_ID,
        // Dokument sanasi – ISO 8601 formatda bo‘lishi kerak :contentReference[oaicite:2]{index=2}
        'documentDate'    => date('c'),
    ];

    if ($productionOrderId !== null && $productionOrderId !== '') {
        $documentBody['productionOrderId'] = $productionOrderId;
    }

    // JSON ga o‘tkazamiz
    $json = json_encode($documentBody, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    if ($json === false) {
        throw new RuntimeException('JSON encode error: ' . json_last_error_msg());
    }

    // ASL BELGISI talabi bo‘yicha documentBody – base64 kodlangan JSON :contentReference[oaicite:3]{index=3}
    $requestBody = [
        'documentBody' => base64_encode($json),
        // 'signature' => '...', // agar E-imzo qo‘shmoqchi bo‘lsang, shu yerga qo‘shasan (hozircha majburiy emas)
    ];

    $url = rtrim($SERVER, '/') . '/public/api/v1/doc/aggregation';

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => [
            'Content-Type: application/json;charset=UTF-8',
            'Authorization: Bearer ' . $API_TOKEN,
        ],
        CURLOPT_POSTFIELDS     => json_encode($requestBody, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
    ]);

    $responseBody = curl_exec($ch);
    $httpCode     = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($responseBody === false) {
        $err = curl_error($ch);
        curl_close($ch);
        throw new RuntimeException('cURL error: ' . $err);
    }

    curl_close($ch);

    $decoded = json_decode($responseBody, true);

    return [
        'httpCode' => $httpCode,
        'raw'      => $responseBody,
        'json'     => $decoded,
    ];
}

/**
 * QUYIDAGI QISM – ODDIY MISOL.
 * Shu yerda faqat kodlar va quti ma’lumotlarini o‘zgartirib ishlata olasan.
 */

// Aggregatsiyaga kiradigan KМ/KИ lar (sen o'zing zaxiradan olasan)


$codes = [
    // Bu yerga haqiqiy KИ/KМ larni qo'yasan
    '010478008327011321R9qNBBJQNeg1e',
    '010478008327011321XL5F9YbJlw9hP',
    '010478008327011321C(RWCPgsWRuiI',
    '010478008327011321."QJLEVMHWAth',
    '010478008327011321Nd558PV1FW4%k',
    '010478008327011321Ig:Wam9Wx7VTn',
    '010478008327011321ftYs0Pli%-T\'a',
    '010478008327011321jN13&X?+*_qlL93dWZq',
    '010478008327011321L5s\'EO/EQ-BVQ',
    '010478008327011321uGx9GZdJmTHeV',
    '010478008327011321edaadU1dtDyxF',
    '010478008327011321C.iVwMiYis,m5',
];



// Quti seriya raqami – algoritmni o'zing belgilaysan.
// Namuna sifatida: "000" + TIN + "00000001"
$unitSerialNumber = '012478008327011721ijVJ%.mKanUzW93dzEr';

// Qutining reja sig‘imi (masalan, 10 ta butilka kiradi)
$capacity = 12;

// Agar ishlab chiqarish buyrug'i raqamini ishlatsang – shu yerga qo'yasan, aks holda null
$productionOrderId = '3'; // yoki null

try {
    $result = sendAggregationReport($codes, $unitSerialNumber, $capacity, $productionOrderId);

    // API dan kutiladigan javob: {"documentId": "..."} bo‘ladi 
    echo "HTTP code: {$result['httpCode']}\n";
    echo "Response raw:\n{$result['raw']}\n";

    if (is_array($result['json']) && isset($result['json']['documentId'])) {
        echo "Yangi aggregatsiya hujjati ID (documentId): " . $result['json']['documentId'] . "\n";
    }
} catch (Throwable $e) {
    echo "Xato: " . $e->getMessage() . "\n";
}
