<?php
// Plaza dynamic APK downloader
// Upload your APK file into the /download folder.
// The APK filename can be anything. If multiple APK files exist, the newest modified APK will be downloaded.

$downloadDir = __DIR__ . DIRECTORY_SEPARATOR . 'download';

if (!is_dir($downloadDir)) {
    http_response_code(404);
    header('Content-Type: text/plain; charset=UTF-8');
    echo 'Download folder not found.';
    exit;
}

$apkFiles = glob($downloadDir . DIRECTORY_SEPARATOR . '*.[aA][pP][kK]');

if (!$apkFiles || count($apkFiles) === 0) {
    http_response_code(404);
    header('Content-Type: text/plain; charset=UTF-8');
    echo 'APK file not found. Please upload one .apk file into the download folder.';
    exit;
}

// Sort by modified time, newest first. Compatible with older PHP versions.
usort($apkFiles, function ($a, $b) {
    $timeA = filemtime($a);
    $timeB = filemtime($b);

    if ($timeA == $timeB) {
        return 0;
    }

    return ($timeA > $timeB) ? -1 : 1;
});

$filePath = realpath($apkFiles[0]);
$realDownloadDir = realpath($downloadDir);

if ($filePath === false || $realDownloadDir === false || strpos($filePath, $realDownloadDir . DIRECTORY_SEPARATOR) !== 0 || !is_file($filePath)) {
    http_response_code(403);
    header('Content-Type: text/plain; charset=UTF-8');
    echo 'Invalid download file.';
    exit;
}

$fileName = basename($filePath);
$fileSize = filesize($filePath);

if ($fileSize === false) {
    http_response_code(500);
    header('Content-Type: text/plain; charset=UTF-8');
    echo 'Unable to read APK file size.';
    exit;
}

// Clear previous output to prevent corrupt APK downloads.
while (ob_get_level() > 0) {
    ob_end_clean();
}

// Safe ASCII fallback filename for old browsers.
$fallbackName = preg_replace('/[^A-Za-z0-9._-]/', '_', $fileName);
if ($fallbackName === '' || $fallbackName === null) {
    $fallbackName = 'Plaza.apk';
}

header('Content-Type: application/vnd.android.package-archive');
header('Content-Transfer-Encoding: binary');
header('Content-Disposition: attachment; filename="' . $fallbackName . '"; filename*=UTF-8\'\'' . rawurlencode($fileName));
header('Content-Length: ' . $fileSize);
header('X-Content-Type-Options: nosniff');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

readfile($filePath);
exit;
