<?php
class TelegramNotifications {
    private $botToken;
    private $groupChatId;
    private $privateChatId;
    private $defaultThreadId;
    
    public function __construct($botToken, $groupChatId, $privateChatId, $defaultThreadId = "72338") {
        $this->botToken = $botToken;
        $this->groupChatId = $groupChatId;
        $this->privateChatId = $privateChatId;
        $this->defaultThreadId = $defaultThreadId;
    }
    
    public function sendActivationSuccess($deviceModel, $serialNumber, $iosVersion, $activationTime, $screenshot = null, $messageThreadId = null) {
        // Use default thread ID if none provided
        if ($messageThreadId === null) {
            $messageThreadId = $this->defaultThreadId;
        }
        
        $message = "✅ *Device Activated Successfully*\n\n" .
                   "📱 *Model:* $deviceModel\n" .
                   "🔢 *Serial:* $serialNumber\n" .
                   "⚙️ *iOS Version:* $iosVersion\n" .
                   "🕒 *Activation Time:* $activationTime\n\n" .
                   "🎉 *A12 Tool*";
        
        if ($screenshot) {
            return $this->sendPhotoWithCaption($message, $screenshot, $this->groupChatId, $messageThreadId);
        } else {
            return $this->sendMessage($message, $this->groupChatId, $messageThreadId);
        }
    }

        public function sendActivationError($deviceModel, $serialNumber, $iosVersion, $activationTime, $screenshot = null, $messageThreadId = null) {
        // Use default thread ID if none provided
        if ($messageThreadId === null) {
            $messageThreadId = $this->defaultThreadId;
        }
        
        $message = "❌ *Device Activation Error* ❌\n\n" .
                   "📱 *Model:* $deviceModel\n" .
                   "🔢 *Serial:* $serialNumber\n" .
                   "⚙️ *iOS Version:* $iosVersion\n" .
                   "🕒 *Activation Time:* $activationTime\n\n" .
                   "🎉 *A12 Tool*";
        
        if ($screenshot) {
            return $this->sendPhotoWithCaption($message, $screenshot, $this->groupChatId, $messageThreadId);
        } else {
            return $this->sendMessage($message, $this->groupChatId, $messageThreadId);
        }
    }
    
    public function sendToolUsage($action, $details = "", $screenshot = null, $messageThreadId = null) {
        // Use default thread ID if none provided
        if ($messageThreadId === null) {
            $messageThreadId = $this->defaultThreadId;
        }
        
        $message = "🔧 *Tool Usage Alert*\n\n" .
                   "📋 *Action:* $action\n" .
                   "📝 *Details:* $details\n" .
                   "🕒 *Time:* " . date('Y-m-d H:i:s');
        
        if ($screenshot) {
            return $this->sendPhotoWithCaption($message, $screenshot, $this->groupChatId, $messageThreadId);
        } else {
            return $this->sendMessage($message, $this->groupChatId, $messageThreadId);
        }
    }
    
    public function sendErrorAlert($errorMessage, $deviceInfo = "", $screenshot = null, $logFile = null, $logFileName = null, $caption = null) {
        // ALWAYS send errors to private chat (no thread)
        
        // Use provided caption or create default one
        $message = $caption ?: "❌ *Activation Error*\n\n" .
                   "⚠️ *Error:* $errorMessage\n" .
                   "📱 *Device:* $deviceInfo\n" .
                   "🕒 *Time:* " . date('Y-m-d H:i:s');
        
        // If we have both screenshot and log file, send them together properly
        if ($screenshot && $logFile) {
            return $this->sendPhotoWithDocument($message, $screenshot, $logFile, $logFileName, $this->privateChatId);
        }
        // If we have only screenshot
        elseif ($screenshot) {
            return $this->sendPhotoWithCaption($message, $screenshot, $this->privateChatId);
        }
        // If we have only log file
        elseif ($logFile) {
            return $this->sendDocumentWithCaption($message, $logFile, $logFileName, $this->privateChatId);
        }
        // If we have neither, send text message
        else {
            return $this->sendMessage($message, $this->privateChatId);
        }
    }
    
    public function sendScreenshot($caption = "", $screenshot = null, $messageThreadId = null) {
        // Use default thread ID if none provided
        if ($messageThreadId === null) {
            $messageThreadId = $this->defaultThreadId;
        }
        
        $message = "📸 *Tool Screenshot*\n\n" .
                   "📝 *Caption:* $caption\n" .
                   "🕒 *Time:* " . date('Y-m-d H:i:s');
        
        if ($screenshot) {
            return $this->sendPhotoWithCaption($message, $screenshot, $this->groupChatId, $messageThreadId);
        } else {
            return $this->sendMessage("❌ No screenshot provided", $this->groupChatId, $messageThreadId);
        }
    }
    
    private function sendMessage($text, $chatId, $messageThreadId = null) {
        $url = "https://api.telegram.org/bot{$this->botToken}/sendMessage";
        
        $data = [
            'chat_id' => $chatId,
            'text' => $text,
            'parse_mode' => 'Markdown',
            'disable_web_page_preview' => true
        ];
        
        // Add message thread ID for topics if provided (only for group chats)
        if ($messageThreadId !== null && $chatId == $this->groupChatId) {
            $data['message_thread_id'] = $messageThreadId;
        }
        
        $options = [
            'http' => [
                'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                'method' => 'POST',
                'content' => http_build_query($data),
            ],
        ];
        
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        
        return $result !== false;
    }
    
    private function sendPhotoWithCaption($caption, $photoData, $chatId, $messageThreadId = null) {
        $url = "https://api.telegram.org/bot{$this->botToken}/sendPhoto";
        
        // Decode base64 image data
        $imageData = base64_decode($photoData);
        if ($imageData === false) {
            // If decoding fails, send text message instead
            return $this->sendMessage($caption . "\n\n❌ *Failed to process screenshot*", $chatId, $messageThreadId);
        }
        
        // Create temporary file
        $tempFile = tempnam(sys_get_temp_dir(), 'telegram_img');
        file_put_contents($tempFile, $imageData);
        
        // Prepare multipart form data
        $data = [
            'chat_id' => $chatId,
            'caption' => $caption,
            'parse_mode' => 'Markdown',
            'photo' => new CURLFile($tempFile, 'image/png', 'screenshot.png')
        ];
        
        // Add message thread ID for topics if provided (only for group chats)
        if ($messageThreadId !== null && $chatId == $this->groupChatId) {
            $data['message_thread_id'] = $messageThreadId;
        }
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        
        $result = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        // Clean up temporary file
        unlink($tempFile);
        
        return $httpCode === 200 && $result !== false;
    }
    
    private function sendDocumentWithCaption($caption, $documentData, $fileName, $chatId, $messageThreadId = null) {
        $url = "https://api.telegram.org/bot{$this->botToken}/sendDocument";
        
        // Decode base64 document data
        $fileData = base64_decode($documentData);
        if ($fileData === false) {
            return $this->sendMessage($caption . "\n\n❌ *Failed to process log file*", $chatId, $messageThreadId);
        }
        
        // Create temporary file
        $tempFile = tempnam(sys_get_temp_dir(), 'telegram_log');
        file_put_contents($tempFile, $fileData);
        
        // Prepare multipart form data
        $data = [
            'chat_id' => $chatId,
            'caption' => $caption,
            'parse_mode' => 'Markdown',
            'document' => new CURLFile($tempFile, 'text/plain', $fileName)
        ];
        
        // Add message thread ID for topics if provided (only for group chats)
        if ($messageThreadId !== null && $chatId == $this->groupChatId) {
            $data['message_thread_id'] = $messageThreadId;
        }
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        
        $result = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        // Clean up temporary file
        unlink($tempFile);
        
        return $httpCode === 200 && $result !== false;
    }
    
    private function sendPhotoWithDocument($caption, $photoData, $documentData, $fileName, $chatId, $messageThreadId = null) {
        // First send the photo with caption
        $photoSuccess = $this->sendPhotoWithCaption($caption, $photoData, $chatId, $messageThreadId);
        
        if ($photoSuccess) {
            // If photo was sent successfully, send the document with a simple caption
            $documentCaption = "📄 *Log File: $fileName*";
            return $this->sendDocumentWithCaption($documentCaption, $documentData, $fileName, $chatId, $messageThreadId);
        }
        
        return false;
    }
}

// Main request handler
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    
    $botToken = "8215749544:AAGhzHlBzw0b4_5I_zvih0cZuLgtWga1NLc";
    $groupChatId = "7884597653"; // Your group chat ID
    $privateChatId = "7884597653"; // Your private chat ID
    $defaultThreadId = "0"; // Your default thread ID
    
    $telegram = new TelegramNotifications($botToken, $groupChatId, $privateChatId, $defaultThreadId);
    
    $action = $input['action'] ?? '';
    $screenshot = $input['screenshot'] ?? null;
    $messageThreadId = $input['message_thread_id'] ?? null; // Can still override via request
    $logFile = $input['log_file'] ?? null;
    $logFileName = $input['log_file_name'] ?? 'error_log.log';
    $caption = $input['caption'] ?? null;
    
    $response = false;
    
    switch ($action) {
        case 'activation_success':
            $response = $telegram->sendActivationSuccess(
                $input['device_model'] ?? '',
                $input['serial_number'] ?? '',
                $input['ios_version'] ?? '',
                $input['activation_time'] ?? '',
                $screenshot,
                $messageThreadId
            );
            break;

             case 'activation_error':
            $response = $telegram->sendActivationError(
                $input['device_model'] ?? '',
                $input['serial_number'] ?? '',
                $input['ios_version'] ?? '',
                $input['activation_time'] ?? '',
                $screenshot,
                $messageThreadId
            );
            break;
            
        case 'tool_usage':
            $response = $telegram->sendToolUsage(
                $input['action_type'] ?? '',
                $input['details'] ?? '',
                $screenshot,
                $messageThreadId
            );
            break;
            
        case 'error_alert':
        case 'error_alert_screenshot':
            $response = $telegram->sendErrorAlert(
                $input['error_message'] ?? '',
                $input['device_info'] ?? '',
                $screenshot,
                $logFile,
                $logFileName,
                $caption
            );
            break;
            
        case 'screenshot':
            $response = $telegram->sendScreenshot(
                $input['details'] ?? '',
                $screenshot,
                $messageThreadId
            );
            break;
            
        default:
            $response = false;
    }
    
    header('Content-Type: application/json');
    echo json_encode(['success' => $response]);
    exit;
}
?>