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

$site_id = isset($_GET['site_id']) ? (int)$_GET['site_id'] : null;
$parent_id = isset($_GET['parent_id']) ? (int)$_GET['parent_id'] : 0;
$view_mode = isset($_COOKIE['site_docs_view']) ? $_COOKIE['site_docs_view'] : 'grid';
$sort_by = isset($_GET['sort']) ? $_GET['sort'] : 'date';
$sort_order = isset($_GET['order']) ? $_GET['order'] : 'desc';

try {
    $pdo->query("SELECT parent_id FROM site_documents LIMIT 1");
} catch (Exception $e) {
    $pdo->exec("ALTER TABLE site_documents ADD COLUMN parent_id INT DEFAULT 0 AFTER site_id");
    $pdo->exec("ALTER TABLE site_documents ADD COLUMN is_folder TINYINT(1) DEFAULT 0 AFTER parent_id");
    $pdo->exec("ALTER TABLE site_documents ADD COLUMN file_size BIGINT DEFAULT 0 AFTER file_type");
    $pdo->exec("ALTER TABLE site_documents MODIFY COLUMN file_path VARCHAR(255) DEFAULT NULL");
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'new_folder') {
    $current_site_id = (int)$_POST['site_id'];
    $folder_name = trim($_POST['folder_name']);
    $current_parent_id = (int)$_POST['parent_id'];
    if ($folder_name) {
        $stmt = $pdo->prepare("INSERT INTO site_documents (site_id, parent_id, file_name, is_folder) VALUES (?, ?, ?, 1)");
        $stmt->execute([$current_site_id, $current_parent_id, $folder_name]);
        header("Location: site_docs.php?site_id=$current_site_id&parent_id=$current_parent_id&success=資料夾已創建");
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'move_items') {
    $target_parent_id = (int)$_POST['target_parent_id'];
    $item_ids = isset($_POST['item_ids']) ? explode(',', $_POST['item_ids']) : [];
    if (!empty($item_ids)) {
        $placeholders = implode(',', array_fill(0, count($item_ids), '?'));
        $stmt = $pdo->prepare("UPDATE site_documents SET parent_id = ? WHERE id IN ($placeholders) AND id != ?");
        $params = array_merge([$target_parent_id], $item_ids, [$target_parent_id]);
        $stmt->execute($params);
        echo json_encode(['success' => true]);
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'upload') {
    $current_site_id = (int)$_POST['site_id'];
    $current_parent_id = (int)$_POST['parent_id'];
    $uploaded_count = 0;
    if (isset($_FILES['files']) && is_array($_FILES['files']['name'])) {
        $file_count = count($_FILES['files']['name']);
        for ($i = 0; $i < $file_count; $i++) {
            if ($_FILES['files']['error'][$i] === UPLOAD_ERR_OK) {
                $file_name = $_FILES['files']['name'][$i];
                $file_size = $_FILES['files']['size'][$i];
                $ext = pathinfo($file_name, PATHINFO_EXTENSION);
                $safe_name = uniqid('doc_') . '.' . $ext;
                if (move_uploaded_file($_FILES['files']['tmp_name'][$i], UPLOAD_DIR . 'documents/' . $safe_name)) {
                    $stmt = $pdo->prepare("INSERT INTO site_documents (site_id, parent_id, file_name, file_path, file_type, file_size, is_folder) VALUES (?, ?, ?, ?, ?, ?, 0)");
                    $stmt->execute([$current_site_id, $current_parent_id, $file_name, 'uploads/documents/' . $safe_name, $ext, $file_size]);
                    $uploaded_count++;
                }
            }
        }
    }
    if ($uploaded_count > 0) {
        header("Location: site_docs.php?site_id=$current_site_id&parent_id=$current_parent_id&success=已成功上傳 $uploaded_count 個文件");
        exit;
    }
}

if (isset($_GET['delete_file'])) {
    $file_id = (int)$_GET['delete_file'];
    $stmt = $pdo->prepare("SELECT * FROM site_documents WHERE id = ?");
    $stmt->execute([$file_id]);
    $file = $stmt->fetch();
    if ($file) {
        $current_site_id = $file['site_id'];
        $current_parent_id = $file['parent_id'];
        if ($file['is_folder']) {
            deleteRecursive($pdo, $file_id);
            $msg = '資料夾及其內容已刪除';
        } else {
            if ($file['file_path']) {
                @unlink(__DIR__ . '/../' . $file['file_path']);
            }
            $pdo->prepare("DELETE FROM site_documents WHERE id = ?")->execute([$file_id]);
            $msg = '文件已刪除';
        }
        header("Location: site_docs.php?site_id=$current_site_id&parent_id=$current_parent_id&success=$msg");
        exit;
    }
}

function deleteRecursive($pdo, $id) {
    $stmt = $pdo->prepare("SELECT * FROM site_documents WHERE parent_id = ?");
    $stmt->execute([$id]);
    $children = $stmt->fetchAll();
    foreach ($children as $child) {
        if ($child['is_folder']) {
            deleteRecursive($pdo, $child['id']);
        } else {
            if ($child['file_path']) {
                @unlink(__DIR__ . '/../' . $child['file_path']);
            }
            $pdo->prepare("DELETE FROM site_documents WHERE id = ?")->execute([$child['id']]);
        }
    }
    $pdo->prepare("DELETE FROM site_documents WHERE id = ?")->execute([$id]);
}

$sites = $pdo->query("SELECT * FROM sites ORDER BY location ASC")->fetchAll();
$success = isset($_GET['success']) ? $_GET['success'] : '';
$error = isset($_GET['error']) ? $_GET['error'] : '';

$breadcrumbs = [];
if ($parent_id > 0) {
    $curr = $parent_id;
    while ($curr > 0) {
        $stmt = $pdo->prepare("SELECT id, file_name, parent_id FROM site_documents WHERE id = ?");
        $stmt->execute([$curr]);
        $folder = $stmt->fetch();
        if ($folder) {
            array_unshift($breadcrumbs, $folder);
            $curr = $folder['parent_id'];
        } else {
            break;
        }
    }
}

$documents = [];
if ($site_id) {
    $order_sql = "is_folder DESC";
    switch ($sort_by) {
        case 'name': $order_sql .= ", file_name " . ($sort_order === 'asc' ? 'ASC' : 'DESC'); break;
        case 'size': $order_sql .= ", file_size " . ($sort_order === 'asc' ? 'ASC' : 'DESC'); break;
        case 'type': $order_sql .= ", file_type " . ($sort_order === 'asc' ? 'ASC' : 'DESC'); break;
        case 'date':
        default: $order_sql .= ", created_at " . ($sort_order === 'asc' ? 'ASC' : 'DESC'); break;
    }
    $stmt = $pdo->prepare("SELECT * FROM site_documents WHERE site_id = ? AND parent_id = ? ORDER BY $order_sql");
    $stmt->execute([$site_id, $parent_id]);
    $documents = $stmt->fetchAll();
}

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

<style>
    .selectable-area { position: relative; }
    .selection-box {
        position: absolute;
        border: 1px solid #3b82f6;
        background: rgba(59, 130, 246, 0.1);
        pointer-events: none;
        z-index: 100;
    }
    .item-selected {
        background-color: rgba(59, 130, 246, 0.1) !important;
        border-color: #3b82f6 !important;
    }
    .drop-target {
        background-color: rgba(34, 197, 94, 0.1) !important;
        border: 2px dashed #22c55e !important;
    }
    #context-menu {
        display: none;
        position: fixed;
        z-index: 1000;
        min-width: 160px;
        background: white;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        border: 1px solid #e2e8f0;
        padding: 4px 0;
    }
    .menu-item {
        padding: 8px 16px;
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 14px;
        color: #475569;
    }
    .menu-item:hover {
        background: #f1f5f9;
        color: #1e293b;
    }
    .menu-item.danger { color: #ef4444; }
    .menu-item.danger:hover { background: #fef2f2; }
</style>

<div class="mb-8">
    <h1 class="text-2xl font-bold text-slate-800">地盤文件</h1>
    <p class="text-slate-500">管理地盤相關合約、圖紙及現場照片</p>
</div>

<div class="bg-white p-6 rounded-2xl shadow-sm border border-slate-100 mb-8">
    <div class="flex flex-wrap items-center justify-between gap-4">
        <form action="site_docs.php" method="GET" class="flex flex-wrap items-end gap-4 flex-1">
            <div class="min-w-[200px]">
                <label class="block text-sm font-medium text-slate-700 mb-1">選擇地盤</label>
                <select name="site_id" onchange="this.form.submit()" class="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none">
                    <option value="">-- 請選擇地盤 --</option>
                    <?php foreach ($sites as $site): ?>
                    <option value="<?php echo $site['id']; ?>" <?php echo $site_id == $site['id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($site['location'] . ($site['unit'] ? ' - ' . $site['unit'] : '')); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php if ($site_id): ?>
            <div class="min-w-[150px]">
                <label class="block text-sm font-medium text-slate-700 mb-1">排序方式</label>
                <div class="flex gap-2">
                    <select name="sort" onchange="this.form.submit()" class="flex-1 px-3 py-2 border border-slate-200 rounded-lg text-sm outline-none">
                        <option value="date" <?php echo $sort_by == 'date' ? 'selected' : ''; ?>>日期</option>
                        <option value="name" <?php echo $sort_by == 'name' ? 'selected' : ''; ?>>名稱</option>
                        <option value="size" <?php echo $sort_by == 'size' ? 'selected' : ''; ?>>大小</option>
                        <option value="type" <?php echo $sort_by == 'type' ? 'selected' : ''; ?>>類型</option>
                    </select>
                    <input type="hidden" name="parent_id" value="<?php echo $parent_id; ?>">
                    <a href="?site_id=<?php echo $site_id; ?>&parent_id=<?php echo $parent_id; ?>&sort=<?php echo $sort_by; ?>&order=<?php echo $sort_order == 'asc' ? 'desc' : 'asc'; ?>" class="px-3 py-2 border border-slate-200 rounded-lg hover:bg-slate-50 transition" title="切換升降序">
                        <i class="fas fa-sort-amount-<?php echo $sort_order == 'asc' ? 'up' : 'down'; ?> text-slate-500"></i>
                    </a>
                </div>
            </div>
            <?php endif; ?>
        </form>
        <?php if ($site_id): ?>
        <div class="flex items-center gap-3">
            <div class="flex border border-slate-200 rounded-lg overflow-hidden mr-2">
                <button onclick="setViewMode('grid')" class="px-3 py-2 <?php echo $view_mode == 'grid' ? 'bg-blue-50 text-blue-600' : 'bg-white text-slate-400'; ?> hover:bg-slate-50 transition border-r border-slate-200" title="大圖示">
                    <i class="fas fa-th-large"></i>
                </button>
                <button onclick="setViewMode('list')" class="px-3 py-2 <?php echo $view_mode == 'list' ? 'bg-blue-50 text-blue-600' : 'bg-white text-slate-400'; ?> hover:bg-slate-50 transition" title="列表視圖">
                    <i class="fas fa-list"></i>
                </button>
            </div>
            <button type="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 transition">
                <i class="fas fa-folder-plus mr-2"></i> 新建資料夾
            </button>
            <button type="button" onclick="document.getElementById('upload-modal').classList.remove('hidden')" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-lg flex items-center shadow-sm transition">
                <i class="fas fa-upload mr-2"></i> 上傳文件
            </button>
        </div>
        <?php endif; ?>
    </div>
</div>

<?php if ($site_id): ?>
<div class="flex items-center gap-2 mb-6 text-sm">
    <a href="?site_id=<?php echo $site_id; ?>" class="text-blue-600 hover:underline flex items-center">
        <i class="fas fa-home mr-1"></i> 根目錄
    </a>
    <?php foreach ($breadcrumbs as $bc): ?>
        <i class="fas fa-chevron-right text-slate-300 text-xs"></i>
        <a href="?site_id=<?php echo $site_id; ?>&parent_id=<?php echo $bc['id']; ?>" class="text-blue-600 hover:underline">
            <?php echo htmlspecialchars($bc['file_name']); ?>
        </a>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<?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 (!$site_id): ?>
    <div class="text-center py-20 bg-slate-50 rounded-2xl border-2 border-dashed border-slate-200">
        <i class="fas fa-folder-open text-slate-300 text-6xl mb-4"></i>
        <p class="text-slate-500">請先選擇一個地盤以查看文件</p>
    </div>
<?php else: ?>
    <div class="selectable-area" id="file-container">
        <?php if ($view_mode === 'grid'): ?>
            <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-6">
                <?php foreach ($documents as $doc): ?>
                <?php
                    $is_image = !$doc['is_folder'] && in_array(strtolower($doc['file_type']), ['jpg', 'jpeg', 'png', 'gif', 'webp']);
                    $icon = 'fa-file';
                    if ($doc['is_folder']) {
                        $icon = 'fa-folder text-yellow-500';
                        $link = "?site_id=$site_id&parent_id=" . $doc['id'];
                    } else {
                        if ($is_image) $icon = 'fa-file-image text-blue-500';
                        elseif ($doc['file_type'] === 'pdf') $icon = 'fa-file-pdf text-red-500';
                        elseif (in_array($doc['file_type'], ['doc', 'docx'])) $icon = 'fa-file-word text-blue-700';
                        elseif (in_array($doc['file_type'], ['xls', 'xlsx'])) $icon = 'fa-file-excel text-green-700';
                        $link = "../" . $doc['file_path'];
                    }
                ?>
                <div class="file-item group relative bg-white p-4 rounded-xl border border-slate-100 shadow-sm hover:shadow-md transition text-center cursor-default select-none" data-id="<?php echo $doc['id']; ?>" data-type="<?php echo $doc['is_folder'] ? 'folder' : 'file'; ?>" data-url="<?php echo $link; ?>" draggable="true">
                    <div class="h-24 flex items-center justify-center mb-3 pointer-events-none">
                        <?php if ($is_image): ?>
                            <img src="../<?php echo $doc['file_path']; ?>" class="h-full w-full object-cover rounded-lg">
                        <?php else: ?>
                            <i class="fas <?php echo $icon; ?> text-5xl"></i>
                        <?php endif; ?>
                    </div>
                    <p class="text-xs font-medium text-slate-700 truncate px-2 pointer-events-none" title="<?php echo htmlspecialchars($doc['file_name']); ?>"><?php echo htmlspecialchars($doc['file_name']); ?></p>
                </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-6 py-3 text-xs font-semibold text-slate-500 uppercase">名稱</th>
                            <th class="px-6 py-3 text-xs font-semibold text-slate-500 uppercase">修改日期</th>
                            <th class="px-6 py-3 text-xs font-semibold text-slate-500 uppercase">類型</th>
                            <th class="px-6 py-3 text-xs font-semibold text-slate-500 uppercase">大小</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100" id="file-list-body">
                        <?php foreach ($documents as $doc): ?>
                        <tr class="file-item hover:bg-slate-50 transition group cursor-default select-none" data-id="<?php echo $doc['id']; ?>" data-type="<?php echo $doc['is_folder'] ? 'folder' : 'file'; ?>" data-url="<?php echo $doc['is_folder'] ? "?site_id=$site_id&parent_id=" . $doc['id'] : "../" . $doc['file_path']; ?>" draggable="true">
                            <td class="px-6 py-4">
                                <div class="flex items-center pointer-events-none">
                                    <?php
                                        $icon = 'fa-file';
                                        if ($doc['is_folder']) {
                                            $icon = 'fa-folder text-yellow-500';
                                        } else {
                                            if (in_array(strtolower($doc['file_type']), ['jpg', 'jpeg', 'png', 'gif', 'webp'])) $icon = 'fa-file-image text-blue-500';
                                            elseif ($doc['file_type'] === 'pdf') $icon = 'fa-file-pdf text-red-500';
                                            elseif (in_array($doc['file_type'], ['doc', 'docx'])) $icon = 'fa-file-word text-blue-700';
                                            elseif (in_array($doc['file_type'], ['xls', 'xlsx'])) $icon = 'fa-file-excel text-green-700';
                                        }
                                    ?>
                                    <i class="fas <?php echo $icon; ?> mr-3 text-lg w-6 text-center"></i>
                                    <span class="text-sm font-medium text-slate-700 truncate max-w-xs"><?php echo htmlspecialchars($doc['file_name']); ?></span>
                                </div>
                            </td>
                            <td class="px-6 py-4 text-sm text-slate-500 pointer-events-none"><?php echo date('Y-m-d H:i', strtotime($doc['created_at'])); ?></td>
                            <td class="px-6 py-4 text-sm text-slate-500 uppercase pointer-events-none"><?php echo $doc['is_folder'] ? '資料夾' : $doc['file_type']; ?></td>
                            <td class="px-6 py-4 text-sm text-slate-500 pointer-events-none"><?php echo $doc['is_folder'] ? '-' : formatSize($doc['file_size']); ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
        <?php if (empty($documents)): ?>
            <div class="py-20 text-center text-slate-400 bg-white rounded-xl border border-dashed border-slate-200 mt-6">
                <i class="fas fa-inbox text-4xl mb-3"></i>
                <p>此資料夾暫無內容</p>
            </div>
        <?php endif; ?>
    </div>
<?php endif; ?>

<div id="context-menu">
    <div class="menu-item" onclick="handleOpen()"><i class="fas fa-folder-open"></i> 打開</div>
    <div class="menu-item border-t border-slate-100" onclick="handleDownload()"><i class="fas fa-download"></i> 下載</div>
    <div class="menu-item danger border-t border-slate-100" onclick="handleDelete()"><i class="fas fa-trash-alt"></i> 刪除</div>
</div>

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

<div id="new-folder-modal" class="hidden fixed inset-0 bg-black bg-opacity-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="site_docs.php" method="POST" class="space-y-4">
            <input type="hidden" name="action" value="new_folder">
            <input type="hidden" name="site_id" value="<?php echo $site_id; ?>">
            <input type="hidden" name="parent_id" value="<?php echo $parent_id; ?>">
            <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="pt-4 flex gap-3">
                <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>

<div id="upload-modal" class="hidden fixed inset-0 bg-black bg-opacity-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 transform transition-all">
        <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="site_docs.php" method="POST" enctype="multipart/form-data" class="space-y-4">
            <input type="hidden" name="action" value="upload">
            <input type="hidden" name="site_id" value="<?php echo $site_id; ?>">
            <input type="hidden" name="parent_id" value="<?php echo $parent_id; ?>">
            <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="fas fa-cloud-upload-alt 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">支援多個文件上傳</p>
                <input type="file" name="files[]" id="file-input" class="hidden" multiple onchange="displaySelectedFiles(this)">
                <div id="file-name-display" class="mt-3 space-y-1"></div>
            </div>
            <div class="pt-4 flex gap-3">
                <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>

<div id="preview-modal" class="hidden fixed inset-0 bg-black bg-opacity-90 z-[60] flex items-center justify-center p-4" onclick="this.classList.add('hidden')">
    <img id="preview-img" src="" class="max-w-full max-h-full shadow-2xl">
</div>

<script>
    let selectedIds = new Set();
    let isSelecting = false;
    let startX, startY;
    const container = document.getElementById('file-container');
    const contextMenu = document.getElementById('context-menu');

    function previewImage(src) {
        document.getElementById('preview-img').src = src;
        document.getElementById('preview-modal').classList.remove('hidden');
    }

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

    function updateSelectionUI() {
        document.querySelectorAll('.file-item').forEach(item => {
            if (selectedIds.has(item.dataset.id)) {
                item.classList.add('item-selected');
            } else {
                item.classList.remove('item-selected');
            }
        });
    }

    container.addEventListener('mousedown', function(e) {
        if (e.button !== 0) return;
        const item = e.target.closest('.file-item');
        if (item) {
            if (e.ctrlKey || e.metaKey) {
                if (selectedIds.has(item.dataset.id)) selectedIds.delete(item.dataset.id);
                else selectedIds.add(item.dataset.id);
            } else {
                if (!selectedIds.has(item.dataset.id)) {
                    selectedIds.clear();
                    selectedIds.add(item.dataset.id);
                }
            }
            updateSelectionUI();
        } else {
            if (!e.ctrlKey && !e.metaKey) {
                selectedIds.clear();
                updateSelectionUI();
            }
            isSelecting = true;
            startX = e.pageX;
            startY = e.pageY;
            const box = document.createElement('div');
            box.className = 'selection-box';
            box.id = 'selection-box';
            document.body.appendChild(box);
        }
        contextMenu.style.display = 'none';
    });

    window.addEventListener('mousemove', function(e) {
        if (!isSelecting) return;
        const box = document.getElementById('selection-box');
        const curX = e.pageX;
        const curY = e.pageY;
        const left = Math.min(startX, curX);
        const top = Math.min(startY, curY);
        const width = Math.abs(startX - curX);
        const height = Math.abs(startY - curY);
        box.style.left = left + 'px';
        box.style.top = top + 'px';
        box.style.width = width + 'px';
        box.style.height = height + 'px';
        document.querySelectorAll('.file-item').forEach(item => {
            const rect = item.getBoundingClientRect();
            const itemTop = rect.top + window.scrollY;
            const itemLeft = rect.left + window.scrollX;
            if (itemLeft < left + width && itemLeft + rect.width > left && itemTop < top + height && itemTop + rect.height > top) {
                selectedIds.add(item.dataset.id);
            }
        });
        updateSelectionUI();
    });

    window.addEventListener('mouseup', function() {
        isSelecting = false;
        const box = document.getElementById('selection-box');
        if (box) box.remove();
    });

    container.addEventListener('dblclick', function(e) {
        const item = e.target.closest('.file-item');
        if (item) {
            window.location.href = item.dataset.url;
        }
    });

    container.addEventListener('contextmenu', function(e) {
        e.preventDefault();
        const item = e.target.closest('.file-item');
        if (item) {
            if (!selectedIds.has(item.dataset.id)) {
                selectedIds.clear();
                selectedIds.add(item.dataset.id);
                updateSelectionUI();
            }
            contextMenu.style.display = 'block';
            contextMenu.style.left = e.clientX + 'px';
            contextMenu.style.top = e.clientY + 'px';
        }
    });

    window.handleOpen = function() {
        if (selectedIds.size === 1) {
            const id = Array.from(selectedIds)[0];
            const item = document.querySelector(`.file-item[data-id="${id}"]`);
            window.location.href = item.dataset.url;
        }
    };

    window.handleDownload = function() {
        selectedIds.forEach(id => {
            const item = document.querySelector(`.file-item[data-id="${id}"]`);
            if (item.dataset.type === 'file') {
                const link = document.createElement('a');
                link.href = item.dataset.url;
                link.download = '';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        });
    };

    window.handleDelete = function() {
        if (confirm(`確定要刪除選中的 ${selectedIds.size} 個項目嗎？`)) {
            selectedIds.forEach(id => {
                window.location.href = `?site_id=<?php echo $site_id; ?>&parent_id=<?php echo $parent_id; ?>&delete_file=${id}`;
            });
        }
    };

    container.addEventListener('dragstart', function(e) {
        const item = e.target.closest('.file-item');
        if (item) {
            if (!selectedIds.has(item.dataset.id)) {
                selectedIds.clear();
                selectedIds.add(item.dataset.id);
                updateSelectionUI();
            }
            e.dataTransfer.setData('text/plain', Array.from(selectedIds).join(','));
        }
    });

    container.addEventListener('dragover', function(e) {
        e.preventDefault();
        const item = e.target.closest('.file-item[data-type="folder"]');
        if (item && !selectedIds.has(item.dataset.id)) {
            item.classList.add('drop-target');
        }
    });

    container.addEventListener('dragleave', function(e) {
        const item = e.target.closest('.file-item[data-type="folder"]');
        if (item) item.classList.remove('drop-target');
    });

    container.addEventListener('drop', function(e) {
        e.preventDefault();
        const target = e.target.closest('.file-item[data-type="folder"]');
        const ids = e.dataTransfer.getData('text/plain');
        if (target && ids && !selectedIds.has(target.dataset.id)) {
            target.classList.remove('drop-target');
            const formData = new FormData();
            formData.append('action', 'move_items');
            formData.append('target_parent_id', target.dataset.id);
            formData.append('item_ids', ids);
            fetch('site_docs.php', { method: 'POST', body: formData }).then(() => location.reload());
        }
    });

    window.addEventListener('click', () => contextMenu.style.display = 'none');

    function displaySelectedFiles(input) {
        const display = document.getElementById('file-name-display');
        display.innerHTML = '';
        if (input.files.length > 0) {
            for (let i = 0; i < input.files.length; i++) {
                const p = document.createElement('p');
                p.className = 'text-xs text-blue-500 font-medium';
                p.textContent = input.files[i].name;
                display.appendChild(p);
            }
        }
    }

    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;
            displaySelectedFiles(fileInput);
        });
    }
</script>

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