<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class TelegramService
{
    protected function token(): ?string
    {
        return config('services.telegram.bot_token') ?: env('TELEGRAM_BOT_TOKEN');
    }

    public function sendMessage(int|string $chatId, string $text): void
    {
        $token = $this->token();
        if (!$token) {
            return;
        }

        // Telegram expects HTML entities only if parse_mode is set.
        Http::asForm()
            ->timeout(5)
            ->post("https://api.telegram.org/bot{$token}/sendMessage", [
                'chat_id' => $chatId,
                'text' => $text,
                'disable_web_page_preview' => true,
            ]);
    }

    public function setWebhook(string $url, ?string $secretToken = null): array
    {
        $token = $this->token();
        if (!$token) {
            return ['ok' => false, 'error' => 'Missing TELEGRAM_BOT_TOKEN'];
        }

        $payload = [
            'url' => $url,
            'drop_pending_updates' => true,
        ];
        if ($secretToken) {
            $payload['secret_token'] = $secretToken;
        }

        $resp = Http::asForm()
            ->timeout(10)
            ->post("https://api.telegram.org/bot{$token}/setWebhook", $payload);

        if (!$resp->ok()) {
            return ['ok' => false, 'status' => $resp->status(), 'body' => $resp->body()];
        }

        return $resp->json();
    }
}

