<?php
// TWARDE WYMUSZENIE UTF-8 (aby escapeshellarg nie zjadało liter np. "ł")
setlocale(LC_ALL, "pl_PL.UTF-8", "en_US.UTF-8", "C.UTF-8");
putenv("LC_ALL=C.UTF-8");

require_once 'functions.php';
checkAuth();

if (!validateCsrfToken()) die('Nieprawidłowy token bezpieczeństwa.');

session_write_close();
set_time_limit(0);
ignore_user_abort(true);

$cfg = cfg();

$folderKey = $_POST['folder'] ?? '';
$subPath = sanitizePath($_POST['path'] ?? '');
$files = $_POST['files'] ?? [];

if (empty($files) || !isset($cfg['allowedFolders'][$folderKey])) die('Odmowa dostępu lub brak plików.');

$basePath = '/mnt/mega' . $cfg['allowedFolders'][$folderKey];
$targetDir = rtrim($basePath . '/' . $subPath, '/');

$validFiles = [];
foreach($files as $file) {
    $safeName = basename($file);
    if(file_exists($targetDir . '/' . $safeName)) {
        $validFiles[] = escapeshellarg($safeName); 
    }
}

if (empty($validFiles)) die('Brak plików.');

$archiveName = "Paczka_Chmura_" . date('Ymd_His') . ".zip";

while (ob_get_level()) ob_end_clean();

header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . $archiveName . '"');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('X-Accel-Buffering: no'); 

$cmd = "cd " . escapeshellarg($targetDir) . " && zip -q -r -0 - " . implode(' ', $validFiles) . " 2>/dev/null";
passthru($cmd);
exit;
?>
