<?php
/**
 * KeyCRM -> ShipPickup bridge (PHP 7.4+, curl).
 *
 * A KeyCRM webhook (event "order status changed") calls this script. The script reads the order, buys the cheapest label
 * through the ShipPickup API and writes the tracking number into the order delivery and the manager 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: .../keycrm-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      parcel as JSON: {"weight_g":800,"length_mm":250,"width_mm":180,"height_mm":80}
 *   KEYCRM_TOKEN           KeyCRM API key (Settings -> API)
 *   KEYCRM_STATUS_ID       (optional) id of the order status that starts the purchase; other statuses are ignored
 *
 * The recipient is taken from the order delivery block: name, phone, address, city, region, zip and the country
 * (use the 2-letter country code, for example DE). The order total (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 keycrm(string $method, string $path, ?array $body = null): array
{
    $ch = curl_init('https://openapi.keycrm.app/v1' . $path);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('KEYCRM_TOKEN'), 'Accept: application/json', '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 : [];
}

$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['context']['id'] ?? $_GET['order_id'] ?? 0);
if ($orderId <= 0) {
    reply(['ok' => false, 'error' => 'no order id'], 400);
}
$wanted = (string) getenv('KEYCRM_STATUS_ID');
if ($wanted !== '' && isset($payload['context']['status_id']) && (string) $payload['context']['status_id'] !== $wanted) {
    reply(['ok' => true, 'skipped' => 'other status']);
}

$crm = keycrm('GET', '/order/' . $orderId . '?include=buyer,shipping,products');
if (!isset($crm['id'])) {
    reply(['ok' => false, 'error' => 'order not found'], 502);
}
if (trim((string) ($crm['shipping']['tracking_code'] ?? '')) !== '') {
    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) ?: [];
$ship = (array) ($crm['shipping'] ?? []);
$items = [];
$sum = 0;
foreach ((array) ($crm['products'] ?? []) as $p) {
    $cents = max(0, (int) round(((float) ($p['price'] ?? 0)) * 100));
    $qty = max(1, (int) ($p['quantity'] ?? 1));
    $items[] = ['description' => (string) ($p['name'] ?? 'Goods'), 'quantity' => $qty, 'unit_value_cents' => $cents, 'origin_country' => (string) ($from['country'] ?? 'US')];
    $sum += $cents * $qty;
}

$order = [
    'from' => $from,
    'to' => array_filter([
        'name' => (string) ($ship['recipient_full_name'] ?? $crm['buyer']['full_name'] ?? ('Order ' . $orderId)),
        'line1' => trim((string) ($ship['shipping_address_street'] ?? $ship['shipping_receive_point'] ?? '') . ' ' . (string) ($ship['shipping_secondary_line'] ?? '')),
        'city' => (string) ($ship['shipping_address_city'] ?? ''),
        'state' => (string) ($ship['shipping_address_region'] ?? ''),
        'postal_code' => (string) ($ship['shipping_address_zip'] ?? ''),
        'country' => strtoupper((string) ($ship['shipping_address_country'] ?? '')),
        'phone' => (string) ($ship['recipient_phone'] ?? $crm['buyer']['phone'] ?? ''),
        'email' => (string) ($crm['buyer']['email'] ?? ''),
    ], static function ($v) { return $v !== ''; }),
    'parcel' => $parcel,
    'items' => $items,
    'declared_value_cents' => $sum,
];

try {
    $api = new ShipPickup();
    $shipment = $api->buyCheapest($order, ShipPickup::idempotencyKey('keycrm-' . $orderId))['data'];
} catch (ShipPickupException $e) {
    keycrm('PUT', '/order/' . $orderId, ['manager_comment' => trim((string) ($crm['manager_comment'] ?? '') . "\nShipPickup: " . $e->errorCode . ' - ' . $e->getMessage())]);
    reply(['ok' => false, 'error' => $e->errorCode, 'message' => $e->getMessage()]);
}

$tracking = (string) ($shipment['tracking_number'] ?? '');
keycrm('PUT', '/order/' . $orderId, ['shipping' => ['tracking_code' => $tracking]]);
keycrm('PUT', '/order/' . $orderId, ['manager_comment' => trim((string) ($crm['manager_comment'] ?? '') . "\nShipPickup label: " . $shipment['carrier'] . ' ' . $shipment['service'] . ', tracking ' . $tracking . ', order ' . $shipment['id'])]);

reply(['ok' => true, 'order_id' => $shipment['id'], 'tracking_number' => $tracking]);
