<?php

namespace App\Modules\Notification\Services;

/**
 * Telegram Bot Service
 *
 * Sends messages via Telegram Bot API.
 */
class TelegramBotService
{
    protected string $apiBase = 'https://api.telegram.org/bot';

    protected ?string $token;

    public function __construct()
    {
        $this->token = env('telegram.bot_token') ?: env('telegram_bot_token');
    }

    /**
     * Send a text message to a Telegram user
     *
     * @param int $telegramUserId Telegram user ID (chat_id)
     * @param string $message Text message to send (HTML supported)
     * @return bool True on success, false on failure
     */
    public function sendMessage(int $telegramUserId, string $message): bool
    {
        if (empty($this->token)) {
            log_message('error', 'TelegramBotService: telegram.bot_token is not set in .env');
            return false;
        }

        $url = $this->apiBase . $this->token . '/sendMessage';

        $payload = [
            'chat_id'                  => $telegramUserId,
            'text'                     => $message,
            'parse_mode'               => 'HTML',
            'disable_web_page_preview' => true,
        ];

        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => json_encode($payload),
            CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 10,
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);

        if ($curlError) {
            log_message('error', 'TelegramBotService sendMessage curl error: ' . $curlError . ' for chat_id=' . $telegramUserId);
            return false;
        }

        if ($httpCode !== 200) {
            log_message('error', 'TelegramBotService sendMessage HTTP ' . $httpCode . ' for chat_id=' . $telegramUserId . ' response=' . $response);
            return false;
        }

        $data = json_decode($response, true);
        if (isset($data['ok']) && $data['ok'] === true) {
            return true;
        }

        log_message('error', 'TelegramBotService sendMessage API error: ' . ($response ?: 'empty'));
        return false;
    }
}
