<?php

/**
 * @return array{ok: bool, status: int, body: array|null, raw: string}
 */
function hubspot_json_request(string $method, string $path, ?array $body): array
{
    $token = defined('HUBSPOT_PRIVATE_APP_TOKEN') ? HUBSPOT_PRIVATE_APP_TOKEN : '';
    $url = 'https://api.hubapi.com' . $path;

    $headers = [
        'Authorization: Bearer ' . $token,
        'Content-Type: application/json',
    ];

    $ch = curl_init($url);
    $opts = [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_TIMEOUT => 45,
        CURLOPT_CUSTOMREQUEST => strtoupper($method),
    ];
    if ($body !== null) {
        $opts[CURLOPT_POSTFIELDS] = json_encode($body);
    }
    curl_setopt_array($ch, $opts);
    $raw = curl_exec($ch);
    $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $decoded = null;
    if (is_string($raw) && $raw !== '') {
        $decoded = json_decode($raw, true);
    }

    return [
        'ok' => $status >= 200 && $status < 300,
        'status' => $status,
        'body' => is_array($decoded) ? $decoded : null,
        'raw' => is_string($raw) ? $raw : '',
    ];
}

/**
 * @return string|null Existing deal ID, or null
 */
function hubspot_find_deal_id_by_shopify_order(string $shopifyOrderId): ?string
{
    $prop = HUBSPOT_DEAL_PROPERTY_SHOPIFY_ORDER_ID;
    $payload = [
        'filterGroups' => [
            [
                'filters' => [
                    [
                        'propertyName' => $prop,
                        'operator' => 'EQ',
                        'value' => $shopifyOrderId,
                    ],
                ],
            ],
        ],
        'properties' => ['dealname', $prop],
        'limit' => 1,
    ];

    $res = hubspot_json_request('POST', '/crm/v3/objects/deals/search', $payload);
    if (!$res['ok'] || !is_array($res['body'])) {
        return null;
    }
    $results = $res['body']['results'] ?? [];
    if (!is_array($results) || $results === []) {
        return null;
    }
    $id = $results[0]['id'] ?? null;
    return $id !== null ? (string) $id : null;
}

/**
 * @param array $order Shopify order JSON (decoded)
 * @param string|null $dealStageId Optional override for the dealstage internal ID.
 * @return array{ok: bool, status: int, deal_id?: string, error?: string}
 */
function hubspot_create_deal_from_shopify_order(array $order, ?string $dealStageId = null): array
{
    $orderId = isset($order['id']) ? (string) $order['id'] : '';
    $name = isset($order['name']) ? (string) $order['name'] : ('Order ' . $orderId);
    $amountRaw = $order['total_price'] ?? $order['current_total_price'] ?? '0';
    $amount = is_numeric($amountRaw) ? (string) $amountRaw : '0';

    $resolvedStageId = $dealStageId !== null && $dealStageId !== '' ? (string) $dealStageId : HUBSPOT_DEALSTAGE_ID;
    $properties = [
        'dealname' => 'Shopify ' . $name,
        'amount' => $amount,
        'pipeline' => HUBSPOT_PIPELINE_ID,
        'dealstage' => $resolvedStageId,
        HUBSPOT_DEAL_PROPERTY_SHOPIFY_ORDER_ID => $orderId,
    ];

    // Multi-line text field in HubSpot to store all product names from this Shopify order.
    // Format: "#1, Product A" newline "#2, Product B" ...
    $lineItems = $order['line_items'] ?? [];
    $productNamesText = '';
    if (is_array($lineItems) && $lineItems !== []) {
        $names = [];
        $i = 1;
        foreach ($lineItems as $item) {
            if (!is_array($item)) {
                continue;
            }

            $title = trim((string) ($item['title'] ?? $item['name'] ?? ''));
            if ($title === '') {
                $sku = trim((string) ($item['sku'] ?? ''));
                if ($sku !== '') {
                    $title = 'SKU ' . $sku;
                } else {
                    $pid = $item['product_id'] ?? '';
                    if ($pid !== '') {
                        $title = 'Product ' . (string) $pid;
                    }
                }
            }

            if ($title !== '') {
                $names[] = '#' . $i . ', ' . $title;
            }
            $i++;
        }
        $productNamesText = implode(PHP_EOL, $names);
    }
    if ($productNamesText !== '') {
        $properties[HUBSPOT_DEAL_PROPERTY_PRODUCT_NAMES] = $productNamesText;
    }

    // Helpful for closed / completed stages
    $properties['closedate'] = (new DateTimeImmutable('now', new DateTimeZone('UTC')))
        ->format('Y-m-d\TH:i:s.000\Z');

    $res = hubspot_json_request('POST', '/crm/v3/objects/deals', ['properties' => $properties]);
    if ($res['ok'] && is_array($res['body']) && isset($res['body']['id'])) {
        return ['ok' => true, 'status' => $res['status'], 'deal_id' => (string) $res['body']['id']];
    }

    $msg = $res['body']['message'] ?? $res['raw'];
    return ['ok' => false, 'status' => $res['status'], 'error' => is_string($msg) ? $msg : 'HubSpot error'];
}
