<?php
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/google_drive_helper.php';
requireLogin();

$gdHelper = new GoogleDriveHelper($pdo);

if (!$gdHelper->isAuthenticated()) {
    header("Location: google_drive_auth.php");
    exit;
}

$view_mode = isset($_COOKIE['gd_view']) ? $_COOKIE['gd_view'] : 'grid';
$current_folder = isset($_GET['folder_id']) ? $_GET['folder_id'] : null;
$success = isset($_GET['success']) ? $_GET['success'] : '';
$error = isset($_GET['error']) ? $_GET['error'] : '';

// AJAX 請求：回傳 JSON 而不渲染整個頁面
$ajax = isset($_GET['ajax']) && $_GET['ajax'] === '1';
if ($ajax) {
    header('Content-Type: application/json');
    $ajaxFolder = $_GET['folder_id'] ?? null;
    if ($ajaxFolder) {
        $ajaxContents = $gdHelper->listFolderContents($ajaxFolder);
        $ajaxBreadcrumbs = $gdHelper->getFolderPath($ajaxFolder);
        echo json_encode([
            'success' => true,
            'contents' => $ajaxContents,
            'breadcrumbs' => $ajaxBreadcrumbs
        ]);
    } else {
        echo json_encode(['success' => false, 'error' => 'No folder specified']);
    }
    exit;
}

// 取得應用程式根資料夾（用於上傳檔案時的預設位置）
$app_folder_id = $gdHelper->getOrCreateAppFolder();
if (!$current_folder) {
    $current_folder = 'root'; // 預設為「我的雲端硬碟」根目錄
}

// 處理新增資料夾
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'new_folder') {
    $folder_name = trim($_POST['folder_name']);
    $parent_id = $_POST['parent_id'];
    if ($folder_name && $parent_id) {
        $result = $gdHelper->createFolder($folder_name, $parent_id);
        if ($result) {
            header("Location: google_drive_docs.php?folder_id=$parent_id&success=資料夾已創建");
        } else {
            header("Location: google_drive_docs.php?folder_id=$parent_id&error=創建失敗");
        }
        exit;
    }
}

// 處理上傳檔案
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'upload') {
    $parent_id = $_POST['parent_id'];
    $uploaded = 0;
    if (isset($_FILES['files']) && is_array($_FILES['files']['name'])) {
        for ($i = 0; $i < count($_FILES['files']['name']); $i++) {
            if ($_FILES['files']['error'][$i] === UPLOAD_ERR_OK) {
                $result = $gdHelper->uploadFile(
                    $_FILES['files']['tmp_name'][$i],
                    $_FILES['files']['name'][$i],
                    $_FILES['files']['type'][$i] ?: 'application/octet-stream',
                    $parent_id
                );
                if ($result) $uploaded++;
            }
        }
    }
    if ($uploaded > 0) {
        header("Location: google_drive_docs.php?folder_id=$parent_id&success=已上傳 $uploaded 個檔案");
    } else {
        header("Location: google_drive_docs.php?folder_id=$parent_id&error=上傳失敗");
    }
    exit;
}

// 處理刪除
if (isset($_GET['delete_file'])) {
    $file_id = $_GET['delete_file'];
    $return_folder = $_GET['return_folder'] ?? $app_folder_id;
    $gdHelper->deleteFile($file_id);
    header("Location: google_drive_docs.php?folder_id=$return_folder&success=已刪除");
    exit;
}

// 取得當前資料夾內容（用於初始頁面渲染）
$initialContents = $gdHelper->listFolderContents($current_folder);
$initialBreadcrumbs = $gdHelper->getFolderPath($current_folder);
$initialFolders = $initialContents['folders'] ?? [];
$initialFiles = $initialContents['files'] ?? [];
$initialItems = array_merge(
    array_map(function($f) { $f['_isFolder'] = true; return $f; }, $initialFolders),
    array_map(function($f) { $f['_isFolder'] = false; return $f; }, $initialFiles)
);

include __DIR__ . '/../includes/header.php';
?>

<style>
    .gd-item:hover { background-color: #f8fafc; }
    .gd-item-selected { background-color: #eff6ff !important; border-color: #3b82f6 !important; }
    .sortable-ghost { opacity: 0.4; background-color: #dbeafe !important; }
    .drag-handle { cursor: grab; }
    .drag-handle:active { cursor: grabbing; }
</style>

<div class="mb-8 flex justify-between items-end">
    <div>
        <nav class="flex text-sm text-slate-400 mb-2">
            <a href="index.php" class="hover:text-blue-500">首頁</a>
            <span class="mx-2">/</span>
            <span class="text-slate-600 font-medium">Google Drive 雲端檔案</span>
        </nav>
        <h1 class="text-2xl font-bold text-slate-800 flex items-center gap-2">
            <i class="fab fa-google-drive text-blue-500"></i> 雲端檔案總管
            <span class="text-xs text-slate-400 font-mono font-normal bg-slate-100 px-2 py-0.5 rounded">即時同步</span>
        </h1>
    </div>
    <div class="flex gap-2">
        <button onclick="document.getElementById('new-folder-modal').classList.remove('hidden')" class="bg-slate-100 hover:bg-slate-200 text-slate-700 px-4 py-2 rounded-lg flex items-center gap-2 transition text-sm font-medium">
            <i class="fas fa-folder-plus"></i> 新增資料夾
        </button>
        <button onclick="document.getElementById('upload-modal').classList.remove('hidden')" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg flex items-center gap-2 transition text-sm font-medium shadow-sm">
            <i class="fas fa-upload"></i> 上傳檔案
        </button>
    </div>
</div>

<?php if ($success): ?>
    <div class="bg-green-50 text-green-600 p-4 rounded-lg mb-6 flex items-center"><i class="fas fa-check-circle mr-2"></i> <?php echo $success; ?></div>
<?php endif; ?>
<?php if ($error): ?>
    <div class="bg-red-50 text-red-600 p-4 rounded-lg mb-6 flex items-center"><i class="fas fa-exclamation-circle mr-2"></i> <?php echo $error; ?></div>
<?php endif; ?>

<div class="flex items-center gap-2 mb-6 text-sm bg-white p-3 rounded-xl border border-slate-100 shadow-sm">
    <a href="javascript:navigateTo('')" class="text-blue-600 hover:underline flex items-center gap-1"><i class="fas fa-home text-xs"></i> 根目錄</a>
    <span id="gd-breadcrumbs"><?php foreach ($initialBreadcrumbs as $bc): ?><i class="fas fa-chevron-right text-slate-300 text-xs"></i><a href="javascript:navigateTo('<?php echo $bc['id']; ?>')" class="text-blue-600 hover:underline"><?php echo htmlspecialchars($bc['name']); ?></a><?php endforeach; ?></span>
    <span class="flex-1"></span>
    <div id="gd-loading" class="hidden"><i class="fas fa-spinner fa-spin text-blue-500 mr-1"></i></div>
    <span id="gd-count" class="text-xs text-slate-400"><?php echo count($initialItems); ?> 個項目</span>
</div>

<!-- 檢視模式切換 -->
<div class="flex justify-end mb-4">
    <div class="flex border border-slate-200 rounded-lg overflow-hidden">
        <button onclick="setView('grid')" class="px-3 py-1.5 text-xs <?php echo $view_mode == 'grid' ? 'bg-blue-50 text-blue-600 font-medium' : 'text-slate-500 hover:bg-slate-50'; ?> border-r border-slate-200"><i class="fas fa-th-large"></i></button>
        <button onclick="setView('list')" class="px-3 py-1.5 text-xs <?php echo $view_mode == 'list' ? 'bg-blue-50 text-blue-600 font-medium' : 'text-slate-500 hover:bg-slate-50'; ?>"><i class="fas fa-list"></i></button>
    </div>
</div>

<div id="gd-content">
<?php if (empty($initialItems)): ?>
    <div class="text-center py-20 bg-white rounded-2xl border-2 border-dashed border-slate-200">
        <i class="fab fa-google-drive text-slate-300 text-6xl mb-4"></i>
        <p class="text-slate-500 mb-2">此資料夾暫無內容</p>
        <div class="flex justify-center gap-3">
            <button onclick="document.getElementById('new-folder-modal').classList.remove('hidden')" class="text-blue-600 hover:text-blue-800 text-sm font-medium">新增資料夾</button>
            <span class="text-slate-300">|</span>
            <button onclick="document.getElementById('upload-modal').classList.remove('hidden')" class="text-blue-600 hover:text-blue-800 text-sm font-medium">上傳檔案</button>
        </div>
    </div>
<?php elseif ($view_mode === 'grid'): ?>
    <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 xl:grid-cols-8 gap-4">
        <?php foreach ($initialItems as $item): ?>
        <div class="gd-item bg-white rounded-xl border border-slate-100 shadow-sm hover:shadow-md transition p-4 text-center cursor-pointer group relative" 
             onclick="<?php echo $item['_isFolder'] ? "navigateTo('{$item['id']}')" : "window.open('{$item['webViewLink']}','_blank')"; ?>">
            <div class="h-20 flex items-center justify-center mb-2">
                <?php if ($item['_isFolder']): ?>
                    <i class="fas fa-folder text-yellow-500 text-5xl"></i>
                <?php elseif (!empty($item['thumbnailLink'])): ?>
                    <img src="<?php echo $item['thumbnailLink']; ?>" class="h-full w-full object-cover rounded-lg">
                <?php else: ?>
                    <i class="fas fa-file text-slate-400 text-5xl"></i>
                <?php endif; ?>
            </div>
            <p class="text-xs font-medium text-slate-700 truncate"><?php echo htmlspecialchars($item['name']); ?></p>
            <?php if (!$item['_isFolder'] && $item['size'] > 0): ?>
                <p class="text-[10px] text-slate-400 mt-0.5"><?php echo formatSize($item['size']); ?></p>
            <?php endif; ?>
            <div class="absolute top-1 right-1 opacity-0 group-hover:opacity-100 transition">
                <a href="?delete_file=<?php echo $item['id']; ?>&return_folder=<?php echo $current_folder; ?>" onclick="return confirm('確定要刪除「<?php echo htmlspecialchars($item['name']); ?>」？')" class="text-red-400 hover:text-red-600 text-xs bg-white rounded-full w-6 h-6 flex items-center justify-center shadow-sm border border-slate-100"><i class="fas fa-times"></i></a>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
<?php else: ?>
    <div class="bg-white rounded-xl border border-slate-100 shadow-sm overflow-hidden">
        <table class="w-full text-left">
            <thead class="bg-slate-50 border-b border-slate-100">
                <tr><th class="px-5 py-3 text-xs font-semibold text-slate-500 uppercase">名稱</th><th class="px-5 py-3 text-xs font-semibold text-slate-500 uppercase">類型</th><th class="px-5 py-3 text-xs font-semibold text-slate-500 uppercase">大小</th><th class="px-5 py-3 text-xs font-semibold text-slate-500 uppercase">修改日期</th><th class="px-5 py-3 text-right"></th></tr>
            </thead>
            <tbody class="divide-y divide-slate-100">
                <?php foreach ($initialItems as $item): ?>
                <tr class="hover:bg-slate-50 transition">
                    <td class="px-5 py-3">
                        <div class="flex items-center gap-3">
                            <?php if ($item['_isFolder']): ?>
                                <i class="fas fa-folder text-yellow-500"></i>
                                <a href="javascript:navigateTo('<?php echo $item['id']; ?>')" class="text-sm font-medium text-slate-700 hover:text-blue-600 truncate max-w-xs"><?php echo htmlspecialchars($item['name']); ?></a>
                            <?php else: ?>
                                <i class="fas fa-file text-slate-400"></i>
                                <a href="<?php echo $item['webViewLink']; ?>" target="_blank" class="text-sm font-medium text-slate-700 hover:text-blue-600 truncate max-w-xs"><?php echo htmlspecialchars($item['name']); ?></a>
                            <?php endif; ?>
                        </div>
                    </td>
                    <td class="px-5 py-3 text-xs text-slate-500"><?php echo $item['_isFolder'] ? '資料夾' : strtoupper(pathinfo($item['name'], PATHINFO_EXTENSION)); ?></td>
                    <td class="px-5 py-3 text-xs text-slate-500"><?php echo $item['_isFolder'] ? '-' : formatSize($item['size']); ?></td>
                    <td class="px-5 py-3 text-xs text-slate-500"><?php echo date('Y-m-d H:i', strtotime($item['modifiedTime'] ?: $item['createdTime'])); ?></td>
                    <td class="px-5 py-3 text-right">
                        <a href="?delete_file=<?php echo $item['id']; ?>&return_folder=<?php echo $current_folder; ?>" onclick="return confirm('確定要刪除「<?php echo htmlspecialchars($item['name']); ?>」？')" class="text-slate-300 hover:text-red-500 text-sm"><i class="fas fa-trash-alt"></i></a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
<?php endif; ?>
</div>

<!-- New Folder Modal -->
<div id="new-folder-modal" class="hidden fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
    <div class="bg-white rounded-2xl w-full max-w-sm p-8 shadow-2xl">
        <div class="flex justify-between items-center mb-6">
            <h2 class="text-xl font-bold text-slate-800">新增資料夾</h2>
            <button onclick="document.getElementById('new-folder-modal').classList.add('hidden')" class="text-slate-400 hover:text-slate-600"><i class="fas fa-times"></i></button>
        </div>
        <form action="google_drive_docs.php" method="POST" class="space-y-4">
            <input type="hidden" name="action" value="new_folder">
            <input type="hidden" name="parent_id" value="<?php echo $current_folder; ?>">
            <div>
                <label class="block text-sm font-medium text-slate-700 mb-1">資料夾名稱</label>
                <input type="text" name="folder_name" required autofocus class="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none">
            </div>
            <div class="flex gap-3 pt-2">
                <button type="button" onclick="document.getElementById('new-folder-modal').classList.add('hidden')" class="flex-1 px-4 py-2 border border-slate-200 text-slate-600 rounded-lg hover:bg-slate-50 transition">取消</button>
                <button type="submit" class="flex-1 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 shadow-lg transition">創建</button>
            </div>
        </form>
    </div>
</div>

<!-- Upload Modal -->
<div id="upload-modal" class="hidden fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
    <div class="bg-white rounded-2xl w-full max-w-md p-8 shadow-2xl">
        <div class="flex justify-between items-center mb-6">
            <h2 class="text-xl font-bold text-slate-800">上傳檔案</h2>
            <button onclick="document.getElementById('upload-modal').classList.add('hidden')" class="text-slate-400 hover:text-slate-600"><i class="fas fa-times"></i></button>
        </div>
        <form action="google_drive_docs.php" method="POST" enctype="multipart/form-data" class="space-y-4">
            <input type="hidden" name="action" value="upload">
            <input type="hidden" name="parent_id" id="upload-parent-id" value="<?php echo $current_folder; ?>">
            <div class="border-2 border-dashed border-slate-200 rounded-xl p-8 text-center hover:border-blue-400 transition cursor-pointer" id="drop-zone">
                <i class="fab fa-google-drive text-4xl text-slate-300 mb-3"></i>
                <p class="text-sm text-slate-500">點擊或拖拽檔案到此處</p>
                <p class="text-xs text-slate-400 mt-1">檔案會即時同步到 Google Drive</p>
                <input type="file" name="files[]" id="file-input" class="hidden" multiple>
                <div id="file-name-display" class="mt-3 space-y-1"></div>
            </div>
            <div class="flex gap-3 pt-2">
                <button type="button" onclick="document.getElementById('upload-modal').classList.add('hidden')" class="flex-1 px-4 py-2 border border-slate-200 text-slate-600 rounded-lg hover:bg-slate-50 transition">取消</button>
                <button type="submit" class="flex-1 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 shadow-lg transition">上傳到雲端</button>
            </div>
        </form>
    </div>
</div>

<script>
let currentFolder = '<?php echo $current_folder; ?>';

function navigateTo(folderId) {
    if (folderId === '') folderId = 'root';
    currentFolder = folderId;
    
    const uploadInput = document.getElementById('upload-parent-id');
    const folderInput = document.querySelector('#new-folder-modal input[name="parent_id"]');
    if (uploadInput) uploadInput.value = folderId;
    if (folderInput) folderInput.value = folderId;
    
    document.getElementById('gd-loading').classList.remove('hidden');
    document.getElementById('gd-content').innerHTML = '<div class="text-center py-20"><i class="fas fa-spinner fa-spin text-blue-500 text-4xl"></i></div>';
    
    fetch('google_drive_docs.php?ajax=1&folder_id=' + encodeURIComponent(folderId))
    .then(r => r.json())
    .then(data => {
        if (!data.success) { document.getElementById('gd-content').innerHTML = '<div class="text-center py-20 text-red-500">載入失敗</div>'; return; }
        
        // 更新麵包屑
        let bcHtml = '';
        (data.breadcrumbs || []).forEach(function(b) {
            bcHtml += '<i class="fas fa-chevron-right text-slate-300 text-xs"></i><a href="javascript:navigateTo(\'' + b.id + '\')" class="text-blue-600 hover:underline">' + he(b.name) + '</a>';
        });
        document.getElementById('gd-breadcrumbs').innerHTML = bcHtml;
        
        renderItems(data.contents);
        document.getElementById('gd-loading').classList.add('hidden');
    })
    .catch(function() {
        document.getElementById('gd-content').innerHTML = '<div class="text-center py-20 text-red-500">載入失敗</div>';
        document.getElementById('gd-loading').classList.add('hidden');
    });
}

function he(str) {
    if (!str) return '';
    return str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#039;');
}

function renderItems(contents) {
    const folders = contents.folders || [];
    const files = contents.files || [];
    const all = [].concat(folders.map(function(f) { f._isFolder = true; return f; }), files.map(function(f) { f._isFolder = false; return f; }));
    document.getElementById('gd-count').textContent = all.length + ' 個項目';
    
    if (all.length === 0) {
        document.getElementById('gd-content').innerHTML = '<div class="text-center py-20 bg-white rounded-2xl border-2 border-dashed border-slate-200">' +
            '<i class="fab fa-google-drive text-slate-300 text-6xl mb-4"></i><p class="text-slate-500 mb-2">此資料夾暫無內容</p>' +
            '<div class="flex justify-center gap-3"><button onclick="document.getElementById(\'new-folder-modal\').classList.remove(\'hidden\')" class="text-blue-600 hover:text-blue-800 text-sm font-medium">新增資料夾</button>' +
            '<span class="text-slate-300">|</span><button onclick="document.getElementById(\'upload-modal\').classList.remove(\'hidden\')" class="text-blue-600 hover:text-blue-800 text-sm font-medium">上傳檔案</button></div></div>';
        return;
    }
    
    <?php if ($view_mode === 'grid'): ?>
    let html = '<div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 xl:grid-cols-8 gap-4">';
    all.forEach(function(item) {
        html += '<div class="gd-item bg-white rounded-xl border border-slate-100 shadow-sm hover:shadow-md transition p-4 text-center cursor-pointer group relative" onclick="' + 
            (item._isFolder ? "navigateTo(\'" + item.id + "\')" : "window.open(\'" + item.webViewLink + "\',\'_blank\')") + '">';
        html += '<div class="h-20 flex items-center justify-center mb-2">' + 
            (item._isFolder ? '<i class="fas fa-folder text-yellow-500 text-5xl"></i>' : 
            (item.thumbnailLink ? '<img src="' + item.thumbnailLink + '" class="h-full w-full object-cover rounded-lg">' : '<i class="fas fa-file text-slate-400 text-5xl"></i>')) + '</div>';
        html += '<p class="text-xs font-medium text-slate-700 truncate" title="' + he(item.name) + '">' + he(item.name) + '</p>';
        if (!item._isFolder && item.size > 0) html += '<p class="text-[10px] text-slate-400 mt-0.5">' + fs(item.size) + '</p>';
        html += '<div class="absolute top-1 right-1 opacity-0 group-hover:opacity-100 transition">' +
            '<a href="?delete_file=' + item.id + '&return_folder=' + currentFolder + '" onclick="return confirm(\'確定要刪除「' + he(item.name) + '」？\')" class="text-red-400 hover:text-red-600 text-xs bg-white rounded-full w-6 h-6 flex items-center justify-center shadow-sm border border-slate-100">' +
            '<i class="fas fa-times"></i></a></div>';
        html += '</div>';
    });
    html += '</div>';
    <?php else: ?>
    let html = '<div class="bg-white rounded-xl border border-slate-100 shadow-sm overflow-hidden"><table class="w-full text-left"><thead class="bg-slate-50 border-b border-slate-100"><tr><th class="px-5 py-3 text-xs font-semibold text-slate-500 uppercase">名稱</th><th class="px-5 py-3 text-xs font-semibold text-slate-500 uppercase">類型</th><th class="px-5 py-3 text-xs font-semibold text-slate-500 uppercase">大小</th><th class="px-5 py-3 text-xs font-semibold text-slate-500 uppercase">修改日期</th><th class="px-5 py-3 text-right"></th></tr></thead><tbody class="divide-y divide-slate-100">';
    all.forEach(function(item) {
        html += '<tr class="hover:bg-slate-50 transition"><td class="px-5 py-3"><div class="flex items-center gap-3">' +
            (item._isFolder ? '<i class="fas fa-folder text-yellow-500"></i><a href="javascript:navigateTo(\'' + item.id + '\')" class="text-sm font-medium text-slate-700 hover:text-blue-600 truncate max-w-xs">' + he(item.name) + '</a>' :
            '<i class="fas fa-file text-slate-400"></i><a href="' + item.webViewLink + '" target="_blank" class="text-sm font-medium text-slate-700 hover:text-blue-600 truncate max-w-xs">' + he(item.name) + '</a>') +
            '</div></td><td class="px-5 py-3 text-xs text-slate-500">' + (item._isFolder ? '資料夾' : (item.fileExtension || '').toUpperCase()) + '</td>' +
            '<td class="px-5 py-3 text-xs text-slate-500">' + (item._isFolder ? '-' : fs(item.size)) + '</td>' +
            '<td class="px-5 py-3 text-xs text-slate-500">' + (item.modifiedTime || item.createdTime || '').substring(0, 16).replace('T', ' ') + '</td>' +
            '<td class="px-5 py-3 text-right"><a href="?delete_file=' + item.id + '&return_folder=' + currentFolder + '" onclick="return confirm(\'確定要刪除「' + he(item.name) + '」？\')" class="text-slate-300 hover:text-red-500 text-sm"><i class="fas fa-trash-alt"></i></a></td></tr>';
    });
    html += '</tbody></table></div>';
    <?php endif; ?>
    document.getElementById('gd-content').innerHTML = html;
}

function fs(bytes) {
    if (bytes >= 1073741824) return (bytes / 1073741824).toFixed(2) + ' GB';
    if (bytes >= 1048576) return (bytes / 1048576).toFixed(2) + ' MB';
    if (bytes >= 1024) return (bytes / 1024).toFixed(2) + ' KB';
    return bytes + ' bytes';
}

function setView(mode) {
    document.cookie = "gd_view=" + mode + ";path=/;max-age=" + (30*24*60*60);
    location.reload();
}

document.addEventListener('DOMContentLoaded', function() {
    // 內容已由伺服器渲染，不需額外載入
    
    const dropZone = document.getElementById('drop-zone');
    const fileInput = document.getElementById('file-input');
    if (dropZone) {
        dropZone.addEventListener('click', () => fileInput.click());
        dropZone.addEventListener('dragover', (e) => { e.preventDefault(); dropZone.classList.add('border-blue-400', 'bg-blue-50'); });
        dropZone.addEventListener('dragleave', () => dropZone.classList.remove('border-blue-400', 'bg-blue-50'));
        dropZone.addEventListener('drop', (e) => {
            e.preventDefault();
            dropZone.classList.remove('border-blue-400', 'bg-blue-50');
            fileInput.files = e.dataTransfer.files;
            const display = document.getElementById('file-name-display');
            display.innerHTML = '';
            for (let f of fileInput.files) {
                display.innerHTML += '<p class="text-xs text-blue-500 font-medium">' + f.name + '</p>';
            }
        });
    }
});
</script>

<?php
function formatSize($bytes) {
    if ($bytes >= 1073741824) return number_format($bytes / 1073741824, 2) . ' GB';
    if ($bytes >= 1048576) return number_format($bytes / 1048576, 2) . ' MB';
    if ($bytes >= 1024) return number_format($bytes / 1024, 2) . ' KB';
    return $bytes . ' bytes';
}
?>

<?php include __DIR__ . '/../includes/footer.php'; ?>
