<?php
/**
 * RetailCRM -> ShipPickup bridge (PHP 7.4+, curl).
 *
 * A RetailCRM trigger (action "HTTP request") calls this script with the order id. The script reads the order, buys the cheapest
 * label through the ShipPickup API and writes the tracking number into a custom field and the manager comment of the order.
 *
 * 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 trigger URL: .../retailcrm-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}
 *   RETAILCRM_URL          your RetailCRM address, for example https://mycompany.retailcrm.ru
 *   RETAILCRM_API_KEY      RetailCRM API key (Administration -> Integration -> API keys) with the order read and write permissions
 *   RETAILCRM_TRACK_FIELD  (optional) code of a text custom field of the order for the tracking number, default shippickup_tracking
 *
 * The order id is read from the request: JSON {"order_id": 123}, form field order_id or ?order_id=123.
 * The recipient is taken from the order: name, phone, email, delivery address (country as ISO code, index, region, city, street).
 * The order weight (grams) is used when it is filled in; the order total (in USD) is 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 retailcrm(string $method, string $path, array $form = []): array
{
    $ch = curl_init(rtrim((string) getenv('RETAILCRM_URL'), '/') . '/api/v5' . $path);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTPHEADER => ['X-API-KEY: ' . getenv('RETAILCRM_API_KEY')],
        CURLOPT_POSTFIELDS => $method === 'POST' ? http_build_query($form) : null,
    ]);
    $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);
}

$payload = json_decode((string) file_get_contents('php://input'), true);
$orderId = (int) ($payload['order_id'] ?? $_POST['order_id'] ?? $_GET['order_id'] ?? 0);
if ($orderId <= 0) {
    reply(['ok' => false, 'error' => 'no order id'], 400);
}

$trackField = (string) (getenv('RETAILCRM_TRACK_FIELD') ?: 'shippickup_tracking');
$crm = (array) (retailcrm('GET', '/orders/' . $orderId . '?by=id')['order'] ?? []);
if ($crm === []) {
    reply(['ok' => false, 'error' => 'order not found'], 502);
}
if (trim((string) ($crm['customFields'][$trackField] ?? '')) !== '') {
    reply(['ok' => true, 'skipped' => 'tracking already set']);   // the label is already bought
}

$from = json_decode((string) getenv('SHIPPICKUP_FROM'), true) ?: [];
$parcel = json_decode((string) getenv('SHIPPICKUP_PARCEL'), true) ?: [];
if (!empty($crm['weight'])) {
    $parcel['weight_g'] = (int) $crm['weight'];
}
$address = (array) ($crm['delivery']['address'] ?? []);
$items = [];
$sum = 0;
foreach ((array) ($crm['items'] ?? []) as $i) {
    $cents = max(0, (int) round(((float) ($i['initialPrice'] ?? 0)) * 100));
    $qty = max(1, (int) round((float) ($i['quantity'] ?? 1)));
    $items[] = ['description' => (string) ($i['offer']['displayName'] ?? $i['productName'] ?? 'Goods'), 'quantity' => $qty, 'unit_value_cents' => $cents, 'origin_country' => (string) ($from['country'] ?? 'US')];
    $sum += $cents * $qty;
}

$order = [
    'from' => $from,
    'to' => array_filter([
        'name' => trim((string) ($crm['firstName'] ?? '') . ' ' . (string) ($crm['lastName'] ?? '')) ?: ('Order ' . $orderId),
        'line1' => trim((string) ($address['street'] ?? '') . ' ' . (string) ($address['building'] ?? '') . ' ' . (string) ($address['flat'] ?? '')) ?: (string) ($address['text'] ?? ''),
        'city' => (string) ($address['city'] ?? ''),
        'state' => (string) ($address['region'] ?? ''),
        'postal_code' => (string) ($address['index'] ?? ''),
        'country' => strtoupper((string) ($address['countryIso'] ?? '')),
        'phone' => (string) ($crm['phone'] ?? ''),
        'email' => (string) ($crm['email'] ?? ''),
    ], static function ($v) { return $v !== ''; }),
    'parcel' => $parcel,
    'items' => $items,
    'declared_value_cents' => $sum,
];

$save = static function (array $change) use ($orderId, $crm): void {
    retailcrm('POST', '/orders/' . $orderId . '/edit', ['by' => 'id', 'site' => (string) ($crm['site'] ?? ''), 'order' => json_encode($change)]);
};

try {
    $api = new ShipPickup();
    $shipment = $api->buyCheapest($order, ShipPickup::idempotencyKey('retailcrm-' . $orderId))['data'];
} catch (ShipPickupException $e) {
    $save(['managerComment' => trim((string) ($crm['managerComment'] ?? '') . "\nShipPickup: " . $e->errorCode . ' - ' . $e->getMessage())]);
    reply(['ok' => false, 'error' => $e->errorCode, 'message' => $e->getMessage()]);
}

$tracking = (string) ($shipment['tracking_number'] ?? '');
$save([
    'customFields' => [$trackField => $tracking],
    'managerComment' => trim((string) ($crm['managerComment'] ?? '') . "\nShipPickup label: " . $shipment['carrier'] . ' ' . $shipment['service'] . ', tracking ' . $tracking . ', order ' . $shipment['id']),
]);

reply(['ok' => true, 'order_id' => $shipment['id'], 'tracking_number' => $tracking]);
