<?php
namespace Core;

class BaleAPI {
    private $token;
    private $apiUrl;
    
    public function __construct($token) {
        $this->token = $token;
        // 🔥 آدرس API مخصوص بله
        $this->apiUrl = "https://tapi.bale.ai/bot{$token}/";
    }
    
    // ارسال پیام متنی
    public function sendMessage($chatId, $text, $options = []) {
        $data = [
            'chat_id' => $chatId,
            'text' => $text,
            'parse_mode' => 'HTML'
        ];
        
        if (isset($options['reply_markup'])) {
            $data['reply_markup'] = $options['reply_markup'];
        }
        
        return $this->call('sendMessage', $data);
    }
    
    // ارسال عکس
    public function sendPhoto($chatId, $photo, $caption = '', $options = []) {
        $data = [
            'chat_id' => $chatId,
            'photo' => $photo,
            'caption' => $caption,
            'parse_mode' => 'HTML'
        ];
        
        if (isset($options['reply_markup'])) {
            $data['reply_markup'] = $options['reply_markup'];
        }
        
        return $this->call('sendPhoto', $data);
    }
    
    // پاسخ به دکمه‌ها
    public function answerCallbackQuery($callbackId, $text = '', $showAlert = false) {
        return $this->call('answerCallbackQuery', [
            'callback_query_id' => $callbackId,
            'text' => $text,
            'show_alert' => $showAlert
        ]);
    }
    
    // دریافت اطلاعات ربات
    public function getMe($token = null) {
        $url = $token ? "https://tapi.bale.ai/bot{$token}/getMe" : $this->apiUrl . 'getMe';
        $response = file_get_contents($url);
        $data = json_decode($response, true);
        return $data['ok'] ? $data['result'] : null;
    }
    
    // تنظیم Webhook برای بله
    public function setWebhook($token, $url) {
        $apiUrl = "https://tapi.bale.ai/bot{$token}/setWebhook";
        $data = ['url' => $url];
        
        $ch = curl_init($apiUrl);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);
        
        return json_decode($response, true);
    }
    
    // متد اصلی برای فراخوانی API
    private function call($method, $data = []) {
        $url = $this->apiUrl . $method;
        
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);
        
        return json_decode($response, true);
    }
}