<?php
require_once dirname(__DIR__) . '/_app_guard.php';
app_guard_validate();
header("Content-Type: application/json; charset=UTF-8");

$cfgFile = dirname(__DIR__) . "/check_update.json";

function update_public_base_url(): string {
    $https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https');
    $scheme = $https ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $origin = rtrim($scheme . '://' . $host, '/');
    $script = str_replace('\\', '/', (string)($_SERVER['SCRIPT_NAME'] ?? '/api/app.php'));
    $panelRoot = rtrim(str_replace('\\', '/', dirname(dirname($script))), '/');
    if ($panelRoot === '/' || $panelRoot === '.') $panelRoot = '';
    return $origin . $panelRoot;
}

function update_abs_url(string $url): string {
    $url = trim($url);
    if ($url === '') return '';
    if (preg_match('~^https?://~i', $url)) return $url;
    return update_public_base_url() . '/' . ltrim($url, '/');
}

function default_update_config(): array {
    return [
        "status" => "ok",
        "tv" => [
            "active" => false,
            "version_code" => 1,
            "version_name" => "1.0",
            "titulo" => "Versão incompatível",
            "mensagem" => "A versão instalada é diferente da versão liberada no painel.",
            "apk_url" => "",
            "force" => true,
            "match_mode" => "exact"
        ],
        "mobile" => [
            "active" => false,
            "version_code" => 1,
            "version_name" => "1.0",
            "titulo" => "Versão incompatível",
            "mensagem" => "A versão instalada é diferente da versão liberada no painel.",
            "apk_url" => "",
            "force" => true,
            "match_mode" => "exact"
        ]
    ];
}

function normalize_update_config($data): array {
    $default = default_update_config();
    if (!is_array($data)) return $default;

    if (isset($data["tv"]) || isset($data["mobile"])) {
        $out = $default;
        foreach (["tv", "mobile"] as $key) {
            if (isset($data[$key]) && is_array($data[$key])) {
                $out[$key] = array_merge($out[$key], $data[$key]);
                $out[$key]["active"] = !empty($out[$key]["active"]);
                $out[$key]["version_code"] = (int)($out[$key]["version_code"] ?? 1);
                $out[$key]["version_name"] = (string)($out[$key]["version_name"] ?? '');
                $out[$key]["apk_url"] = update_abs_url((string)($out[$key]["apk_url"] ?? ''));
                $out[$key]["force"] = !empty($out[$key]["force"]);
                $out[$key]["match_mode"] = "exact";
            }
        }
        return $out;
    }

    $default["tv"] = [
        "active" => !empty($data["active"]),
        "version_code" => (int)($data["version_code"] ?? $default["tv"]["version_code"]),
        "version_name" => (string)($data["version_name"] ?? $default["tv"]["version_name"]),
        "titulo" => (string)($data["titulo"] ?? $default["tv"]["titulo"]),
        "mensagem" => (string)($data["mensagem"] ?? $default["tv"]["mensagem"]),
        "apk_url" => update_abs_url((string)($data["apk_url"] ?? $default["tv"]["apk_url"])),
        "force" => !empty($data["force"]),
        "match_mode" => "exact"
    ];
    return $default;
}

if (!file_exists($cfgFile)) {
    file_put_contents($cfgFile, json_encode(default_update_config(), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}

$data = normalize_update_config(json_decode((string)file_get_contents($cfgFile), true));

$deviceType = strtolower(trim((string)($_REQUEST["device_type"] ?? "")));
$deviceKey = in_array($deviceType, ["mobile", "celular", "phone", "android"], true) ? "mobile" : ($deviceType === "tv" ? "tv" : "");

if ($deviceKey !== "") {
    echo json_encode(array_merge(["status" => "ok", "device_type" => $deviceKey], $data[$deviceKey]), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$legacy = array_merge(["status" => "ok"], $data["tv"], ["tv" => $data["tv"], "mobile" => $data["mobile"]]);
echo json_encode($legacy, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
