<?php
// فعال کردن لاگ‌گیری خطاها
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/php_errors.log');
error_log('Script started at ' . date('Y-m-d H:i:s'));

header('Content-Type: application/json');

// تنظیمات تلگرام
$telegramBotToken = '8155672747:AAFj19oadvAA5M3Gy-5YSduF8dW0nBPWgh8';
$telegramChatID = '-1002582157705';

// تابع برای ارسال پاسخ استاندارد
function sendResponse($status, $message = '', $data = []) {
    $response = ['status' => $status];
    if ($message) $response['message'] = $message;
    if (!empty($data)) $response = array_merge($response, $data);
    error_log('Sending response: ' . json_encode($response));
    echo json_encode($response);
    exit;
}

// اگر درخواست از نوع POST با محتوای x-www-form-urlencoded باشد
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    error_log('Received form-urlencoded POST request');
    $action = $_POST['action'];
    
    if ($action === 'download_clicked') {
        $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'نامشخص';
        $ip = $_SERVER['REMOTE_ADDR'] ?? 'نامشخص';
        $device = detectDevice($userAgent);
        $time = date('H:i:s');

        error_log("Download clicked - IP: $ip, Device: $device, Time: $time");
        sendTelegramNotification($telegramBotToken, $telegramChatID, $userAgent, $ip, $device, $time);
        sendResponse('success', 'Download recorded successfully');
        exit;
    }
}

// دریافت و اعتبارسنجی داده‌های ورودی
$input = file_get_contents('php://input');
error_log('Raw input received: ' . substr($input, 0, 500));

// اگر داده‌ای دریافت نشده باشد
if (empty($input)) {
    if (!empty($_POST)) {
        $input = json_encode($_POST);
        error_log('Using POST data instead: ' . print_r($_POST, true));
    } else {
        error_log('No input data received');
        sendResponse('error', 'No data received');
    }
}

$data = json_decode($input, true);

// اگر داده JSON معتبر نباشد
if (json_last_error() !== JSON_ERROR_NONE) {
    parse_str($input, $parsedData);
    
    if (!empty($parsedData)) {
        $data = $parsedData;
        error_log('Parsed form-urlencoded data: ' . print_r($parsedData, true));
    } else {
        $errorMsg = 'Invalid JSON data: ' . json_last_error_msg() . ' | Input: ' . substr($input, 0, 200);
        error_log($errorMsg);
        sendResponse('error', 'Invalid JSON data');
    }
}

error_log('Processed input data: ' . print_r($data, true));

// تشخیص نوع درخواست
if (isset($data['message'])) {
    error_log('Processing Telegram message');
    processTelegramMessage($data, $telegramBotToken, $telegramChatID);
} elseif (isset($data['my_chat_member'])) {
    error_log('Processing chat member update');
    processChatMemberUpdate($data, $telegramBotToken);
} elseif (isset($data['action'])) {
    error_log('Processing API request with action: ' . $data['action']);
    processApiRequest($data, $telegramBotToken, $telegramChatID);
} else {
    error_log('Unsupported request structure');
    sendResponse('error', 'Unsupported request structure');
}

// تابع پردازش به‌روزرسانی وضعیت چت
function processChatMemberUpdate($data, $botToken) {
    $update = $data['my_chat_member'];
    $chatId = $update['chat']['id'];
    $userId = $update['from']['id'];
    $oldStatus = $update['old_chat_member']['status'];
    $newStatus = $update['new_chat_member']['status'];
    
    error_log("Chat member status changed - User: $userId, Chat: $chatId, From: $oldStatus, To: $newStatus");
    
    sendResponse('success', 'Chat member update processed');
}

// تابع پردازش پیام‌های تلگرام
function processTelegramMessage($data, $botToken, $mainChatId) {
    $message = $data['message'];
    $currentChatId = $message['chat']['id'];
    error_log("Processing message from chat ID: $currentChatId");
    
    if (isset($message['text']) && strpos($message['text'], '/set') === 0) {
        error_log("Processing /set command");
        handleSetCommand($message, $currentChatId, $botToken, $mainChatId);
    } else {
        error_log("Ignoring unsupported message type");
        sendResponse('success', 'Message ignored');
    }
}

// تابع پردازش دستور /set
function handleSetCommand($message, $currentChatId, $botToken, $mainChatId) {
    if (isset($message['reply_to_message']['document'])) {
        $document = $message['reply_to_message']['document'];
        $fileId = $document['file_id'];
        $originalFileName = $document['file_name'] ?? 'file';
        $fileSize = formatFileSize($document['file_size']);
        $fileType = pathinfo($originalFileName, PATHINFO_EXTENSION);
        
        error_log("Processing file: $originalFileName, Size: $fileSize, Type: $fileType");
        
        $userFileName = trim(str_replace('/set', '', $message['text']));
        
        if (empty($userFileName)) {
            $userFileName = $originalFileName;
        } else {
            if (strpos($userFileName, '.') === false) {
                $userFileName .= '.' . $fileType;
            }
        }
        
        error_log("Final filename will be: $userFileName");
        
        $currentFilePath = __DIR__ . '/current_file.txt';
        $targetFilePath = __DIR__ . '/' . $userFileName;
        
        $fileInfo = getTelegramFileInfo($botToken, $fileId);
        if (!$fileInfo || !isset($fileInfo['result']['file_path'])) {
            error_log("Failed to get file info from Telegram");
            sendTelegramMessage($botToken, $currentChatId, "❌ اطلاعات فایل دریافت نشد.");
            return;
        }
        
        error_log("Telegram file path: " . $fileInfo['result']['file_path']);
        $uploadResult = uploadFileFromTelegram($botToken, $fileInfo, $userFileName);
        
        if ($uploadResult['success']) {
            file_put_contents($currentFilePath, $userFileName);
            $replaced = file_exists($targetFilePath) ? ' (جایگزین شد)' : '';
            error_log("File saved$replaced successfully: $userFileName");
            
            $uploader = $message['from']['first_name'] ?? 'ناشناس';
            if (isset($message['from']['last_name'])) {
                $uploader .= ' ' . $message['from']['last_name'];
            }
            
            error_log("File uploaded by: $uploader");
            
            $inlineKeyboard = [
                'inline_keyboard' => [
                    [
                        ['text' => "📅 تاریخ استخراج", 'callback_data' => 'show_date'],
                        ['text' => date('Y/m/d'), 'callback_data' => 'date_data']
                    ],
                    [
                        ['text' => "👤 کاربر استخراج کننده", 'callback_data' => 'show_uploader'],
                        ['text' => $uploader, 'callback_data' => 'uploader_data']
                    ],
                    [
                        ['text' => "📦 حجم فایل", 'callback_data' => 'show_size'],
                        ['text' => $fileSize, 'callback_data' => 'size_data']
                    ],
                    [
                        ['text' => "📝 نوع فایل", 'callback_data' => 'show_type'],
                        ['text' => strtoupper($fileType), 'callback_data' => 'type_data']
                    ],
                    [
                        ['text' => "🆕 نام فایل", 'callback_data' => 'show_filename'],
                        ['text' => $userFileName, 'callback_data' => 'filename_data']
                    ]
                ]
            ];
            
            $telegramData = [
                'chat_id' => $mainChatId,
                'text' => "✅ فایل با موفقیت آپلود شد" . $replaced,
                'reply_markup' => json_encode($inlineKeyboard)
            ];
            
            if ($message['chat']['id'] == $mainChatId && isset($message['reply_to_message']['message_id'])) {
                $telegramData['reply_to_message_id'] = $message['reply_to_message']['message_id'];
                error_log("Will reply to message ID: " . $message['reply_to_message']['message_id']);
            }
            
            error_log("Sending message to chat ID: $mainChatId");
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "https://api.telegram.org/bot$botToken/sendMessage");
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $telegramData);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $result = curl_exec($ch);
            
            if(curl_errno($ch)) {
                error_log('CURL error: ' . curl_error($ch));
            } else {
                $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                if($httpCode !== 200) {
                    error_log("Telegram API returned HTTP code: $httpCode\nResponse: $result");
                } else {
                    error_log("Message sent successfully to Telegram");
                }
            }
            
            curl_close($ch);
            
        } else {
            error_log("File upload failed: " . $uploadResult['error']);
            sendTelegramMessage($botToken, $currentChatId, "❌ خطا در آپلود فایل: {$uploadResult['error']}");
        }
    } else {
        error_log("Invalid /set command format");
        sendTelegramMessage($botToken, $currentChatId, "⚠️ لطفاً این دستور را روی یک فایل ریپلی کنید. مثال:\n/set filename.ext");
    }
}

// تابع پردازش درخواست‌های API
function processApiRequest($data, $botToken, $chatId) {
    try {
        if ($data['action'] === 'download') {
            $userAgent = isset($data['userAgent']) ? htmlspecialchars($data['userAgent']) : 'نامشخص';
            $ip = $_SERVER['REMOTE_ADDR'] ?? 'نامشخص';
            $device = detectDevice($userAgent);
            $time = date('H:i:s');

            error_log("API Download request - IP: $ip, Device: $device, UserAgent: $userAgent");
            sendTelegramNotification($botToken, $chatId, $userAgent, $ip, $device, $time);
            sendResponse('success', 'Download recorded successfully');
        } else {
            error_log('Unknown API action: ' . $data['action']);
            sendResponse('error', 'Unknown action');
        }
    } catch (Exception $e) {
        error_log('Error in API processing: ' . $e->getMessage());
        sendResponse('error', 'Internal server error');
    }
}

// تابع تشخیص دستگاه
function detectDevice($userAgent) {
    $userAgentLower = strtolower($userAgent);
    if (strpos($userAgentLower, 'android') !== false) return 'اندروید';
    if (strpos($userAgentLower, 'iphone') !== false || strpos($userAgentLower, 'ipad') !== false) return 'iOS';
    if (strpos($userAgentLower, 'windows') !== false) return 'ویندوز';
    if (strpos($userAgentLower, 'mac') !== false) return 'مک';
    if (strpos($userAgentLower, 'linux') !== false) return 'لینوکس';
    return 'نامشخص';
}

// تابع ارسال نوتیفیکیشن به تلگرام
function sendTelegramNotification($botToken, $chatId, $userAgent, $ip, $device, $time) {
    $message = "📤 کاربر وارد صفحه دانلود شما شد و اپلیکیشن شما رو دانلود کرد";
    error_log("Preparing Telegram notification: $message");
    
    $inlineKeyboard = [
        'inline_keyboard' => [
            [
                ['text' => "🕒 زمان", 'callback_data' => 'show_time'],
                ['text' => $time, 'callback_data' => 'time_data']
            ],
            [
                ['text' => "📱 دستگاه", 'callback_data' => 'show_device'],
                ['text' => $device, 'callback_data' => 'device_data']
            ],
            [
                ['text' => "🌐 آی‌پی", 'callback_data' => 'show_ip'],
                ['text' => $ip, 'callback_data' => 'ip_data']
            ]
        ]
    ];
    
    $telegramData = [
        'chat_id' => $chatId,
        'text' => $message,
        'parse_mode' => 'MarkdownV2',
        'reply_markup' => json_encode($inlineKeyboard)
    ];
    
    error_log("Sending Telegram notification");
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.telegram.org/bot$botToken/sendMessage");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $telegramData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    
    if(curl_errno($ch)) {
        error_log('CURL error: ' . curl_error($ch));
    } else {
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if($httpCode !== 200) {
            error_log("Telegram API returned HTTP code: $httpCode\nResponse: $result");
        } else {
            error_log("Notification sent successfully");
        }
    }
    
    curl_close($ch);
}

// توابع کمکی برای آپلود فایل
function getTelegramFileInfo($botToken, $fileId) {
    error_log("Getting file info from Telegram for file ID: $fileId");
    $fileInfoUrl = "https://api.telegram.org/bot$botToken/getFile?file_id=$fileId";
    $response = file_get_contents($fileInfoUrl);
    return json_decode($response, true);
}

function uploadFileFromTelegram($botToken, $fileInfo, $fileName) {
    if (!$fileInfo || !isset($fileInfo['result']['file_path'])) {
        error_log("Invalid file info received");
        return ['success' => false, 'error' => 'File info not available'];
    }
    
    $filePath = $fileInfo['result']['file_path'];
    $telegramFileUrl = "https://api.telegram.org/file/bot$botToken/$filePath";
    $savePath = __DIR__ . '/' . $fileName;
    
    error_log("Downloading file from Telegram: $telegramFileUrl");
    error_log("Saving to: $savePath");
    
    $fileContent = file_get_contents($telegramFileUrl);
    if ($fileContent === false) {
        error_log("Failed to download file from Telegram");
        return ['success' => false, 'error' => 'Could not download file'];
    }
    
    if (file_put_contents($savePath, $fileContent)) {
        error_log("File saved successfully: $fileName");
        return ['success' => true, 'filename' => $fileName];
    } else {
        error_log("Failed to save file locally");
        return ['success' => false, 'error' => 'Could not save file'];
    }
}

// تابع ارسال پیام به تلگرام
function sendTelegramMessage($botToken, $chatId, $text, $parseMode = null) {
    error_log("Sending Telegram message to $chatId: " . substr($text, 0, 100) . "...");
    $url = "https://api.telegram.org/bot$botToken/sendMessage";
    
    $data = [
        'chat_id' => $chatId,
        'text' => $text
    ];
    
    if ($parseMode) {
        $data['parse_mode'] = $parseMode;
    }
    
    $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);
    $result = curl_exec($ch);
    
    if(curl_errno($ch)) {
        error_log('CURL error: ' . curl_error($ch));
    } else {
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if($httpCode !== 200) {
            error_log("Telegram API returned HTTP code: $httpCode\nResponse: $result");
        } else {
            error_log("Message sent successfully");
        }
    }
    
    curl_close($ch);
}

// تابع فرمت‌دهی حجم فایل
function formatFileSize($bytes) {
    if ($bytes >= 1073741824) {
        return number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        return number_format($bytes / 1024, 2) . ' KB';
    } elseif ($bytes > 1) {
        return $bytes . ' bytes';
    } elseif ($bytes == 1) {
        return '1 byte';
    } else {
        return '0 bytes';
    }
}

error_log('Script execution completed at ' . date('Y-m-d H:i:s'));