<?php
/**
 * Telegram Bot - Base Class
 * Handles all Telegram interactions
 */

namespace App\Classes\Telegram;

class TelegramBot {
    protected $botToken;
    protected $apiUrl = 'https://api.telegram.org/bot';
    protected $timeout = 10;
    
    public function __construct($botToken = null) {
        $this->botToken = $botToken ?: env('TELEGRAM_BOT_TOKEN');
        
        if (!$this->botToken) {
            throw new \Exception('Telegram bot token not configured');
        }
    }
    
    /**
     * Send message to user
     */
    public function sendMessage($chatId, $text, $parseMode = 'HTML', $keyboard = null) {
        $data = [
            'chat_id' => $chatId,
            'text' => $text,
            'parse_mode' => $parseMode
        ];
        
        if ($keyboard) {
            $data['reply_markup'] = json_encode($keyboard);
        }
        
        return $this->request('sendMessage', $data);
    }
    
    /**
     * Send photo
     */
    public function sendPhoto($chatId, $photo, $caption = '', $parseMode = 'HTML') {
        return $this->request('sendPhoto', [
            'chat_id' => $chatId,
            'photo' => $photo,
            'caption' => $caption,
            'parse_mode' => $parseMode
        ]);
    }
    
    /**
     * Edit message
     */
    public function editMessage($chatId, $messageId, $text, $parseMode = 'HTML', $keyboard = null) {
        $data = [
            'chat_id' => $chatId,
            'message_id' => $messageId,
            'text' => $text,
            'parse_mode' => $parseMode
        ];
        
        if ($keyboard) {
            $data['reply_markup'] = json_encode($keyboard);
        }
        
        return $this->request('editMessageText', $data);
    }
    
    /**
     * Send inline keyboard
     */
    public function sendInlineKeyboard($chatId, $text, $buttons = []) {
        $keyboard = [
            'inline_keyboard' => $buttons
        ];
        
        return $this->sendMessage($chatId, $text, 'HTML', $keyboard);
    }
    
    /**
     * Answer callback query (button press)
     */
    public function answerCallbackQuery($callbackQueryId, $text = '', $showAlert = false) {
        return $this->request('answerCallbackQuery', [
            'callback_query_id' => $callbackQueryId,
            'text' => $text,
            'show_alert' => $showAlert
        ]);
    }
    
    /**
     * Get webhook info
     */
    public function getWebhookInfo() {
        return $this->request('getWebhookInfo', []);
    }
    
    /**
     * Set webhook
     */
    public function setWebhook($url) {
        return $this->request('setWebhook', [
            'url' => $url
        ]);
    }
    
    /**
     * Delete webhook
     */
    public function deleteWebhook() {
        return $this->request('deleteWebhook', []);
    }
    
    /**
     * Get me (bot info)
     */
    public function getMe() {
        return $this->request('getMe', []);
    }
    
    /**
     * Make API request
     */
    protected function request($method, $data = []) {
        try {
            $url = $this->apiUrl . $this->botToken . '/' . $method;
            
            $curl = curl_init();
            
            curl_setopt_array($curl, [
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => $this->timeout,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS => json_encode($data),
                CURLOPT_HTTPHEADER => [
                    'Content-Type: application/json'
                ]
            ]);
            
            $response = curl_exec($curl);
            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            $curlError = curl_error($curl);
            curl_close($curl);
            
            if ($curlError) {
                throw new \Exception('CURL Error: ' . $curlError);
            }
            
            if ($httpCode !== 200) {
                throw new \Exception('HTTP Error: ' . $httpCode);
            }
            
            $decoded = json_decode($response, true);
            
            if ($decoded === null) {
                throw new \Exception('Invalid JSON response');
            }
            
            return $decoded;
            
        } catch (\Exception $e) {
            error_log('Telegram API Error: ' . $e->getMessage());
            return [
                'ok' => false,
                'error_code' => 0,
                'description' => $e->getMessage()
            ];
        }
    }
    
    /**
     * Create inline keyboard button
     */
    public static function inlineButton($text, $callbackData) {
        return [
            [
                'text' => $text,
                'callback_data' => $callbackData
            ]
        ];
    }
    
    /**
     * Create URL button
     */
    public static function urlButton($text, $url) {
        return [
            [
                'text' => $text,
                'url' => $url
            ]
        ];
    }
    
    /**
     * Format price for Telegram
     */
    public static function formatPrice($amount, $currency = 'UGX') {
        if ($currency === 'UGX') {
            return '₨ ' . number_format($amount, 0);
        } elseif ($currency === 'USD') {
            return '$ ' . number_format($amount, 2);
        } elseif ($currency === 'KSH') {
            return 'KSh ' . number_format($amount, 2);
        }
        return $amount . ' ' . $currency;
    }
}
?>
