<?php
/**
 * amoCRM -> ShipPickup bridge (PHP 7.4+, curl).
 *
 * The "Webhook" trigger of a digital pipeline stage calls this script. The script reads the deal from amoCRM,
 * buys the cheapest label through the ShipPickup API and writes the tracking number back into the deal (field and note).
 *
 * 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: .../amocrm-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}
 *   AMO_DOMAIN             your account domain, for example mycompany.amocrm.ru
 *   AMO_TOKEN              long-lived token of your amoCRM integration
 *   AMO_FIELDS             ids of the deal custom fields as JSON: {"line1":111,"city":112,"state":113,"postal_code":114,"country":115,"weight_g":116,"tracking":117}
 *                          (weight_g is optional; the deal budget 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 amo(string $method, string $path, ?array $body = null): array
{
    $ch = curl_init('https://' . getenv('AMO_DOMAIN') . $path);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('AMO_TOKEN'), 'Content-Type: application/json'],
        CURLOPT_POSTFIELDS => $body === null ? null : json_encode($body),
    ]);
    $raw = curl_exec($ch);
    curl_close($ch);
    $json = json_decode((string) $raw, true);
    return is_array($json) ? $json : [];
}

/** Value of a custom field (by id) of an amoCRM entity. */
function field(array $entity, int $id): string
{
    foreach ((array) ($entity['custom_fields_values'] ?? []) as $f) {
        if ((int) ($f['field_id'] ?? 0) === $id) {
            return trim((string) ($f['values'][0]['value'] ?? ''));
        }
    }
    return '';
}

/** Value of a contact field by code (PHONE, EMAIL). */
function contactField(array $contact, string $code): string
{
    foreach ((array) ($contact['custom_fields_values'] ?? []) as $f) {
        if (($f['field_code'] ?? '') === $code) {
            return trim((string) ($f['values'][0]['value'] ?? ''));
        }
    }
    return '';
}

$secret = (string) getenv('BRIDGE_SECRET');
if ($secret === '' || !hash_equals($secret, (string) ($_GET['secret'] ?? ''))) {
    reply(['ok' => false, 'error' => 'forbidden'], 403);
}

// The digital pipeline sends leads[status][0][id] (or leads[add][0][id]); ?lead_id=... is accepted for manual tests.
$leadId = (int) ($_POST['leads']['status'][0]['id'] ?? $_POST['leads']['add'][0]['id'] ?? $_GET['lead_id'] ?? 0);
if ($leadId <= 0) {
    reply(['ok' => false, 'error' => 'no lead id'], 400);
}

$fields = json_decode((string) getenv('AMO_FIELDS'), true) ?: [];
$from = json_decode((string) getenv('SHIPPICKUP_FROM'), true) ?: [];
$parcel = json_decode((string) getenv('SHIPPICKUP_PARCEL'), true) ?: [];

$lead = amo('GET', '/api/v4/leads/' . $leadId . '?with=contacts');
if (!isset($lead['id'])) {
    reply(['ok' => false, 'error' => 'lead not found'], 502);
}
if (!empty($fields['tracking']) && field($lead, (int) $fields['tracking']) !== '') {
    reply(['ok' => true, 'skipped' => 'tracking already set']);   // the label is already bought
}

$contact = [];
if (!empty($lead['_embedded']['contacts'][0]['id'])) {
    $contact = amo('GET', '/api/v4/contacts/' . (int) $lead['_embedded']['contacts'][0]['id']);
}
$f = static function (string $name) use ($lead, $fields): string {
    return empty($fields[$name]) ? '' : field($lead, (int) $fields[$name]);
};
if ($f('weight_g') !== '') {
    $parcel['weight_g'] = (int) $f('weight_g');
}
$valueCents = max(0, (int) round(((float) ($lead['price'] ?? 0)) * 100));

$order = [
    'from' => $from,
    'to' => array_filter([
        'name' => (string) ($contact['name'] ?? ('Lead ' . $leadId)),
        'line1' => $f('line1'),
        'city' => $f('city'),
        'state' => $f('state'),
        'postal_code' => $f('postal_code'),
        'country' => strtoupper($f('country')),
        'phone' => contactField($contact, 'PHONE'),
        'email' => contactField($contact, 'EMAIL'),
    ], static function ($v) { return $v !== ''; }),
    'parcel' => $parcel,
    'items' => [['description' => (string) ($lead['name'] ?? '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('amocrm-' . $leadId))['data'];
} catch (ShipPickupException $e) {
    amo('POST', '/api/v4/leads/' . $leadId . '/notes', [['note_type' => 'common', 'params' => ['text' => 'ShipPickup: ' . $e->errorCode . ' - ' . $e->getMessage()]]]);
    reply(['ok' => false, 'error' => $e->errorCode, 'message' => $e->getMessage()]);   // 200: amoCRM does not repeat the call
}

$tracking = (string) ($shipment['tracking_number'] ?? '');
if (!empty($fields['tracking']) && $tracking !== '') {
    amo('PATCH', '/api/v4/leads/' . $leadId, ['custom_fields_values' => [['field_id' => (int) $fields['tracking'], 'values' => [['value' => $tracking]]]]]);
}
amo('POST', '/api/v4/leads/' . $leadId . '/notes', [['note_type' => 'common', 'params' => ['text' => '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]);
