<?php
/**
 * Telegram Bot API Wrapper
 * Handles all Telegram API interactions
 */

class Telegram {
    private $token;
    private $apiUrl = 'https://api.telegram.org/bot';
    private $db;

    public function __construct($token = BOT_TOKEN) {
        $this->token = $token;
        $this->db = Database::getInstance();
    }

    /**
     * Make API Request
     */
    private function request($method, $params = []) {
        $url = $this->apiUrl . $this->token . '/' . $method;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);

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

        if (curl_errno($ch)) {
            error_log('Telegram API Error: ' . curl_error($ch));
            curl_close($ch);
            return false;
        }

        curl_close($ch);

        if ($httpCode !== 200) {
            error_log("Telegram API HTTP Error: {$httpCode}");
            return false;
        }

        $data = json_decode($response, true);

        if (!$data['ok']) {
            error_log('Telegram API Error: ' . ($data['description'] ?? 'Unknown error'));
            return false;
        }

        return $data['result'];
    }

    /**
     * Send Message
     */
    public function sendMessage($chatId, $text, $options = []) {
        $params = [
            'chat_id' => $chatId,
            'text' => $text,
            'parse_mode' => $options['parse_mode'] ?? 'HTML',
            'disable_web_page_preview' => $options['disable_preview'] ?? true
        ];

        if (isset($options['reply_markup'])) {
            $params['reply_markup'] = is_array($options['reply_markup']) 
                ? json_encode($options['reply_markup']) 
                : $options['reply_markup'];
        }

        if (isset($options['reply_to_message_id'])) {
            $params['reply_to_message_id'] = $options['reply_to_message_id'];
        }

        return $this->request('sendMessage', $params);
    }

    /**
     * Send Photo
     */
    public function sendPhoto($chatId, $photo, $caption = '', $options = []) {
        $params = [
            'chat_id' => $chatId,
            'photo' => $photo,
            'caption' => $caption,
            'parse_mode' => 'HTML'
        ];

        if (isset($options['reply_markup'])) {
            $params['reply_markup'] = is_array($options['reply_markup']) 
                ? json_encode($options['reply_markup']) 
                : $options['reply_markup'];
        }

        return $this->request('sendPhoto', $params);
    }

    /**
     * Send Document
     */
    public function sendDocument($chatId, $document, $caption = '', $options = []) {
        $params = [
            'chat_id' => $chatId,
            'document' => $document,
            'caption' => $caption,
            'parse_mode' => 'HTML'
        ];

        if (isset($options['reply_markup'])) {
            $params['reply_markup'] = is_array($options['reply_markup']) 
                ? json_encode($options['reply_markup']) 
                : $options['reply_markup'];
        }

        return $this->request('sendDocument', $params);
    }

    /**
     * Edit Message Text
     */
    public function editMessageText($chatId, $messageId, $text, $options = []) {
        $params = [
            'chat_id' => $chatId,
            'message_id' => $messageId,
            'text' => $text,
            'parse_mode' => $options['parse_mode'] ?? 'HTML'
        ];

        if (isset($options['reply_markup'])) {
            $params['reply_markup'] = is_array($options['reply_markup']) 
                ? json_encode($options['reply_markup']) 
                : $options['reply_markup'];
        }

        return $this->request('editMessageText', $params);
    }

    /**
     * Delete Message
     */
    public function deleteMessage($chatId, $messageId) {
        return $this->request('deleteMessage', [
            'chat_id' => $chatId,
            'message_id' => $messageId
        ]);
    }

    /**
     * Answer Callback Query
     */
    public function answerCallbackQuery($callbackQueryId, $text = '', $showAlert = false) {
        $params = [
            'callback_query_id' => $callbackQueryId
        ];

        if (!empty($text)) {
            $params['text'] = $text;
            $params['show_alert'] = $showAlert;
        }

        return $this->request('answerCallbackQuery', $params);
    }

    /**
     * Set Webhook
     */
    public function setWebhook($url, $options = []) {
        $params = ['url' => $url];

        if (isset($options['max_connections'])) {
            $params['max_connections'] = $options['max_connections'];
        }

        if (isset($options['allowed_updates'])) {
            $params['allowed_updates'] = json_encode($options['allowed_updates']);
        }

        return $this->request('setWebhook', $params);
    }

    /**
     * Delete Webhook
     */
    public function deleteWebhook() {
        return $this->request('deleteWebhook', ['drop_pending_updates' => true]);
    }

    /**
     * Get Webhook Info
     */
    public function getWebhookInfo() {
        return $this->request('getWebhookInfo');
    }

    /**
     * Get Bot Info
     */
    public function getMe() {
        return $this->request('getMe');
    }

    /**
     * Send Chat Action
     */
    public function sendChatAction($chatId, $action = 'typing') {
        return $this->request('sendChatAction', [
            'chat_id' => $chatId,
            'action' => $action
        ]);
    }

    /**
     * Get File
     */
    public function getFile($fileId) {
        return $this->request('getFile', ['file_id' => $fileId]);
    }

    /**
     * Send Invoice (for Telegram Payments)
     */
    public function sendInvoice($chatId, $title, $description, $payload, $providerToken, $currency, $prices, $options = []) {
        $params = [
            'chat_id' => $chatId,
            'title' => $title,
            'description' => $description,
            'payload' => $payload,
            'provider_token' => $providerToken,
            'currency' => $currency,
            'prices' => json_encode($prices)
        ];

        foreach (['photo_url', 'photo_size', 'photo_width', 'photo_height', 'need_name', 'need_phone_number', 'need_email', 'need_shipping_address', 'is_flexible'] as $opt) {
            if (isset($options[$opt])) {
                $params[$opt] = $options[$opt];
            }
        }

        return $this->request('sendInvoice', $params);
    }

    /**
     * Answer Pre Checkout Query
     */
    public function answerPreCheckoutQuery($preCheckoutQueryId, $ok = true, $errorMessage = '') {
        $params = [
            'pre_checkout_query_id' => $preCheckoutQueryId,
            'ok' => $ok
        ];

        if (!$ok && !empty($errorMessage)) {
            $params['error_message'] = $errorMessage;
        }

        return $this->request('answerPreCheckoutQuery', $params);
    }

    /**
     * Get Chat Member
     */
    public function getChatMember($chatId, $userId) {
        return $this->request('getChatMember', [
            'chat_id' => $chatId,
            'user_id' => $userId
        ]);
    }

    /**
     * Ban Chat Member
     */
    public function banChatMember($chatId, $userId, $untilDate = 0) {
        $params = [
            'chat_id' => $chatId,
            'user_id' => $userId
        ];

        if ($untilDate > 0) {
            $params['until_date'] = $untilDate;
        }

        return $this->request('banChatMember', $params);
    }

    /**
     * Unban Chat Member
     */
    public function unbanChatMember($chatId, $userId) {
        return $this->request('unbanChatMember', [
            'chat_id' => $chatId,
            'user_id' => $userId
        ]);
    }

    /**
     * Create Inline Keyboard
     */
    public static function inlineKeyboard($buttons) {
        return ['inline_keyboard' => $buttons];
    }

    /**
     * Create Reply Keyboard
     */
    public static function replyKeyboard($buttons, $resize = true, $oneTime = false) {
        return [
            'keyboard' => $buttons,
            'resize_keyboard' => $resize,
            'one_time_keyboard' => $oneTime
        ];
    }

    /**
     * Remove Keyboard
     */
    public static function removeKeyboard() {
        return ['remove_keyboard' => true];
    }

    /**
     * Build Button
     */
    public static function button($text, $callbackData = null, $url = null) {
        $button = ['text' => $text];

        if ($callbackData !== null) {
            $button['callback_data'] = $callbackData;
        }

        if ($url !== null) {
            $button['url'] = $url;
        }

        return $button;
    }

    /**
     * Log message for debugging
     */
    private function log($message) {
        $logFile = LOGS_PATH . 'telegram_api.log';
        $date = date('Y-m-d H:i:s');
        file_put_contents($logFile, "[{$date}] {$message}
", FILE_APPEND | LOCK_EX);
    }
}
