<?php
require_once 'functions.php';
checkAuth();
$cfg = cfg();

$folderKey = $_GET['folder'] ?? '';
$subPath = $_GET['path'] ?? '';
$fileName = $_GET['file'] ?? '';

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

$subPath = sanitizePath($subPath);
$fileName = basename($fileName);
if (empty($fileName) || $fileName === '.' || $fileName === '..') die('Zła nazwa pliku.');

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

if (!file_exists($localPath) || is_dir($localPath)) die('Błąd 404.');

recordDownload($megaPath); // Zapisujemy statystykę do JSON

$encodedFileName = rawurlencode($fileName);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $fileName . '"; filename*=UTF-8\'\'' . $encodedFileName);
header("X-Sendfile: " . $localPath);
exit;
