<?php
/**
 * MoySklad -> ShipPickup bridge (PHP 7.4+, curl).
 *
 * MoySklad webhook on creating or updating a shipment (demand) calls this script. The script reads the shipment with the
 * counterparty, buys the cheapest label through the ShipPickup API and writes the tracking number into the shipment description.
 *
 * 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: .../moysklad-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}
 *   MOYSKLAD_TOKEN         MoySklad API token
 *
 * The shipment must have an additional field (attribute) "ShipPickup country" with the 2-letter country code of the recipient
 * (for example DE); "ShipPickup weight_g" with the weight in grams is optional. The address is taken from the shipment address.
 * The sum of the shipment (in USD) is used as the declared value.
 */
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 moysklad(string $method, string $url, ?array $body = null): array
{
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('MOYSKLAD_TOKEN'), 'Content-Type: application/json', 'Accept-Encoding: gzip'],
        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 : [];
}

function attribute(array $entity, string $name): string
{
    foreach ((array) ($entity['attributes'] ?? []) as $a) {
        if (($a['name'] ?? '') === $name) {
            return trim((string) ($a['value'] ?? ''));
        }
    }
    return '';
}

$secret = (string) getenv('BRIDGE_SECRET');
if ($secret === '' || !hash_equals($secret, (string) ($_GET['secret'] ?? ''))) {
    reply(['ok' => false, 'error' => 'forbidden'], 403);
}

$payload = json_decode((string) file_get_contents('php://input'), true);
$results = [];
foreach ((array) ($payload['events'] ?? []) as $event) {
    $href = (string) ($event['meta']['href'] ?? '');
    // Only real MoySklad addresses are followed, so the token never goes anywhere else.
    if (($event['meta']['type'] ?? '') !== 'demand' || strpos($href, 'https://api.moysklad.ru/api/remap/1.2/entity/demand/') !== 0) {
        continue;
    }
    $demand = moysklad('GET', $href . '?expand=agent');
    if (!isset($demand['id'])) {
        $results[] = ['href' => $href, 'error' => 'shipment not found'];
        continue;
    }
    if (strpos((string) ($demand['description'] ?? ''), 'ShipPickup') !== false) {
        $results[] = ['id' => $demand['id'], 'skipped' => 'already processed (delete the ShipPickup line from the description to retry)'];
        continue;
    }

    $from = json_decode((string) getenv('SHIPPICKUP_FROM'), true) ?: [];
    $parcel = json_decode((string) getenv('SHIPPICKUP_PARCEL'), true) ?: [];
    if (attribute($demand, 'ShipPickup weight_g') !== '') {
        $parcel['weight_g'] = (int) attribute($demand, 'ShipPickup weight_g');
    }
    $addr = (array) ($demand['shipmentAddressFull'] ?? []);
    $valueCents = max(0, (int) round(((float) ($demand['sum'] ?? 0))));   // MoySklad keeps sums in the minor units (cents)

    $order = [
        'from' => $from,
        'to' => array_filter([
            'name' => (string) ($demand['agent']['name'] ?? 'Customer'),
            'line1' => trim((string) ($addr['street'] ?? '') . ' ' . (string) ($addr['house'] ?? '') . ' ' . (string) ($addr['apartment'] ?? '')),
            'city' => (string) ($addr['city'] ?? ''),
            'state' => '',
            'postal_code' => (string) ($addr['postalCode'] ?? ''),
            'country' => strtoupper(attribute($demand, 'ShipPickup country')),
            'phone' => (string) ($demand['agent']['phone'] ?? ''),
            'email' => (string) ($demand['agent']['email'] ?? ''),
        ], static function ($v) { return $v !== ''; }),
        'parcel' => $parcel,
        'items' => [['description' => 'Order ' . (string) ($demand['name'] ?? ''), '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('moysklad-' . $demand['id']))['data'];
    } catch (ShipPickupException $e) {
        moysklad('PUT', $href, ['description' => trim((string) ($demand['description'] ?? '') . "\nShipPickup: " . $e->errorCode . ' - ' . $e->getMessage())]);
        $results[] = ['id' => $demand['id'], 'error' => $e->errorCode];
        continue;
    }
    $tracking = (string) ($shipment['tracking_number'] ?? '');
    moysklad('PUT', $href, ['description' => trim((string) ($demand['description'] ?? '') . "\nShipPickup tracking: " . $tracking . ' (' . $shipment['carrier'] . ' ' . $shipment['service'] . ', order ' . $shipment['id'] . ')')]);
    $results[] = ['id' => $demand['id'], 'order_id' => $shipment['id'], 'tracking_number' => $tracking];
}

reply(['ok' => true, 'results' => $results]);
