<?php

/**
 * Send order summary to Discord webhook (if URL is configured in settings).
 *
 * @param array<string, mixed> $payload id, order_type, user_phone, address, total_amount, order_summary (optional)
 */
function send_order_to_discord(array $payload): void
{
    $settingModel = model(\App\Models\SettingModel::class);
    $url          = $settingModel->getValue('discord_webhook_url');
    if ($url === null || $url === '') {
        return;
    }
    $lines = [
        '**New paid order** #' . ($payload['id'] ?? ''),
        'Type: ' . ($payload['order_type'] ?? ''),
        'User: ' . ($payload['user_phone'] ?? ''),
        'Address: ' . ($payload['address'] ?? ''),
        'Total: ' . number_format((float) ($payload['total_amount'] ?? 0)) . ' UGX',
    ];
    $summary = $payload['order_summary'] ?? null;
    if (is_array($summary) && $summary !== []) {
        $parts = [];
        foreach ($summary as $k => $v) {
            if (in_array($k, ['car_plate', 'kit_addons'], true) || is_array($v)) {
                continue;
            }
            $parts[] = $k . ': ' . $v;
        }
        if ($parts !== []) {
            $lines[] = 'Details: ' . implode(' · ', $parts);
        }
        if (! empty($summary['car_plate'])) {
            $lines[] = 'Car plate: ' . $summary['car_plate'];
        }
        if (! empty($summary['kit_addons']) && is_array($summary['kit_addons'])) {
            $addons = array_map(static function ($a) {
                return ($a['name'] ?? '') . ' (' . number_format((float) ($a['price'] ?? 0)) . ' UGX)';
            }, $summary['kit_addons']);
            $lines[] = 'Add-ons: ' . implode(', ', $addons);
        }
    }
    $client = \Config\Services::curlrequest();
    $body   = json_encode(['content' => implode("\n", $lines)]);
    try {
        $client->post($url, [
            'headers' => ['Content-Type' => 'application/json'],
            'body'    => $body,
            'timeout' => 5,
        ]);
    } catch (\Throwable $e) {
        log_message('error', 'Discord webhook failed: ' . $e->getMessage());
    }
}
