<?php
setlocale(LC_CTYPE, "pl_PL.UTF-8", "en_US.UTF-8", "C.UTF-8");
require_once 'functions.php';
checkAuth();
if ($_SESSION['role'] !== 'admin') die(json_encode(['status'=>'error', 'msg'=>'Odmowa dostępu!']));

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

if (!isset($cfg['allowedFolders'][$folderKey])) die(json_encode(['status'=>'error']));
$basePath = '/mnt/mega' . $cfg['allowedFolders'][$folderKey];
$targetDir = rtrim($basePath . '/' . $subPath, '/');

if ($action === 'delete') {
    $file = basename($_POST['file'] ?? '');
    $fullPath = $targetDir . '/' . $file;
    if (file_exists($fullPath)) { is_dir($fullPath) ? exec("rm -rf " . escapeshellarg($fullPath)) : unlink($fullPath); echo json_encode(['status'=>'ok']); } else echo json_encode(['status'=>'error']);
}
elseif ($action === 'multi_delete') {
    $files = $_POST['files'] ?? [];
    foreach($files as $file) {
        $safeName = basename($file);
        $fullPath = $targetDir . '/' . $safeName;
        if(file_exists($fullPath)) {
            is_dir($fullPath) ? exec("rm -rf " . escapeshellarg($fullPath)) : unlink($fullPath);
        }
    }
    echo json_encode(['status'=>'ok']);
}
elseif ($action === 'rename') {
    $old = basename($_POST['old_name'] ?? ''); $new = basename($_POST['new_name'] ?? '');
    if(rename($targetDir . '/' . $old, $targetDir . '/' . $new)) echo json_encode(['status'=>'ok']); else echo json_encode(['status'=>'error']);
}
elseif ($action === 'upload') {
    if (!empty($_FILES['files']['name'][0])) {
        $errors = [];
        foreach($_FILES['files']['name'] as $k => $name) {
            $filename = basename($name);
            $tmpName = $_FILES['files']['tmp_name'][$k];
            if(!move_uploaded_file($tmpName, $targetDir . '/' . $filename)) $errors[] = $filename;
        }
        
        // POPRAWKA: Czeka 10 minut i wywołuje czysty skrypt systemowy do usunięcia VFS Cache
        exec("nohup bash -c 'sleep 600 && sudo -n /usr/local/bin/clean_vfs.sh' >/dev/null 2>&1 < /dev/null &");
        
        if (empty($errors)) echo json_encode(['status'=>'ok']); else echo json_encode(['status'=>'error', 'msg'=>'Błąd wgrywania: ' . implode(', ', $errors)]);
    } else echo json_encode(['status'=>'error', 'msg'=>'Brak plików.']);
}
elseif ($action === 'upload_cookies') {
    if (!empty($_FILES['cookie_file']['tmp_name'])) {
        $target = __DIR__ . '/data/cookies.txt';
        $content = file_get_contents($_FILES['cookie_file']['tmp_name']);
        if ($content === false) die(json_encode(['status'=>'error', 'msg'=>'Serwer nie mógł odczytać wgranego pliku!']));
        if(file_put_contents($target, $content) !== false) {
            chmod($target, 0666);
            $rozmiar = round(strlen($content) / 1024, 2);
            echo json_encode(['status'=>'ok', 'msg'=>'Sukces! Ciasteczka wgrane! Waga: ' . $rozmiar . ' KB. Wyczyść log i pobieraj.']);
        } else echo json_encode(['status'=>'error', 'msg'=>'Błąd zapisu! Sprawdź uprawnienia do folderu data/']);
    } else echo json_encode(['status'=>'error', 'msg'=>'Nie przesłano żadnego pliku.']);
}
elseif ($action === 'mkdir') {
    $name = basename($_POST['name'] ?? '');
    if(mkdir($targetDir . '/' . $name, 0777, true)) echo json_encode(['status'=>'ok']); else echo json_encode(['status'=>'error', 'msg'=>'Błąd tworzenia folderu.']);
}
elseif ($action === 'move' || $action === 'copy') {
    $files = $_POST['files'] ?? [];
    $destFolderKey = $_POST['dest_folder'] ?? ''; $destSubPath = sanitizePath($_POST['dest_path'] ?? '');
    if (!isset($cfg['allowedFolders'][$destFolderKey])) die(json_encode(['status'=>'error', 'msg'=>'Błędny folder docelowy']));
    $destBase = rtrim('/mnt/mega' . $cfg['allowedFolders'][$destFolderKey] . '/' . $destSubPath, '/');
    if (!is_dir($destBase)) mkdir($destBase, 0777, true);

    foreach($files as $file) {
        $safeName = basename($file);
        $src = $targetDir . '/' . $safeName; $dst = $destBase . '/' . $safeName;
        if(file_exists($src)) {
            if ($action === 'move') rename($src, $dst);
            if ($action === 'copy') exec("cp -r " . escapeshellarg($src) . " " . escapeshellarg($dst));
        }
    }
    echo json_encode(['status'=>'ok']);
}
elseif ($action === 'unpack') {
    $files = $_POST['files'] ?? [];
    if (empty($files)) die(json_encode(['status'=>'error', 'msg'=>'Brak plików.']));
    
    $localTempDir = __DIR__ . '/data/yt_temp';
    @mkdir($localTempDir, 0777, true);
    $uniq = uniqid();
    
    $shPath = $localTempDir . '/unpack_' . $uniq . '.sh';
    
    $sh = "#!/bin/bash\n";
    foreach($files as $file) {
        $fullPath = $targetDir . '/' . basename($file);
        $extractDir = $localTempDir . '/dir_' . $uniq;
        $archiveName = pathinfo(basename($file), PATHINFO_FILENAME);
        $finalDir = $targetDir . '/' . preg_replace('/[^A-Za-z0-9_\-\.]/', '_', $archiveName);
        
        $sh .= "mkdir -p ".escapeshellarg($extractDir)."\n";
        if (strtolower(pathinfo($fullPath, PATHINFO_EXTENSION)) == 'zip') 
            $sh .= "unzip -o ".escapeshellarg($fullPath)." -d ".escapeshellarg($extractDir)." >/dev/null 2>&1\n";
        else 
            $sh .= "unrar x -y -o+ ".escapeshellarg($fullPath)." ".escapeshellarg($extractDir)."/ >/dev/null 2>&1\n";
            
        $sh .= "\\cp -rf ".escapeshellarg($extractDir)."/* ".escapeshellarg($finalDir)."/ >/dev/null 2>&1\n";
        $sh .= "rm -rf ".escapeshellarg($extractDir)."\n";
    }
    // POPRAWKA: Użycie systemowego czyściciela
    $sh .= "( sleep 600 && sudo -n /usr/local/bin/clean_vfs.sh ) &\n";
    $sh .= "rm -f \"\$0\"";
    
    file_put_contents($shPath, $sh);
    chmod($shPath, 0777);
    exec("nohup bash ".escapeshellarg($shPath)." >/dev/null 2>&1 < /dev/null &");
    
    echo json_encode(['status'=>'ok', 'msg'=>'Rozpoczęto rozpakowywanie w tle. Pliki pojawią się w folderze po odświeżeniu za kilka chwil.']);
}
elseif ($action === 'ytdlp') {
    $url = $_POST['url'] ?? '';
    if(empty($url)) die(json_encode(['status'=>'error', 'msg'=>'Pusty link.']));
    
    if (strpos($url, 'watch?v=') !== false || strpos($url, 'youtu.be/') !== false || strpos($url, '/shorts/') !== false) {
        $playlistArg = "--no-playlist";
    } else {
        $playlistArg = "--yes-playlist"; 
    }

    $localTempDir = __DIR__ . '/data/yt_temp';
    if (!is_dir($localTempDir)) { mkdir($localTempDir, 0777, true); chmod($localTempDir, 0777); }
    
    $safeTargetDir = escapeshellarg($targetDir);
    $safeTempDir = escapeshellarg($localTempDir);
    $outputTemplate = escapeshellarg('%(title)s.%(ext)s');
    $safeUrl = escapeshellarg($url);
    
    $logFileBase = __DIR__ . '/data/yt.log';
    if (!file_exists($logFileBase)) { touch($logFileBase); chmod($logFileBase, 0666); }
    $logFile = escapeshellarg($logFileBase);
    
    $cookiesFile = __DIR__ . '/data/cookies.txt';
    $cookiesArg = file_exists($cookiesFile) ? "--cookies " . escapeshellarg($cookiesFile) : "";
    
    $cacheDir = __DIR__ . '/data/yt_cache';
    if (!is_dir($cacheDir)) { mkdir($cacheDir, 0777, true); }
    $cacheArg = "--cache-dir " . escapeshellarg($cacheDir);
    
    $ytCmd = "sudo -n /usr/local/bin/yt-dlp --js-runtimes deno:/usr/local/bin/deno --remote-components ejs:github $cacheArg $cookiesArg --ffmpeg-location /usr/bin/ffmpeg -P temp:$safeTempDir -P home:$safeTargetDir -f 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best' -o $outputTemplate $playlistArg --no-playlist-reverse --ignore-errors $safeUrl";

    // POPRAWKA: Skrypt używa praw roota do wyczyszczenia folderu tymczasowego yt_temp na wypadek braku praw zapisu, a opóźnienie 10-minutowe opiera o stworzony skrypt VFS.
    $fullScript = "echo '=== START ZADANIA YT ===' ; " . $ytCmd . " ; echo '[SYSTEM] Sprzatanie lokalnych smieci (yt_temp)...' ; sudo -n rm -rf $safeTempDir/* 2>/dev/null ; echo '[SYSTEM] Odliczam 10 minut do wyczyszczenia chmury (VFS Cache)...' ; sleep 600 ; sudo -n /usr/local/bin/clean_vfs.sh ; echo '[SYSTEM] Czysto!'";

    $cmd = "nohup bash -c " . escapeshellarg($fullScript) . " >> $logFile 2>&1 &";
    exec($cmd);
    
    echo json_encode(['status'=>'ok', 'msg'=>'Pobieranie uruchomione (Tryb Ochrony Pamięci)! Zobacz Status YT.']);
}
elseif ($action === 'yt_log') {
    $logFile = __DIR__ . '/data/yt.log';
    if(!file_exists($logFile)) die(json_encode(['status'=>'ok', 'log'=>'Brak pliku logów. Pobieranie jeszcze nie ruszyło.']));
    $log = shell_exec("tail -n 50 " . escapeshellarg($logFile));
    echo json_encode(['status'=>'ok', 'log'=>$log]);
}
elseif ($action === 'yt_log_clear') {
    $logFile = __DIR__ . '/data/yt.log';
    if(file_exists($logFile)) unlink($logFile);
    echo json_encode(['status'=>'ok']);
}
