<?php
setlocale(LC_CTYPE, "pl_PL.UTF-8", "en_US.UTF-8", "C.UTF-8");
require_once 'functions.php';
checkAuth();
$cfg = cfg();
$isAdmin = ($_SESSION['role'] === 'admin');
$folderKey = $_GET['folder'] ?? '';
$subPath = sanitizePath($_GET['path'] ?? '');
$sort = $_GET['sort'] ?? 'name_asc';

if(!isset($cfg['allowedFolders'][$folderKey])) die('Odmowa dostępu.');
$items = listMegaFolder($cfg['allowedFolders'][$folderKey], $subPath, $sort);

$pathParts = empty($subPath) ? [] : explode('/', $subPath);
$breadcrumbsHtml = "<div class='breadcrumbs' style='display:flex; flex-wrap:wrap; align-items:center; gap:8px; margin:0 0 0 15px; font-size:1.1em; font-weight:bold;'>";
$breadcrumbsHtml .= "<a href='folder.php?folder=" . urlencode($folderKey) . "' style='color:#333; text-decoration:none;'>&#128193; " . htmlspecialchars($folderKey) . "</a>";

$currentCumulativePath = "";
foreach($pathParts as $part) {
    if(empty($part)) continue;
    $currentCumulativePath .= (empty($currentCumulativePath) ? "" : "/") . $part;
    $breadcrumbsHtml .= "<span style='color:#888;'>/</span>";
    $breadcrumbsHtml .= "<a href='folder.php?folder=" . urlencode($folderKey) . "&path=" . urlencode($currentCumulativePath) . "' style='color:#333; text-decoration:none;'>" . htmlspecialchars($part) . "</a>";
}
$breadcrumbsHtml .= "</div>";

$backLink = empty($subPath) ? 'index.php' : 'folder.php?folder=' . urlencode($folderKey) . '&path=' . urlencode(dirname($subPath));

$supportedImages = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
$supportedVideos = ['mp4', 'webm']; 
$externalVideos = ['mkv', 'avi', 'ts', 'mts']; 
$supportedAudio = ['mp3', 'wav', 'ogg', 'oga', 'flac', 'm4a', 'aac'];
$supportedDocs = ['pdf', 'txt', 'json', 'xml', 'csv', 'html', 'css', 'js', 'svg'];

require 'header.php';
?>

<style>
    .breadcrumbs a:hover { color: #007bff !important; text-decoration: underline !important; }
</style>

<div class="path-header" style="justify-content: space-between; flex-wrap: wrap; gap: 15px;">
    <div style="display:flex; align-items:center;">
        <a href="<?=htmlspecialchars($backLink)?>" class="btn btn-gray" style="margin-bottom:0;">&laquo; Wr&#243;&#263;</a>
        <?=$breadcrumbsHtml?>
    </div>
    
    <div style="display:flex; align-items:center; gap: 5px; flex-wrap: wrap;">
        <select onchange="window.location.href=this.value" class="sort-select">
            <?php
            $baseUrl = "?folder=" . urlencode($folderKey) . "&path=" . urlencode($subPath) . "&sort=";
            $options = ['name_asc' => '&#128244; Nazwa (A-Z)', 'name_desc' => '&#128244; Nazwa (Z-A)', 'type_asc' => '&#128194; Typ (A-Z)', 'type_desc' => '&#128194; Typ (Z-A)', 'date_desc' => '&#128197; Najnowsze', 'date_asc' => '&#128197; Najstarsze', 'size_desc' => '&#9878; Najwi&#281;ksze', 'size_asc' => '&#9878; Najmniejsze'];
            foreach($options as $k => $v) { $sel = ($sort === $k) ? 'selected' : ''; echo "<option value=\"$baseUrl$k\" $sel>$v</option>"; }
            ?>
        </select>
        
        <?php if($isAdmin): ?>
            <button onclick="adminMkdir()" class="btn btn-gray" style="margin:0;">&#128193; Nowy Folder</button>
            <button onclick="openYtDlpModal()" class="btn btn-orange" style="margin:0;">&#9729; Z linku (YT)</button>
            <button onclick="adminYtLog()" class="btn btn-dark" style="margin:0;">&#128221; Status YT</button>
            <button onclick="adminConvertStatus()" class="btn btn-dark" style="margin:0;">&#127916; Status konwersji</button>
            <button onclick="adminDiskStatus()" class="btn btn-dark" style="margin:0;">&#128190; Miejsce</button>
            <button id="btnUploadCookies" class="btn btn-gray" style="margin:0; background:#6c757d; border-color:#5c636a; color:#fff;">&#127850; Cookies</button>
            
            <div style="display:none;">
                <button id="btnUpload"></button>
                <input type="file" id="fileUploader">
            </div>

            <button onclick="document.getElementById('fileUploaderLive').click();" id="btnUploadLive" class="btn btn-green" style="margin:0;">&#128228; Wgraj</button>
            <input type="file" id="fileUploaderLive" multiple style="display:none;" data-folder="<?=htmlspecialchars($folderKey)?>" data-path="<?=htmlspecialchars($subPath)?>">
            
            <input type="file" id="cookiesUploader" accept=".txt" style="display:none;">
        <?php endif; ?>
    </div>
</div>

<form id="multiForm" method="POST" action="zip.php">
<input type="hidden" name="folder" value="<?=htmlspecialchars($folderKey)?>">
<input type="hidden" name="path" value="<?=htmlspecialchars($subPath)?>">
<input type="hidden" name="csrf_token" value="<?=htmlspecialchars(csrfToken(), ENT_QUOTES)?>">

<table class="file-list">
<thead>
    <tr>
        <th style="width: 40px;"><input type="checkbox" id="checkAll"></th>
        <th>Plik / Folder</th>
        <th>Rozmiar</th>
        <th>Pobrania</th>
        <th style="text-align: right;">Akcje</th>
    </tr>
</thead>
<tbody>

<?php foreach($items['folders'] as $folder): ?>
<?php $nextPath = empty($subPath) ? $folder['name'] : $subPath . '/' . $folder['name']; ?>
<tr class="file-row">
    <td><input type="checkbox" name="files[]" value="<?=htmlspecialchars($folder['name'])?>" class="chk-item" data-is-video="0"></td>
    <td class="icon-cell">
        <a href="folder.php?folder=<?=urlencode($folderKey)?>&path=<?=urlencode($nextPath)?>" class="item-link">
            <span class="item-icon">&#128193;</span>
            <span class="item-name"><strong><?=htmlspecialchars($folder['name'])?></strong></span>
        </a>
    </td>
    <td class="meta-data">-</td>
    <td class="meta-data">-</td>
    <td class="actions-cell">
        <a href="folder.php?folder=<?=urlencode($folderKey)?>&path=<?=urlencode($nextPath)?>" class="btn btn-gray">Wejd&#378;</a>
        <?php if($isAdmin): ?>
            <button type="button" onclick='adminAction("rename", <?=json_encode($folder['name'], JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE)?>)' class="btn btn-dark">&#9999;</button>
            <button type="button" onclick='adminAction("delete", <?=json_encode($folder['name'], JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE)?>)' class="btn" style="background:#dc3545;">&#128465;</button>
        <?php endif; ?>
    </td>
</tr>
<?php endforeach; ?>

<?php foreach($items['files'] as $file): ?>
<?php 
  $fileExt = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
  $isImage = in_array($fileExt, $supportedImages); 
  $isVideo = in_array($fileExt, $supportedVideos);
  $isExtVid = in_array($fileExt, $externalVideos); 
  $isAudio = in_array($fileExt, $supportedAudio);
  $isDoc = in_array($fileExt, $supportedDocs); 
  
  $isAnyVideo = ($isVideo || $isExtVid); 
  $canView = ($isImage || $isAudio || $isDoc); 
  
  $dlParams = "folder=".urlencode($folderKey)."&path=".urlencode($subPath)."&file=".urlencode($file['name']);
  
  $iconSym = '&#128196;'; 
  if ($isAnyVideo) $iconSym = '&#127916;'; 
  elseif ($isAudio) $iconSym = '&#127925;'; 
  elseif ($isDoc) $iconSym = '&#128214;'; 
?>
<tr class="file-row">
    <td><input type="checkbox" name="files[]" value="<?=htmlspecialchars($file['name'])?>" class="chk-item" data-is-video="<?=$isAnyVideo ? '1' : '0'?>"></td>
    <td class="icon-cell">
        <?php if ($isImage): ?>
            <a href="view.php?<?=$dlParams?>" class="item-link glightbox" data-gallery="folder-gallery" data-title="<?=htmlspecialchars($file['name'])?>">
                <img src="thumb.php?<?=$dlParams?>" class="item-thumb" loading="lazy" decoding="async" alt="thumb"><span class="item-name"><?=htmlspecialchars($file['name'])?></span>
            </a>
        <?php elseif ($isAnyVideo): ?>
            <a href="play.php?<?=$dlParams?>" target="_blank" class="item-link">
                <img src="video_thumb.php?<?=$dlParams?>" data-thumb-url="video_thumb.php?<?=$dlParams?>" class="item-thumb video-thumb" loading="lazy" decoding="async" alt="Miniatura filmu"><span class="item-name"><?=htmlspecialchars($file['name'])?></span>
            </a>
        <?php elseif ($canView): ?>
            <a href="view.php?<?=$dlParams?>" target="_blank" class="item-link"><span class="item-icon"><?=$iconSym?></span><span class="item-name"><?=htmlspecialchars($file['name'])?></span></a>
        <?php else: ?>
            <a href="download.php?<?=$dlParams?>" target="_blank" class="item-link"><span class="item-icon"><?=$iconSym?></span><span class="item-name"><?=htmlspecialchars($file['name'])?></span></a>
        <?php endif; ?>
    </td>
    <td class="meta-data"><?=htmlspecialchars($file['size'])?></td>
    <td><span class="badge"><?=htmlspecialchars($file['downloads'])?></span></td>
    <td class="actions-cell">
        <?php if ($canView): ?><a href="view.php?<?=$dlParams?>" target="_blank" class="btn btn-green">Zobacz</a><?php endif; ?>
        
        <?php if ($isAnyVideo): ?>
            <a href="play.php?<?=$dlParams?>" target="_blank" class="btn btn-green">&#127916; Zobacz</a>
        <?php endif; ?>
        
        <a href="download.php?<?=$dlParams?>" class="btn btn-blue">Pobierz</a>
        
        <?php if($isAdmin): ?>
            <button type="button" onclick='adminAction("rename", <?=json_encode($file['name'], JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE)?>)' class="btn btn-dark">&#9999;</button>
            <button type="button" onclick='adminAction("delete", <?=json_encode($file['name'], JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE)?>)' class="btn" style="background:#dc3545;">&#128465;</button>
        <?php else: ?>
            <?php if (!$isAnyVideo): ?>
                <button type="button" onclick='shareFile(<?=json_encode(urlencode($folderKey), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE)?>, <?=json_encode(urlencode($subPath), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE)?>, <?=json_encode(urlencode($file['name']), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE)?>)' class="btn btn-dark">&#128279;</button>
            <?php endif; ?>
        <?php endif; ?>
    </td>
</tr>
<?php endforeach; ?>
</tbody>
</table>

<div id="multiActionBar" style="display:none; position:fixed; bottom:0; left:0; width:100%; background:rgba(30,30,30,0.95); padding:15px; text-align:center; box-shadow:0 -5px 15px rgba(0,0,0,0.3); z-index:9000; backdrop-filter: blur(10px);">
    <span id="selCount" style="color:#fff; margin-right:20px; font-weight:bold;">Wybrano: 0</span>
    <button type="button" onclick="document.getElementById('multiForm').submit();" class="btn btn-blue" style="font-size:15px; padding:10px 20px;">&#128230; Pobierz ZIP w locie</button>
    <?php if($isAdmin): ?>
        <button type="button" onclick="openMoveCopyModal('move')" class="btn btn-orange" style="font-size:15px; padding:10px 20px;">&#10145;&#65039; Przenie&#347;</button>
        <button type="button" onclick="openMoveCopyModal('copy')" class="btn btn-green" style="font-size:15px; padding:10px 20px;">&#128196; Kopiuj</button>
        <button type="button" onclick="executeConvert()" class="btn btn-orange" style="font-size:15px; padding:10px 20px;">&#127916; Konwertuj</button>
        <button type="button" onclick="executeMultiDelete()" class="btn" style="background:#dc3545; font-size:15px; padding:10px 20px; color:#fff;">&#128465; Usu&#324;</button>
        <button type="button" id="btn-multi-unpack" onclick="executeUnpack()" class="btn btn-warning" style="font-size:15px; padding:10px 20px; color:#000; margin-left:5px;">&#128230; Rozpakuj</button>
    <?php endif; ?>
</div>
</form>

<?php if($isAdmin): ?>
<div id="mcModal" class="modal-overlay" style="display:none;">
    <div class="modal-box">
        <h3 style="margin-top:0;" id="mcTitle">Wybierz miejsce</h3>
        <label style="font-size:14px; color:#bbb;">G&#322;&#243;wny folder:</label>
        <select id="mcDestFolder" class="sort-select" style="width:100%; margin:5px 0 15px 0; padding:10px;">
            <?php foreach($cfg['allowedFolders'] as $k => $v) echo "<option value='$k'>$k</option>"; ?>
        </select>
        <label style="font-size:14px; color:#bbb;">Podkatalog (opcjonalnie):</label>
        <input type="text" id="mcDestPath" placeholder="np. Nowe/Zdjecia" style="width:100%; box-sizing:border-box; margin:5px 0 20px 0; padding:10px; border-radius:6px; border:1px solid #444; background:#222; color:#fff; outline:none;">
        <input type="hidden" id="mcActionType">
        <div style="display:flex; gap:10px;">
            <button onclick="executeMoveCopy()" class="btn btn-blue" style="flex:1; padding:12px;">Potwierd&#378;</button>
            <button onclick="document.getElementById('mcModal').style.display='none'" class="btn btn-gray" style="flex:1; padding:12px;">Anuluj</button>
        </div>
    </div>
</div>

<div id="ytLogModal" class="modal-overlay" style="display:none; z-index:9998;">
    <div class="modal-box" style="max-width:800px; width:95%;">
        <h3 style="margin-top:0; color:#007bff;">&#9729; Status zadania w tle (yt-dlp)</h3>
        <div id="ytLogContent" style="background:#000; color:#0f0; padding:15px; height:350px; overflow-y:auto; font-size:13px; font-family:monospace; border-radius:6px; border:1px solid #333; text-align:left; white-space:pre-wrap; word-wrap:break-word;">
            &#321;adowanie...
        </div>
        <div style="display:flex; gap:10px; margin-top:15px;">
            <button onclick="adminYtLog()" class="btn btn-blue" style="flex:1;">&#128260; Odśwież Log</button>
            <button onclick="adminYtLogClear()" class="btn" style="background:#dc3545;">&#128465; Wyczyść</button>
            <button onclick="document.getElementById('ytLogModal').style.display='none'" class="btn btn-gray" style="flex:1;">Zamknij</button>
        </div>
    </div>
</div>

<div id="convertStatusModal" class="modal-overlay" style="display:none; z-index:9998;">
    <div class="modal-box" style="max-width:850px; width:95%;">
        <h3 style="margin-top:0; color:#fd7e14;">&#127916; Status konwersji do MP4</h3>
        <div id="convertStatusContent" style="background:#000; color:#eee; padding:15px; min-height:180px; max-height:420px; overflow-y:auto; font-size:13px; font-family:monospace; border-radius:6px; border:1px solid #333; text-align:left; white-space:pre-wrap; overflow-wrap:anywhere;">
            Ładowanie...
        </div>
        <div style="display:flex; gap:10px; margin-top:15px; flex-wrap:wrap;">
            <button onclick="loadConvertStatus()" class="btn btn-blue" style="flex:1;">&#128260; Odśwież</button>
            <button onclick="closeConvertStatus()" class="btn btn-gray" style="flex:1;">Zamknij</button>
        </div>
    </div>
</div>

<div id="diskStatusModal" class="modal-overlay" style="display:none; z-index:9998;">
    <div class="modal-box" style="max-width:700px; width:95%;">
        <h3 style="margin-top:0; color:#17a2b8;">&#128190; Monitor miejsca na dysku</h3>
        <div id="diskStatusContent" style="background:#000; color:#eee; padding:15px; min-height:180px; max-height:420px; overflow-y:auto; font-size:13px; font-family:monospace; border-radius:6px; border:1px solid #333; text-align:left; white-space:pre-wrap; overflow-wrap:anywhere;">
            Ładowanie...
        </div>
        <div style="display:flex; gap:10px; margin-top:15px; flex-wrap:wrap;">
            <button onclick="loadDiskStatus()" class="btn btn-blue" style="flex:1;">&#128260; Odśwież</button>
            <button onclick="closeDiskStatus()" class="btn btn-gray" style="flex:1;">Zamknij</button>
        </div>
    </div>
</div>

<div id="unpackTerminalModal" class="modal-overlay" style="display:none; z-index:9999;">
    <div class="modal-box" style="max-width:800px; width:95%;">
        <h3 style="margin-top:0; color:#007bff;">&#128187; Terminal Rozpakowywania [LIVE]</h3>
        <div id="unpackLogContent" style="background:#000; color:#0f0; padding:15px; height:350px; overflow-y:auto; font-size:13px; font-family:monospace; border-radius:6px; border:1px solid #333; text-align:left; word-wrap:break-word;">
        </div>
        <div style="display:flex; gap:10px; margin-top:15px;">
            <button onclick="window.location.reload();" class="btn btn-green" style="flex:1;">Odśwież folder</button>
            <button onclick="document.getElementById('unpackTerminalModal').style.display='none'" class="btn btn-gray" style="flex:1;">Zamknij Terminal</button>
        </div>
    </div>
</div>

<div id="ytDlpModal" class="modal-overlay" style="display:none; z-index:9999;">
    <div class="modal-box" style="max-width:600px; width:95%;">
        <h3 style="margin-top:0; color:#fd7e14;">&#9729; Pobierz masowo z linków (YT-DLP)</h3>
        <p style="font-size:13px; color:#bbb; text-align:left; margin-bottom:5px;">Wklej linki poniżej (każdy w nowej linii). Możesz wkleić kilkanaście linków naraz:</p>
        <textarea id="ytLinksInput" rows="6" style="width:100%; box-sizing:border-box; margin-bottom:15px; padding:10px; border-radius:6px; border:1px solid #444; background:#222; color:#fff; outline:none; font-family:monospace; resize:vertical;" placeholder="https://youtube.com/watch?v=...&#10;https://youtube.com/watch?v=..."></textarea>
        <div style="display:flex; gap:10px;">
            <button onclick="executeYtDlp()" id="ytDlpSubmitBtn" class="btn btn-orange" style="flex:1; padding:12px;">Pobierz wszystko w tle</button>
            <button onclick="document.getElementById('ytDlpModal').style.display='none'" class="btn btn-gray" style="flex:1; padding:12px;">Anuluj</button>
        </div>
    </div>
</div>
<?php endif; ?>

<script>
// --- NOWA FUNKCJA GENEROWANIA LINKÓW (Zamiast starego okienka) ---
window.shareFile = function(folderEnc, pathEnc, fileEnc) {
    let folder = decodeURIComponent(folderEnc.replace(/\+/g, '%20'));
    let path = decodeURIComponent(pathEnc.replace(/\+/g, '%20'));
    let file = decodeURIComponent(fileEnc.replace(/\+/g, '%20'));
    
    let formData = new FormData();
    formData.append('action', 'share');
    formData.append('folder', folder);
    formData.append('path', path);
    formData.append('file', file);

    fetch('admin_ajax.php', { method: 'POST', body: formData })
    .then(res => res.json())
    .then(data => {
        if(data.status === 'ok') {
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(data.link).then(() => alert('Gotowe! Skopiowano link 24h:\n' + data.link));
            } else {
                prompt('Twój link 24h (skopiuj go):', data.link);
            }
        } else {
            alert('Błąd: ' + (data.msg || 'Odmowa dostępu'));
        }
    }).catch(e => alert('Błąd sieci / Przerwane połączenie'));
};
// ------------------------------------------------------------------

function openYtDlpModal() {
    let input = document.getElementById('ytLinksInput');
    if(input) input.value = '';
    document.getElementById('ytDlpModal').style.display = 'flex';
}

function executeYtDlp() {
    let links = document.getElementById('ytLinksInput').value.trim();
    if(!links) return alert('Wklej przynajmniej jeden link!');
    
    let btn = document.getElementById('ytDlpSubmitBtn');
    let originalText = btn.innerText;
    btn.innerText = 'Wysyłanie do tła...';
    btn.disabled = true;

    let params = new URLSearchParams(window.location.search);
    let formData = new FormData();
    formData.append('action', 'ytdlp');
    formData.append('folder', params.get('folder') || '');
    formData.append('path', params.get('path') || '');
    formData.append('url', links);

    fetch('admin_ajax.php', { method: 'POST', body: formData })
    .then(res => res.json())
    .then(data => {
        btn.innerText = originalText;
        btn.disabled = false;
        if(data.status === 'ok') {
            document.getElementById('ytDlpModal').style.display = 'none';
            document.getElementById('ytLinksInput').value = '';
            if(typeof adminYtLog === 'function') adminYtLog();
        } else {
            alert(data.msg || 'Wystąpił błąd.');
        }
    }).catch(e => {
        alert('Błąd sieci / Przerwane połączenie');
        btn.innerText = originalText;
        btn.disabled = false;
    });
}

function executeUnpack() {
    let files = [];
    let checkboxes = document.querySelectorAll('.chk-item:checked');
    for (let i = 0; i < checkboxes.length; i++) {
        let val = checkboxes[i].value;
        if(val && val !== 'on') files.push(val);
    }
    if(files.length === 0) return alert('Wybierz pliki do rozpakowania!');
    
    let hasArchive = false;
    for (let i = 0; i < files.length; i++) {
        let f = files[i].toLowerCase();
        if (f.endsWith('.zip') || f.endsWith('.rar')) hasArchive = true;
    }
    if(!hasArchive) return alert('\u017baden z zaznaczonych plik\u00f3w nie jest archiwum!');

    let modal = document.getElementById('unpackTerminalModal');
    let content = document.getElementById('unpackLogContent');
    if(!modal || !content) return alert('Błąd: Brak HTML terminala!');
    
    modal.style.display = 'flex';
    content.innerHTML = '<span style="color:yellow">[SYSTEM] Łączenie z jądrem serwera...</span><br>';
    
    let params = new URLSearchParams(window.location.search);
    let formData = new FormData();
    formData.append('folder', params.get('folder') || '');
    formData.append('path', params.get('path') || '');
    files.forEach(f => formData.append('files[]', f));

    fetch('unpack.php', {
        method: 'POST',
        body: formData
    }).then(async response => {
        const reader = response.body.getReader();
        const decoder = new TextDecoder('utf-8');
        content.innerHTML = '';
        
        while (true) {
            const { done, value } = await reader.read();
            if (value) {
                let text = decoder.decode(value, {stream: true});
                content.innerHTML += text.replace(/\n/g, '<br>');
                content.scrollTop = content.scrollHeight;
            }
            if (done) break;
        }
    }).catch(err => {
        content.innerHTML += '<br><span style="color:red">[BŁĄD SIECI] Połączenie z terminalem zerwane.</span>';
    });
}

try {
    document.addEventListener("DOMContentLoaded", function() {
        var liveInput = document.getElementById('fileUploaderLive');
        var liveBtn = document.getElementById('btnUploadLive');
        
        if(liveInput && liveBtn) {
            liveInput.addEventListener('change', function() {
                var files = this.files;
                if (files.length === 0) return;

                var originalText = liveBtn.innerHTML; 
                var formData = new FormData();
                
                formData.append('action', 'upload');
                formData.append('folder', this.getAttribute('data-folder'));
                formData.append('path', this.getAttribute('data-path'));
                
                for (var i = 0; i < files.length; i++) {
                    formData.append('files[]', files[i]);
                }

                var xhr = new XMLHttpRequest();
                xhr.open('POST', 'admin_ajax.php', true);

                xhr.upload.addEventListener("progress", function(evt) {
                    if (evt.lengthComputable) {
                        var percentComplete = Math.round((evt.loaded / evt.total) * 100);
                        liveBtn.innerHTML = '&#8987; Wgrywanie... ' + percentComplete + '%';
                    }
                }, false);

                xhr.onload = function() {
                    if (xhr.status === 200) {
                        try {
                            var data = JSON.parse(xhr.responseText);
                            if(data.status === 'ok') {
                                liveBtn.innerHTML = '&#10004; Zapisano!';
                                setTimeout(function() { window.location.reload(); }, 1500);
                            } else {
                                alert(data.msg);
                                liveBtn.innerHTML = originalText;
                                liveBtn.disabled = false;
                            }
                        } catch(e) {
                            alert('Błąd serwera (nieprawidłowa odpowiedź).');
                            liveBtn.innerHTML = originalText;
                            liveBtn.disabled = false;
                        }
                    } else {
                        alert('Błąd połączenia z serwerem!');
                        liveBtn.innerHTML = originalText;
                        liveBtn.disabled = false;
                    }
                };

                xhr.onerror = function() {
                    alert('Błąd sieci / Przerwane połączenie!');
                    liveBtn.innerHTML = originalText;
                    liveBtn.disabled = false;
                };

                liveBtn.disabled = true;
                liveBtn.innerHTML = 'Wgrywanie... 0%';
                xhr.send(formData);

                this.value = '';
            });
        }
    });
} catch(e) {}
</script>
</div>
</body></html>
