<?php

declare(strict_types=1);

require __DIR__ . '/bootstrap.php';

$config = mergeSiteConfig(loadSiteConfigRaw());
$apkPath = getApkPath($config);

if ($apkPath === null) {
    http_response_code(404);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'APK 尚未上传，请联系管理员。';
    exit;
}

$fileSize = filesize($apkPath);
if ($fileSize === false || $fileSize < 1) {
    http_response_code(503);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'APK 文件无效，请管理员重新上传。';
    exit;
}

recordDownload();

$downloadName = trim((string)($config['apk_original_name'] ?? 'boss-app.apk'));
if ($downloadName === '') {
    $downloadName = 'boss-app.apk';
}
if (!str_ends_with(strtolower($downloadName), '.apk')) {
    $downloadName .= '.apk';
}

$safeName = preg_replace('/[^\w\.\-]+/u', '_', $downloadName) ?: 'boss-app.apk';
$fileSize = filesize($apkPath);

header('Content-Type: application/vnd.android.package-archive');
header('Content-Disposition: attachment; filename="' . $safeName . '"');
header('Content-Length: ' . (string)$fileSize);
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Pragma: no-cache');

if (ob_get_level()) {
    ob_end_clean();
}

readfile($apkPath);
exit;
