<?php

namespace App\Service;

use GuzzleHttp\Client;

class TelegramService
{
    private $apiToken;
    private $chatId;
    private $httpClient;

    public function __construct(array $config)
    {
        $this->apiToken = $config['telegram']['api_token'];
        $this->chatId = $config['telegram']['chat_id'];
        $this->httpClient = new Client(['base_uri' => 'https://api.telegram.org']);
    }

    public function sendMessage(string $message, array $keyboard = []): bool
{
    try {
        $response = $this->httpClient->post("/bot{$this->apiToken}/sendMessage", [
            'json' => [
                'chat_id' => $this->chatId,
                'text' => $message,
                'parse_mode' => 'HTML',
                'reply_markup' => $keyboard
            ]
        ]);

        return $response->getStatusCode() === 200;
    } catch (\Exception $e) {
        error_log('Telegram API Error: ' . $e->getMessage());
        return false;
    }
}

public function sendMessageWithPhotos($message, $keyboard, $qrPath): void
{
    $chatId = $this->chatId;

    $params = [
        'chat_id' => $chatId,
        'caption' => $message,
        'parse_mode' => 'HTML',
        'reply_markup' => json_encode($keyboard)
    ];

    if ($qrPath) {
        $this->sendPhoto($chatId, $qrPath, $params);
    }
    
}

private function sendPhoto($chatId, $photoPath, $params): void
{
    $url = 'https://api.telegram.org/bot' . $this->apiToken . '/sendPhoto';

    $postFields = [
        'chat_id' => $chatId,
        'caption' => $params['caption'],
        'parse_mode' => 'HTML',
        'photo' => curl_file_create($photoPath),
        'reply_markup' => $params['reply_markup']
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        error_log('Telegram API error: ' . curl_error($ch));
    }

    curl_close($ch);
}


}
