<?php

declare(strict_types=1);

$config = require __DIR__ . '/lalamove_config.php';

function out($data): void
{
    if (PHP_SAPI !== 'cli') {
        header('Content-Type: application/json; charset=utf-8');
    }
    echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . PHP_EOL;
}

function makeTraceId(): string
{
    return bin2hex(random_bytes(16)) . '.' . random_int(300, 499) . '.' . (string) round(microtime(true) * 1000000);
}

function makeSu(): string
{
    return time() . 'ehll' . random_int(1000000000, 9999999999);
}

function buildUrl(array $config, string $module, array $args = []): string
{
    $query = $config['common_query'];
    $query['_m'] = $module;
    $query['_su'] = makeSu();
    $query['_t'] = (string) time();
    $query['_traceId'] = makeTraceId();
    $query['token'] = $config['token'];
    $query['args'] = json_encode($args, JSON_UNESCAPED_SLASHES);

    return rtrim($config['base_url'], '/') . '/?' . http_build_query($query);
}

function requestJson(string $url, array $headers): array
{
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_TIMEOUT => 45,
        CURLOPT_HTTPHEADER => $headers,
    ]);

    $body = curl_exec($ch);
    $errno = curl_errno($ch);
    $error = curl_error($ch);
    $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($errno !== 0) {
        return [
            'ok' => false,
            'http_status' => $status,
            'error' => 'cURL error: ' . $error,
            'raw' => $body,
        ];
    }

    $decoded = json_decode((string) $body, true);
    if (!is_array($decoded)) {
        return [
            'ok' => false,
            'http_status' => $status,
            'error' => 'Invalid JSON response',
            'raw' => $body,
        ];
    }

    return [
        'ok' => true,
        'http_status' => $status,
        'data' => $decoded,
        'raw' => $body,
    ];
}

function attemptLogin(array $config): array
{
    if (empty($config['login']['username']) || empty($config['login']['password'])) {
        return [
            'ok' => false,
            'message' => 'Login not implemented yet. Capture the real login request first, then patch attemptLogin().',
        ];
    }

    return [
        'ok' => false,
        'message' => 'Login stub only. Need actual Lalamove login request details.',
    ];
}

function checkLogin(array $config): array
{
    $url = buildUrl($config, 'get_user_info', []);
    return requestJson($url, $config['headers']);
}

function fetchOrders(array $config, string $lastId = ''): array
{
    $defaults = $config['defaults'];
    $args = [
        'order_statuses'       => [],
        'last_id'              => $lastId,
        'page_size'            => $defaults['page_size'],
        'daylight_zone'        => $defaults['daylight_zone'],
        'start_order_datetime' => $defaults['start_order_datetime'],
        'end_order_datetime'   => $defaults['end_order_datetime'],
        'order_type_arr'       => $defaults['order_type_arr'],
        'placed_by'            => $defaults['placed_by'],
    ];

    $url = buildUrl($config, 'order_list_new', $args);
    return requestJson($url, $config['headers']);
}

function fetchOrderDetail(array $config, string $orderUuid): array
{
    $args = [
        'order_uuid' => $orderUuid,
        'interest_id' => 0,
        'daylight_zone' => 'Asia/Kuala_Lumpur',
    ];

    $url = buildUrl($config, 'order_detail', $args);
    return requestJson($url, $config['headers']);
}

function pickShareLink(array $detail): ?string
{
    $candidates = [
        $detail['data']['share_link'] ?? null,
        $detail['data']['order_detail_info']['share_link'] ?? null,
        $detail['data']['order_detail_info']['tracking_info']['share_link'] ?? null,
    ];

    foreach ($candidates as $candidate) {
        if (is_string($candidate) && $candidate !== '') {
            return $candidate;
        }
    }

    $raw = json_encode($detail['data'], JSON_UNESCAPED_SLASHES);
    if (is_string($raw) && preg_match('~https://share\.lalamove\.com/[^"\\\s]+~', $raw, $m)) {
        return $m[0];
    }

    return null;
}

$loginCheck = checkLogin($config);
if (!$loginCheck['ok']) {
    out([
        'ok' => false,
        'stage' => 'check_login_http',
        'result' => $loginCheck,
    ]);
    exit;
}

$loginData = $loginCheck['data'];
$loggedIn = (isset($loginData['ret']) && (int) $loginData['ret'] === 0);

if (!$loggedIn) {
    $loginAttempt = attemptLogin($config);
    out([
        'ok' => false,
        'stage' => 'login_required',
        'login_check' => $loginData,
        'login_attempt' => $loginAttempt,
    ]);
    exit;
}

$orderList = fetchOrders($config);
if (!$orderList['ok']) {
    out([
        'ok' => false,
        'stage' => 'fetch_orders_http',
        'result' => $orderList,
    ]);
    exit;
}

$listData = $orderList['data'];
if (!isset($listData['ret']) || (int) $listData['ret'] !== 0) {
    out([
        'ok' => false,
        'stage' => 'fetch_orders_api',
        'result' => $listData,
    ]);
    exit;
}

$orders = $listData['data']['order_base_info'] ?? [];
$summary = [];

foreach ($orders as $order) {
    $orderUuid = (string) ($order['order_uuid'] ?? '');
    if ($orderUuid === '') {
        continue;
    }

    $detail = fetchOrderDetail($config, $orderUuid);
    $shareLink = null;
    $detailStatus = null;
    $detailError = null;

    if ($detail['ok']) {
        $detailStatus = $detail['data']['ret'] ?? null;
        if ((int) $detailStatus === 0) {
            $shareLink = pickShareLink($detail);
        } else {
            $detailError = $detail['data'];
        }
    } else {
        $detailError = $detail;
    }

    $pickup = $order['addr_info'][0] ?? [];
    $dropoff = $order['addr_info'][1] ?? [];

    $summary[] = [
        'order_uuid' => $orderUuid,
        'order_display_id' => $order['order_display_id_str'] ?? null,
        'status' => $order['order_status'] ?? null,
        'driver_name' => $order['driver']['name'] ?? null,
        'display_final_price' => $order['display_final_price'] ?? null,
        'pickup_name' => $pickup['contacts_name'] ?? null,
        'pickup_phone' => $pickup['contacts_phone_no'] ?? null,
        'pickup_addr' => $pickup['addr'] ?? null,
        'dropoff_name' => $dropoff['contacts_name'] ?? null,
        'dropoff_phone' => $dropoff['contacts_phone_no'] ?? null,
        'dropoff_addr' => $dropoff['addr'] ?? null,
        'share_link' => $shareLink,
        'detail_ret' => $detailStatus,
        'detail_error' => $detailError,
    ];
}

out([
    'ok' => true,
    'login_check_ret' => $loginData['ret'] ?? null,
    'order_count' => count($orders),
    'orders' => $summary,
    'next_last_id' => $listData['data']['last_id'] ?? null,
]);
