<?php
require __DIR__ . '/config.php';

$rel = isset($_GET['file']) ? $_GET['file'] : '';
$rel = ltrim(str_replace('\\', '/', $rel), '/');

if ($rel === '') {
    http_response_code(400);
    die('No file specified.');
}

// Reject any path containing a hidden/protected segment.
foreach (explode('/', $rel) as $segment) {
    if (zerg_is_hidden($segment)) {
        http_response_code(403);
        die('Access denied.');
    }
}

$full = zerg_safe_path($rel);

if ($full === false || !is_file($full)) {
    http_response_code(404);
    die('File not found.');
}

// Count the download before streaming.
zerg_bump_count($rel);

$filename = basename($full);
$mime = 'application/octet-stream';
if (function_exists('finfo_open')) {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $detected = finfo_file($finfo, $full);
    finfo_close($finfo);
    if ($detected) $mime = $detected;
}

header('Content-Description: File Transfer');
header('Content-Type: ' . $mime);
header('Content-Disposition: attachment; filename="' . str_replace('"', '', $filename) . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($full));
header('Cache-Control: no-cache, must-revalidate');
header('Expires: 0');

// Stream in chunks so large files don't blow up memory.
$handle = fopen($full, 'rb');
while (!feof($handle)) {
    echo fread($handle, 1024 * 512);
    flush();
}
fclose($handle);
exit;
