<?php
require_once 'functions.php';
checkAuth();

// [!!!] Zwalnia sesję przed wysyłaniem pliku. Zapobiega "wieszaniu się" auto-next.
session_write_close(); 

$cfg = cfg();
$folderKey = $_GET['folder'] ?? '';
$subPath = sanitizePath($_GET['path'] ?? '');
$fileName = basename($_GET['file'] ?? '');

if (!isset($cfg['allowedFolders'][$folderKey])) die('Odmowa dostępu.');

$megaPath = rtrim($cfg['allowedFolders'][$folderKey] . '/' . $subPath, '/') . '/' . $fileName;
$localPath = '/mnt/mega' . $megaPath;

if (!file_exists($localPath) || is_dir($localPath)) die('Plik nie istnieje.');

recordDownload($megaPath);

$ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

$mimeTypes = [
    'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif', 'webp' => 'image/webp', 'svg' => 'application/octet-stream',
    'mp4' => 'video/mp4', 'webm' => 'video/webm',
    'mp3' => 'audio/mpeg', 'wav' => 'audio/wav', 'ogg' => 'audio/ogg', 'oga' => 'audio/ogg', 'flac' => 'audio/flac', 'm4a' => 'audio/mp4', 'aac' => 'audio/aac',
    'pdf' => 'application/pdf', 'txt' => 'text/plain; charset=utf-8', 'json' => 'application/json; charset=utf-8', 'xml' => 'application/xml; charset=utf-8', 'csv' => 'text/csv; charset=utf-8', 'html' => 'application/octet-stream', 'css' => 'text/css; charset=utf-8', 'js' => 'application/javascript; charset=utf-8'
];

$contentType = $mimeTypes[$ext] ?? 'application/octet-stream';

$forceDownload = in_array($ext, ['html', 'htm', 'svg'], true);

if ($contentType !== 'application/octet-stream' && !$forceDownload) {
    header('Content-Disposition: inline; filename="' . $fileName . '"');
} else {
    header('Content-Disposition: attachment; filename="' . $fileName . '"');
}

header('Content-Type: ' . $contentType);
header('X-Content-Type-Options: nosniff');
header('X-Sendfile: ' . $localPath);
exit;
?>
