<?php
declare(strict_types=1);
require_once __DIR__ . '/../helpers.php';
$config = require __DIR__ . '/../config.php';
$currentVersionCode = (int)($_GET['current_version_code'] ?? 0);
$conn = db();
$result = $conn->query('SELECT version_code, version_name, force_update, notes, apk_file_name FROM app_updates WHERE is_active = 1 ORDER BY version_code DESC LIMIT 1');
$row = $result->fetch_assoc();
if (!$row) {
    respond(['success' => true, 'message' => 'No update configured', 'data' => null]);
}
$row['version_code'] = (int)$row['version_code'];
$row['force_update'] = (bool)$row['force_update'];
$apkFileName = trim((string)($row['apk_file_name'] ?? ''));
if ($apkFileName === '') {
    respond(['success' => false, 'message' => 'Update APK filename is empty', 'data' => null]);
}
$apkDiskPath = realpath(__DIR__ . '/../apk');
if ($apkDiskPath === false || !is_file($apkDiskPath . DIRECTORY_SEPARATOR . $apkFileName)) {
    respond(['success' => false, 'message' => 'Update APK file not found on server', 'data' => null]);
}
$baseUrl = trim((string)($config['base_app_url'] ?? ''));
if ($baseUrl === '' || stripos($baseUrl, 'YOUR_SERVER') !== false) {
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $scriptDir = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '/updates')), '/');
    $baseUrl = $scheme . '://' . $host . preg_replace('#/updates$#', '', $scriptDir);
}
$row['apk_url'] = rtrim($baseUrl, '/') . '/apk/' . rawurlencode($apkFileName);
unset($row['apk_file_name']);
respond(['success' => true, 'data' => $row, 'is_newer' => $row['version_code'] > $currentVersionCode]);
