<?php
// ==============================================
// ✅ ARQUIVO: /api/check_update.php
// Lê SQLite (/api/express.db) e envia JSON para o aplicativo
// Formato:
// { "version_code": 12, "version_name":"1.2", "apk_url":"...", "changelog":"...", "force":false }
// ==============================================

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

$dbPath  = __DIR__ . '/express.db';
$apksDir = __DIR__ . '/apks';

// Helpers
function api_base_dir(): string {
    // dirname do SCRIPT_NAME aqui será algo como /ibo4/api
    $dir = dirname($_SERVER['SCRIPT_NAME'] ?? '/api');
    $dir = str_replace('\\', '/', $dir);
    if ($dir === '.') $dir = '/api';
    return rtrim($dir, '/');
}

function base_url_for_api(): string {
    $isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
        || (isset($_SERVER['SERVER_PORT']) && (int)$_SERVER['SERVER_PORT'] === 443);

    $scheme = $isHttps ? 'https' : 'http';
    $host   = $_SERVER['HTTP_HOST'] ?? 'localhost';

    $dir = api_base_dir(); // ex: /ibo4/api
    return $scheme . '://' . $host . $dir;
}

function out($arr) {
    echo json_encode($arr, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    if (!file_exists($dbPath)) {
        out([
            "version_code" => 0,
            "version_name" => "",
            "apk_url" => "",
            "changelog" => "",
            "force" => false,
            "error" => "DB não encontrado"
        ]);
    }

    $pdo = new PDO('sqlite:' . $dbPath);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Garante tabela (se alguém abrir direto sem usar o painel)
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS update_settings (
            id INTEGER PRIMARY KEY,
            version_code INTEGER NOT NULL DEFAULT 0,
            version_name TEXT DEFAULT '',
            apk_source TEXT NOT NULL DEFAULT 'remote',
            apk_url TEXT DEFAULT '',
            local_file TEXT DEFAULT '',
            changelog TEXT DEFAULT '',
            force INTEGER NOT NULL DEFAULT 0,
            updated_at TEXT DEFAULT ''
        )
    ");
    $pdo->exec("INSERT OR IGNORE INTO update_settings (id) VALUES (1)");

    $row = $pdo->query("SELECT * FROM update_settings WHERE id = 1")->fetch(PDO::FETCH_ASSOC);

    $versionCode = (int)($row['version_code'] ?? 0);
    $versionName = (string)($row['version_name'] ?? '');
    $source      = (string)($row['apk_source'] ?? 'remote');
    $apkUrl      = (string)($row['apk_url'] ?? '');
    $localFile   = (string)($row['local_file'] ?? '');
    $changelog   = (string)($row['changelog'] ?? '');
    $force       = ((int)($row['force'] ?? 0) === 1);

    // Se for local, recalcula URL com base no host atual (evita URL errada)
    if ($source === 'local' && $localFile !== '') {
        $filePath = $apksDir . '/' . $localFile;
        if (file_exists($filePath)) {
            $apkUrl = base_url_for_api() . '/apks/' . rawurlencode($localFile);
        } else {
            $apkUrl = ""; // arquivo sumiu
        }
    }

    out([
        "version_code" => $versionCode,
        "version_name" => $versionName,
        "apk_url"      => $apkUrl,
        "changelog"    => $changelog,
        "force"        => $force
    ]);

} catch (Exception $e) {
    out([
        "version_code" => 0,
        "version_name" => "",
        "apk_url" => "",
        "changelog" => "",
        "force" => false,
        "error" => $e->getMessage()
    ]);
}
