<?php

$scriptStart = microtime(true);

// Telegram bot token and user ID
$armpToken = "6699635284:AAFklesnB4P6CmMz0mc8nIVq72XjSRf0gCQ";
$armpUserID = "6503581406";

// Read filters from Filters.txt
$filterLoadStart = microtime(true);
$filtersFile = "../Filters.txt";
if (!file_exists($filtersFile)) {
die("Filters.txt file not found.");
}

$Filters = file($filtersFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$Filters = array_map('trim', $Filters);

if (empty($Filters)) {
die("No filters found in Filters.txt.");
}

// Function to fetch content using cURL
function fetchContent($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36');
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

$html = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if (curl_errno($ch)) {
echo "cURL Error: " . curl_error($ch) . "\n";
curl_close($ch);
return false;
}

curl_close($ch);

if ($httpCode != 200) {
echo "HTTP Error: $httpCode\n";
return false;
}

return $html;
}

// Read channel usernames from chs.txt
$channelsFile = "chs.txt";
if (!file_exists($channelsFile)) {
die("chs.txt file not found.");
}

$channels = file($channelsFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

if (empty($channels)) {
die("No channels found in chs.txt.");
}

// Process each channel
foreach ($channels as $Channel) {
$channelStart = microtime(true);

$Channel = trim($Channel);
if (empty($Channel)) {
continue;
}

$url = "https://ble.ir/$Channel";

// Fetch the HTML content from the URL
$fetchStart = microtime(true);
$html = fetchContent($url);
$fetchTime = (microtime(true) - $fetchStart);

if ($html === false) {
echo "Failed to fetch content for channel: $Channel\n\n";
continue;
}

// Extract JSON data from the __NEXT_DATA__ script tag
$parseStart = microtime(true);
preg_match('/<script id="__NEXT_DATA__" type="application\/json">(.*?)<\/script>/s', $html, $matches);

if (empty($matches[1])) {
echo "No JSON data found for channel: $Channel\n\n";
continue;
}

$jsonData = json_decode($matches[1], true);

if (json_last_error() !== JSON_ERROR_NONE) {
echo "JSON decode error for channel: $Channel - " . json_last_error_msg() . "\n\n";
continue;
}

if (!isset($jsonData['props']['pageProps']['messages']) || empty($jsonData['props']['pageProps']['messages'])) {
echo "No messages found for channel: $Channel\n\n";
continue;
}

$messages = $jsonData['props']['pageProps']['messages'];
$lastMessage = end($messages);

$messageText = "";

if ($lastMessage['type'] === 'TEXT' && isset($lastMessage['message']['textMessage']['text'])) {
$messageText = $lastMessage['message']['textMessage']['text'];
}
elseif ($lastMessage['type'] === 'PHOTO' && isset($lastMessage['message']['documentMessage']['caption']['text'])) {
$messageText = $lastMessage['message']['documentMessage']['caption']['text'];
}
elseif ($lastMessage['type'] === 'VIDEO' && isset($lastMessage['message']['documentMessage']['caption']['text'])) {
$messageText = $lastMessage['message']['documentMessage']['caption']['text'];
}

$messageText = trim($messageText);
$parseTime = (microtime(true) - $parseStart);

if (empty($messageText)) {
echo "Empty message from channel: $Channel\n\n";
continue;
}

// Check filters
$filterStart = microtime(true);
$foundFilters = array();
foreach ($Filters as $filter) {
if (str_contains($messageText, $filter)) {
$foundFilters[] = $filter;
}
}
$filterCheckTime = (microtime(true) - $filterStart) * 1000;

if (!empty($foundFilters)) {
$channelFile = "$Channel.txt";
if (!file_exists($channelFile) || $messageText != file_get_contents($channelFile)) {
$filterList = implode(", ", $foundFilters);
$channelTotal = (microtime(true) - $channelStart);

$armpText = "<code>$messageText</code>

━━━━━━━━━━━━━━━━━━━━━━
🔔 NEW MESSAGE FROM BALE
━━━━━━━━━━━━━━━━━━━━━━

📍 Channel: @$Channel
🔍 Found Filter: $filterList

━━━━━━━━━━━━━━━━━━━━━━
⏱ PERFORMANCE STATS:
━━━━━━━━━━━━━━━━━━━━━━

⏳ Fetch Time: " . round($fetchTime, 2) . "s
⚙️ Parse Time: " . round($parseTime, 3) . "s
🔎 Filter Check: " . round($filterCheckTime, 2) . "ms
📊 Total Time: " . round($channelTotal, 2) . "s

━━━━━━━━━━━━━━━━━━━━━━";

$armp = file_get_contents("https://api.telegram.org/bot$armpToken/SendMessage?chat_id=$armpUserID&parse_mode=HTML&text=" . urlencode($armpText));
if ($armp) {
echo "Text Sent To TG for channel: $Channel. [" . round($channelTotal, 2) . "s]\n";
}

file_put_contents($channelFile, $messageText);
}
else {
echo "Text Already Sent To TG for channel: $Channel.\n";
}
}
else {
echo "Message from $Channel is not important.\n";
}
}

$scriptTotal = (microtime(true) - $scriptStart);

echo "\n━━━━━━━━━━━━━━━━━━━━━━\n";
echo "Script completed in " . round($scriptTotal, 2) . " seconds\n";
echo "━━━━━━━━━━━━━━━━━━━━━━\n";
?>