<?php

namespace App\Listeners;

use App\Events\OrderPlaced;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

/**
 * Kirim notifikasi Telegram ke Admin saat pesanan baru masuk.
 *
 * Konfigurasi di .env:
 *   TELEGRAM_BOT_TOKEN=123456:ABC-DEF...
 *   TELEGRAM_CHAT_ID=-1001234567890
 *
 * Jika salah satu config kosong → skip diam-diam, tidak error.
 */
class SendTelegramOrderNotification
{
    public function handle(OrderPlaced $event): void
    {
        $token  = config('services.telegram.bot_token');
        $chatId = config('services.telegram.chat_id');

        // Skip jika belum dikonfigurasi
        if (! $token || ! $chatId) {
            return;
        }

        $order = $event->order;

        // Format pesan Telegram (MarkdownV2 — escape karakter khusus)
        $adminUrl = rtrim(config('app.url'), '/') . '/admin/pesanan/' . $order->id;

        $lines = [
            '🛒 *Pesanan Baru Masuk\!*',
            '',
            '📋 *No\. Pesanan:* `' . $this->escape($order->order_number) . '`',
            '👤 *Customer:* ' . $this->escape($order->customer_name),
            '📱 *WhatsApp:* ' . $this->escape($order->customer_phone),
            '💰 *Total:* Rp ' . $this->escape(number_format($order->grand_total, 0, ',', '.')),
            '💳 *Pembayaran:* ' . $this->escape($order->payment_method->label()),
            '🕐 *Waktu:* ' . $this->escape($order->created_at->format('d M Y, H:i')),
            '',
            '🔗 [Buka Panel Admin](' . $adminUrl . ')',
        ];

        $text = implode("\n", $lines);

        try {
            Http::timeout(5)->post(
                "https://api.telegram.org/bot{$token}/sendMessage",
                [
                    'chat_id'    => $chatId,
                    'text'       => $text,
                    'parse_mode' => 'MarkdownV2',
                ]
            );
        } catch (\Throwable $e) {
            // Log error tapi jangan throw — checkout sudah selesai, jangan ganggu customer
            Log::warning('Telegram notification failed: ' . $e->getMessage(), [
                'order_number' => $order->order_number,
            ]);
        }
    }

    /**
     * Escape karakter khusus MarkdownV2 Telegram.
     * @see https://core.telegram.org/bots/api#markdownv2-style
     */
    private function escape(string $text): string
    {
        return preg_replace('/([_*\[\]()~`>#+\-=|{}.!\\\\])/', '\\\\$1', $text);
    }
}
