<?php
$BASE_DIR = __DIR__;
$CONFIG_PATH = $BASE_DIR . '/config.json';
$UPLOADS_DIR = $BASE_DIR . '/uploads';

if (!is_dir($UPLOADS_DIR)) {
    mkdir($UPLOADS_DIR, 0755, true);
}

function loadConfig() {
    global $CONFIG_PATH;
    $j = file_get_contents($CONFIG_PATH);
    return $j ? json_decode($j, true) : [];
}

function sendTelegram($text) {
    $cfg = loadConfig();
    $token = $cfg['telegram']['bot_token'] ?? '';
    $chatId = $cfg['telegram']['chat_id'] ?? '';
    if (!$token || $token === 'YOUR_BOT_TOKEN_HERE') return false;
    if (!$chatId || $chatId === 'YOUR_CHAT_ID_HERE') return false;
    $url = "https://api.telegram.org/bot{$token}/sendMessage";
    $payload = json_encode(['chat_id' => $chatId, 'text' => $text, 'parse_mode' => 'HTML']);

    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 10
        ]);
        $r = @curl_exec($ch);
        $ok = ($r !== false && curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200);
        curl_close($ch);
        return $ok;
    }
    $ctx = stream_context_create([
        'http' => [
            'method' => 'POST',
            'header' => "Content-Type: application/json\r\n",
            'content' => $payload,
            'timeout' => 10
        ]
    ]);
    $r = @file_get_contents($url, false, $ctx);
    return $r !== false;
}

function isLikelyBot($ua) {
    if (empty($ua)) return true;
    $ua = strtolower($ua);
    $patterns = ['bot', 'crawler', 'spider', 'scraper', 'headless', 'phantom', 'selenium', 'puppeteer', 'playwright', 'curl', 'wget', 'python-requests', 'go-http-client', 'java/', 'apache-httpclient', 'okhttp', 'scrapy', 'googlebot', 'bingbot', 'yandexbot', 'baiduspider', 'facebookexternalhit', 'twitterbot', 'linkedinbot', 'slurp', 'duckduckbot', 'applebot', 'petalbot'];
    foreach ($patterns as $p) {
        if (strpos($ua, $p) !== false) return true;
    }
    return false;
}
