<?php
setlocale(LC_CTYPE, "pl_PL.UTF-8", "en_US.UTF-8", "C.UTF-8");
require_once 'functions.php';

$action = $_POST['action'] ?? '';

// WYJĄTEK: Zapis i natychmiastowy odczyt czasu działają na Ciasteczku (omijają blokadę F5)
if ($action !== 'save_progress' && $action !== 'get_progress') {
    checkAuth();
}

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

if ($action !== 'save_progress' && $action !== 'get_progress') {
    if (!isset($cfg['allowedFolders'][$folderKey])) die(json_encode(['status'=>'error']));
}

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

if (isset($_SESSION['role']) && $_SESSION['role'] !== 'admin' && !in_array($action, ['share', 'save_progress', 'get_progress'])) {
    die(json_encode(['status'=>'error', 'msg'=>'Odmowa dostępu!']));
}

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;
        }
        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";
    }
    $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') {
    $urlsRaw = $_POST['url'] ?? '';
    $urlsArray = preg_split('/[\r\n\s,]+/', trim($urlsRaw), -1, PREG_SPLIT_NO_EMPTY);
    
    if(empty($urlsArray)) die(json_encode(['status'=>'error', 'msg'=>'Brak poprawnych linków.']));
    
    $localTempDir = __DIR__ . '/data/yt_temp';
    if (!is_dir($localTempDir)) { mkdir($localTempDir, 0777, true); chmod($localTempDir, 0777); }
    
    $safeTargetDir = escapeshellarg($targetDir);
    $safeTempDir = escapeshellarg($localTempDir);
    
    $logFileBase = __DIR__ . '/data/yt.log';
    if (!file_exists($logFileBase)) { touch($logFileBase); chmod($logFileBase, 0666); }
    
    $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);
    
    $scriptContent  = "#!/bin/bash\n";
    $scriptContent .= "exec >> " . escapeshellarg($logFileBase) . " 2>&1\n";
    $scriptContent .= "echo '=== START MASOWEGO POBIERANIA Z LINKOW ==='\n";

    foreach ($urlsArray as $u) {
        $safeUrl = escapeshellarg($u);
        
        $pathInfo = pathinfo(parse_url($u, PHP_URL_PATH));
        $ext = isset($pathInfo['extension']) ? strtolower($pathInfo['extension']) : '';
        $isDirectFile = in_array($ext, ['zip', 'rar', 'txt', 'py', 'jpg', 'png', 'pdf', 'mp4', 'avi', 'mkv', 'iso', 'exe', 'bin', 'tar', 'gz']);
        $isYouTubeOrSimilar = (strpos($u, 'youtube.com') !== false || strpos($u, 'youtu.be') !== false || strpos($u, 'vimeo') !== false);
        
        $scriptContent .= "echo '===================================='\n";
        $scriptContent .= "echo 'Przetwarzanie: $safeUrl'\n";
        
        if ($isDirectFile && !$isYouTubeOrSimilar) {
            $filenameExtracted = escapeshellarg(basename(parse_url($u, PHP_URL_PATH)));
            $scriptContent .= "echo '[METODA] Serwer zewnetrzny. Uzywam bezposredniego pobierania (wget).'\n";
            $scriptContent .= "wget -q --show-progress -O $safeTempDir/$filenameExtracted $safeUrl\n";
            $scriptContent .= "echo '[Przenoszenie do chmury...]'\n";
            $scriptContent .= "mv -f $safeTempDir/$filenameExtracted $safeTargetDir/ 2>/dev/null\n";
        } else {
            $playlistArg = (strpos($u, 'watch?v=') === false && (strpos($u, 'playlist') !== false || strpos($u, '&list=') !== false)) ? "--yes-playlist" : "--no-playlist";
            $outputTemplate = escapeshellarg('%(title)s.%(ext)s');
            
            $scriptContent .= "echo '[METODA] Strumien wideo. Uzywam yt-dlp.'\n";
            $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";
            $scriptContent .= $ytCmd . "\n";
        }
        $scriptContent .= "echo '[ZAKONCZONO]: $safeUrl'\n";
    }

    $scriptContent .= "echo '===================================='\n";
    $scriptContent .= "echo '[SYSTEM] Sprzatanie lokalnych smieci (yt_temp)...'\n";
    $scriptContent .= "rm -rf $safeTempDir/* 2>/dev/null\n";
    $scriptContent .= "echo '[SYSTEM] Odliczam 10 minut do wyczyszczenia chmury (VFS Cache)...'\n";
    $scriptContent .= "sleep 600\n";
    $scriptContent .= "sudo -n /usr/local/bin/clean_vfs.sh\n";
    $scriptContent .= "echo '[SYSTEM] Czysto!'\n";
    $scriptContent .= "rm -f \"\$0\"\n";

    $uniqId = uniqid();
    $shFile = __DIR__ . "/data/mass_download_{$uniqId}.sh";
    file_put_contents($shFile, $scriptContent);
    chmod($shFile, 0777);
    
    $cmd = "nohup bash " . escapeshellarg($shFile) . " >/dev/null 2>&1 < /dev/null &";
    exec($cmd);
    
    echo json_encode(['status'=>'ok', 'msg'=>"Pobieranie uruchomione pomyślnie."]);
}
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']);
}
elseif ($action === 'share') {
    $fileName = $_POST['file'] ?? '';
    $fullPath = $targetDir . '/' . basename($fileName);
    
    if (!file_exists($fullPath)) die(json_encode(['status'=>'error', 'msg'=>'Plik nie istnieje.']));
    
    $hash = bin2hex(random_bytes(6));
    $db = getDb();
    $db['shares'][$hash] = [
        'folder' => $folderKey,
        'path' => $subPath,
        'file' => $fileName,
        'expires' => time() + (24 * 3600)
    ];
    saveDb($db);
    
    $scheme = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https" : "http";
    $hostPath = $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/') . "/share.php?h=" . $hash;
    $fullUrl = $scheme . "://" . $hostPath;
    
    echo json_encode(['status'=>'ok', 'link'=>$fullUrl]);
}

// --- AKCJA ZAPISU HISTORII OGLĄDANIA ---
elseif ($action === 'save_progress') {
    $file = $_POST['file'] ?? '';
    $time = (float)($_POST['time'] ?? 0);
    $pin = $_COOKIE['user_pin'] ?? 'user';

    $progFile = __DIR__ . '/data/progress.json';
    $prog = file_exists($progFile) ? json_decode(file_get_contents($progFile), true) : [];
    if(!$prog) $prog = [];
    if (!isset($prog[$pin])) $prog[$pin] = [];

    $prog[$pin][$file] = ['time' => $time, 'ts' => time()];
    file_put_contents($progFile, json_encode($prog, JSON_PRETTY_PRINT), LOCK_EX);
    echo json_encode(['status'=>'ok']);
    exit;
}

// --- AKCJA POBRANIA CZASU (OMINIĘCIE CACHE PRZEGLĄDARKI) ---
elseif ($action === 'get_progress') {
    $file = $_POST['file'] ?? '';
    $pin = $_COOKIE['user_pin'] ?? 'user';
    
    $progFile = __DIR__ . '/data/progress.json';
    $prog = file_exists($progFile) ? json_decode(file_get_contents($progFile), true) : [];
    $time = isset($prog[$pin][$file]) ? (float)$prog[$pin][$file]['time'] : 0;
    
    echo json_encode(['status'=>'ok', 'time'=>$time]);
    exit;
}
