<?php

namespace kernel\modules\notification\channels;

use kernel\Flash;
use kernel\modules\notification\contracts\NotificationChannelInterface;
use kernel\modules\notification\contracts\NotificationMessage;
use kernel\modules\notification\models\User;

class TelegramChannel implements NotificationChannelInterface
{
    protected string $botToken;

    public function __construct(string $botToken)
    {
        $this->botToken = $botToken;
    }

    public function send(NotificationMessage $notification, User $user): bool
    {
        if (empty($user->telegram_chat_id)) {
            return false;
        }

        $httpClient = new \GuzzleHttp\Client();

        try {
            $response = $httpClient->post("https://api.telegram.org/bot{$this->botToken}/sendMessage", [
                'form_params' => [
                    'chat_id' => $user->telegram_chat_id,
                    'text' => $notification->getMessage(),
                    'parse_mode' => 'HTML'
                ]
            ]);

            return $response->getStatusCode() === 200;
        } catch (\Exception $e) {
            Flash::setMessage("error", $e->getMessage());
            return false;
        }
    }
}