<?php
/**
 * Main Bot Class
 * Version: 2.0
 * PHP: 7.4+
 */

declare(strict_types=1);

class Bot {
    private Telegram $telegram;
    private Database $db;
    private ?object $update = null;
    private ?object $message = null;
    private ?object $callbackQuery = null;
    
    // Message properties
    private ?int $chatId = null;
    private ?int $userId = null;
    private ?int $messageId = null;
    private ?string $text = null;
    private ?string $chatType = null;
    private ?string $firstName = null;
    private ?string $lastName = null;
    private ?string $username = null;
    
    public function __construct() {
        $this->telegram = Telegram::getInstance();
        $this->db = Database::getInstance();
        
        // Load additional systems
        require_once 'Language.php';
        require_once 'PluginManager.php';
        require_once 'services/GeminiAI.php';
        require_once 'SubscriptionManager.php';
        require_once 'AccessControl.php';
        
        $this->loadUpdate();
    }
    
    /**
     * Load update from Telegram
     */
    private function loadUpdate(): void {
        $input = file_get_contents('php://input');
        if (!$input) {
            return;
        }
        
        $this->update = json_decode($input);
        
        if (isset($this->update->message)) {
            $this->message = $this->update->message;
            $this->loadMessageData();
        } elseif (isset($this->update->callback_query)) {
            $this->callbackQuery = $this->update->callback_query;
            $this->message = $this->callbackQuery->message;
            $this->loadCallbackData();
        } elseif (isset($this->update->edited_message)) {
            $this->message = $this->update->edited_message;
            $this->loadMessageData();
        }
    }
    
    /**
     * Load message data
     */
    private function loadMessageData(): void {
        if (!$this->message) {
            return;
        }
        
        $this->chatId = $this->message->chat->id ?? null;
        $this->chatType = $this->message->chat->type ?? null;
        $this->messageId = $this->message->message_id ?? null;
        $this->text = $this->message->text ?? $this->message->caption ?? null;
        
        if (isset($this->message->from)) {
            $this->userId = $this->message->from->id;
            $this->firstName = $this->message->from->first_name ?? null;
            $this->lastName = $this->message->from->last_name ?? null;
            $this->username = $this->message->from->username ?? null;
        }
    }
    
    /**
     * Load callback data
     */
    private function loadCallbackData(): void {
        if (!$this->callbackQuery) {
            return;
        }
        
        $this->chatId = $this->message->chat->id ?? null;
        $this->chatType = $this->message->chat->type ?? null;
        $this->messageId = $this->message->message_id ?? null;
        
        if (isset($this->callbackQuery->from)) {
            $this->userId = $this->callbackQuery->from->id;
            $this->firstName = $this->callbackQuery->from->first_name ?? null;
            $this->lastName = $this->callbackQuery->from->last_name ?? null;
            $this->username = $this->callbackQuery->from->username ?? null;
        }
    }
    
    /**
     * Process update
     */
    public function process(): void {
        if (!$this->update) {
            return;
        }
        
        // Check if message is too old (more than 5 seconds)
        // Disabled temporarily - server time might be incorrect
        /*
        if ($this->message && isset($this->message->date)) {
            if (time() - $this->message->date > 5) {
                return;
            }
        }
        */
        
        // Set user language
        if ($this->userId) {
            $lang = Language::getInstance();
            $userLang = $lang->getUserLanguage($this->userId);
            $lang->setLanguage($userLang);
        }
        
        // Trigger plugin events
        $this->triggerPluginEvents();
        
        // Route to appropriate handler
        if ($this->chatType === 'private') {
            $this->handlePrivateChat();
        } elseif ($this->chatType === 'supergroup') {
            $this->handleSupergroup();
        } elseif ($this->chatType === 'group') {
            $this->handleGroup();
        }
        
        // Handle callback queries
        if ($this->callbackQuery) {
            $this->handleCallback();
        }
    }
    
    /**
     * Trigger plugin events
     */
    private function triggerPluginEvents(): void {
        $pluginManager = PluginManager::getInstance();
        
        // Message event
        if ($this->message && $this->text) {
            $pluginManager->triggerEvent('message', [
                'chat_id' => $this->chatId,
                'user_id' => $this->userId,
                'text' => $this->text,
                'chat_type' => $this->chatType,
                'message' => $this->message
            ]);
        }
        
        // New member event
        if ($this->message && isset($this->message->new_chat_members)) {
            foreach ($this->message->new_chat_members as $member) {
                $pluginManager->triggerEvent('newMember', [
                    'chat_id' => $this->chatId,
                    'user_id' => $member->id,
                    'first_name' => $member->first_name ?? '',
                    'username' => $member->username ?? ''
                ]);
            }
        }
        
        // Command event
        if ($this->text && preg_match('/^[\/\!](\w+)/', $this->text, $matches)) {
            $pluginManager->triggerEvent('command', [
                'chat_id' => $this->chatId,
                'user_id' => $this->userId,
                'command' => $matches[1],
                'text' => $this->text
            ]);
        }
    }
    
    /**
     * Handle private chat
     */
    private function handlePrivateChat(): void {
        // Save user if not exists
        $this->saveUser();
        
        // Check if user is admin
        if ($this->isAdmin()) {
            require_once 'handlers/AdminPanel.php';
            $panel = new AdminPanel($this);
            $panel->handle();
            return;
        }
        
        // Handle subscription commands
        require_once 'handlers/SubscriptionHandler.php';
        $subHandler = new SubscriptionHandler($this);
        
        // Check if it's a photo (receipt)
        if ($this->message && isset($this->message->photo)) {
            $photo = end($this->message->photo);
            $subHandler->handleReceiptPhoto($photo->file_id);
            return;
        }
        
        // Handle subscription commands
        $subHandler->handle();
        
        // Handle user commands
        require_once 'handlers/PrivateChat.php';
        $handler = new PrivateChat($this);
        $handler->handle();
    }
    
    /**
     * Handle supergroup
     */
    private function handleSupergroup(): void {
        require_once 'handlers/GroupManager.php';
        $manager = new GroupManager($this);
        $manager->handle();
    }
    
    /**
     * Handle regular group
     */
    private function handleGroup(): void {
        $this->telegram->sendMessage(
            $this->chatId,
            "⚠️ ربات فقط در گروه‌های سوپر قابل استفاده است!\n\n" .
            "لطفاً گروه را به سوپرگروه تبدیل کنید."
        );
        $this->telegram->leaveChat($this->chatId);
    }
    
    /**
     * Handle callback query
     */
    private function handleCallback(): void {
        if ($this->chatType === 'private') {
            if ($this->isAdmin()) {
                require_once 'handlers/AdminPanel.php';
                $panel = new AdminPanel($this);
                $panel->handleCallback();
            } else {
                require_once 'handlers/SubscriptionHandler.php';
                $subHandler = new SubscriptionHandler($this);
                $subHandler->handleCallback();
            }
        } elseif ($this->chatType === 'supergroup') {
            require_once 'handlers/GroupManager.php';
            $manager = new GroupManager($this);
            $manager->handleCallback();
        }
    }
    
    /**
     * Save user to database
     */
    private function saveUser(): void {
        if (!$this->userId) {
            return;
        }
        
        $exists = $this->db->fetchOne(
            "SELECT id FROM `members` WHERE id = ?",
            [$this->userId]
        );
        
        if (!$exists) {
            $this->db->insert('members', [
                'id' => $this->userId,
                'username' => $this->username,
                'first_name' => $this->firstName
            ]);
        }
    }
    
    /**
     * Check if user is admin
     */
    public function isAdmin(?int $userId = null): bool {
        $userId = $userId ?? $this->userId;
        return in_array($userId, ADMIN_IDS);
    }
    
    // Getters
    public function getTelegram(): Telegram { return $this->telegram; }
    public function getDb(): Database { return $this->db; }
    public function getUpdate(): ?object { return $this->update; }
    public function getMessage(): ?object { return $this->message; }
    public function getCallbackQuery(): ?object { return $this->callbackQuery; }
    public function getChatId(): ?int { return $this->chatId; }
    public function getUserId(): ?int { return $this->userId; }
    public function getMessageId(): ?int { return $this->messageId; }
    public function getText(): ?string { return $this->text; }
    public function getChatType(): ?string { return $this->chatType; }
    public function getFirstName(): ?string { return $this->firstName; }
    public function getLastName(): ?string { return $this->lastName; }
    public function getUsername(): ?string { return $this->username; }
    
    /**
     * Get callback data
     */
    public function getCallbackData(): ?string {
        return $this->callbackQuery->data ?? null;
    }
}
