<?php
/**
 * Bitrix24 -> ShipPickup bridge (PHP 7.4+, curl).
 *
 * Called by an outgoing webhook (event ONCRMDEALUPDATE) or by the "Webhook" robot of a deal stage.
 * The script reads the deal, and when it is in the chosen stage and has no tracking yet, buys the cheapest label through
 * the ShipPickup API, then writes the tracking number into the deal field and adds a timeline comment.
 *
 * Put this file and shippickup.php on your server (HTTPS) and set these environment variables, nothing is stored in the file:
 *   BRIDGE_SECRET          any long random string, the same as in the webhook URL: .../bitrix24-bridge.php?secret=...
 *   SHIPPICKUP_API_KEY     live key (sk_live_...) with the rates:read and labels:create permissions
 *   SHIPPICKUP_FROM        sender address as JSON: {"name":"Acme","line1":"350 5th Ave","city":"New York","state":"NY","postal_code":"10001","country":"US","phone":"+12125550100"}
 *   SHIPPICKUP_PARCEL      default parcel as JSON: {"weight_g":800,"length_mm":250,"width_mm":180,"height_mm":80}
 *   BITRIX_WEBHOOK_URL     inbound webhook of Bitrix24 with the CRM permission, for example https://mycompany.bitrix24.com/rest/1/xxxxxxxx/
 *   BITRIX_STAGE           deal stage id in which the label is bought, for example PREPARATION
 *   BITRIX_FIELDS          deal user fields as JSON: {"line1":"UF_CRM_1","city":"UF_CRM_2","state":"UF_CRM_3","postal_code":"UF_CRM_4","country":"UF_CRM_5","weight_g":"UF_CRM_6","tracking":"UF_CRM_7"}
 *                          (weight_g is optional; the deal amount is used as the declared value in USD)
 */
require __DIR__ . '/shippickup.php';

header('Content-Type: application/json');

function reply(array $data, int $status = 200): void
{
    http_response_code($status);
    echo json_encode($data);
    exit;
}

function bitrix(string $method, array $params = []): array
{
    $ch = curl_init(rtrim((string) getenv('BITRIX_WEBHOOK_URL'), '/') . '/' . $method . '.json');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_POSTFIELDS => http_build_query($params),
    ]);
    $raw = curl_exec($ch);
    curl_close($ch);
    $json = json_decode((string) $raw, true);
    return is_array($json) ? $json : [];
}

$secret = (string) getenv('BRIDGE_SECRET');
if ($secret === '' || !hash_equals($secret, (string) ($_GET['secret'] ?? ''))) {
    reply(['ok' => false, 'error' => 'forbidden'], 403);
}

// Outgoing webhook: data[FIELDS][ID]. Robot: document_id[2] = DEAL_<id>. Manual test: ?deal_id=...
$dealId = (int) ($_POST['data']['FIELDS']['ID'] ?? 0);
if ($dealId <= 0 && isset($_POST['document_id'][2])) {
    $dealId = (int) preg_replace('/\D+/', '', (string) $_POST['document_id'][2]);
}
if ($dealId <= 0) {
    $dealId = (int) ($_GET['deal_id'] ?? 0);
}
if ($dealId <= 0) {
    reply(['ok' => false, 'error' => 'no deal id'], 400);
}

$fields = json_decode((string) getenv('BITRIX_FIELDS'), true) ?: [];
$from = json_decode((string) getenv('SHIPPICKUP_FROM'), true) ?: [];
$parcel = json_decode((string) getenv('SHIPPICKUP_PARCEL'), true) ?: [];

$deal = (array) (bitrix('crm.deal.get', ['id' => $dealId])['result'] ?? []);
if ($deal === []) {
    reply(['ok' => false, 'error' => 'deal not found'], 502);
}
if ((string) getenv('BITRIX_STAGE') !== '' && ($deal['STAGE_ID'] ?? '') !== (string) getenv('BITRIX_STAGE')) {
    reply(['ok' => true, 'skipped' => 'other stage']);
}
$trackField = (string) ($fields['tracking'] ?? '');
if ($trackField !== '' && trim((string) ($deal[$trackField] ?? '')) !== '') {
    reply(['ok' => true, 'skipped' => 'tracking already set']);   // the label is already bought
}

$contact = [];
if (!empty($deal['CONTACT_ID'])) {
    $contact = (array) (bitrix('crm.contact.get', ['id' => (int) $deal['CONTACT_ID']])['result'] ?? []);
}
$f = static function (string $name) use ($deal, $fields): string {
    return empty($fields[$name]) ? '' : trim((string) ($deal[$fields[$name]] ?? ''));
};
if ($f('weight_g') !== '') {
    $parcel['weight_g'] = (int) $f('weight_g');
}
$valueCents = max(0, (int) round(((float) ($deal['OPPORTUNITY'] ?? 0)) * 100));

$order = [
    'from' => $from,
    'to' => array_filter([
        'name' => trim((string) ($contact['NAME'] ?? '') . ' ' . (string) ($contact['LAST_NAME'] ?? '')) ?: ('Deal ' . $dealId),
        'line1' => $f('line1'),
        'city' => $f('city'),
        'state' => $f('state'),
        'postal_code' => $f('postal_code'),
        'country' => strtoupper($f('country')),
        'phone' => (string) ($contact['PHONE'][0]['VALUE'] ?? ''),
        'email' => (string) ($contact['EMAIL'][0]['VALUE'] ?? ''),
    ], static function ($v) { return $v !== ''; }),
    'parcel' => $parcel,
    'items' => [['description' => (string) ($deal['TITLE'] ?? 'Goods'), 'quantity' => 1, 'unit_value_cents' => $valueCents, 'origin_country' => (string) ($from['country'] ?? 'US')]],
    'declared_value_cents' => $valueCents,
];

try {
    $api = new ShipPickup();
    $shipment = $api->buyCheapest($order, ShipPickup::idempotencyKey('bitrix24-' . $dealId))['data'];
} catch (ShipPickupException $e) {
    bitrix('crm.timeline.comment.add', ['fields' => ['ENTITY_ID' => $dealId, 'ENTITY_TYPE' => 'deal', 'COMMENT' => 'ShipPickup: ' . $e->errorCode . ' - ' . $e->getMessage()]]);
    reply(['ok' => false, 'error' => $e->errorCode, 'message' => $e->getMessage()]);
}

$tracking = (string) ($shipment['tracking_number'] ?? '');
if ($trackField !== '' && $tracking !== '') {
    bitrix('crm.deal.update', ['id' => $dealId, 'fields' => [$trackField => $tracking]]);
}
bitrix('crm.timeline.comment.add', ['fields' => ['ENTITY_ID' => $dealId, 'ENTITY_TYPE' => 'deal', 'COMMENT' => 'ShipPickup label: ' . $shipment['carrier'] . ' ' . $shipment['service'] . ', tracking ' . $tracking . ', order ' . $shipment['id'] . ', ' . number_format($shipment['price_cents'] / 100, 2, '.', '') . ' ' . $shipment['currency']]]);

reply(['ok' => true, 'order_id' => $shipment['id'], 'tracking_number' => $tracking]);
