<?php
$current = basename($_SERVER['PHP_SELF']);

$role = strtolower(trim($_SESSION['role'] ?? 'user'));
$fullName = trim($_SESSION['full_name'] ?? 'User');
$userCompanies = $_SESSION['companies'] ?? [];
$userCompanyIds = $_SESSION['company_ids'] ?? [];

$isAdmin = ($role === 'admin');
$hasCompanyWorkspace = $isAdmin || !empty($userCompanies);

$workspace = $_GET['workspace'] ?? 'personal';
$scope = $_GET['scope'] ?? $workspace;
$selectedCompanyId = (int)($_GET['company_id'] ?? 0);

if ($workspace === 'company' && !$hasCompanyWorkspace) {
    $workspace = 'personal';
}
if ($scope === 'company' && !$hasCompanyWorkspace) {
    $scope = 'personal';
}

function buildUrl(string $page, array $params = []): string
{
    $query = http_build_query($params);
    return $query ? $page . '?' . $query : $page;
}

function isActivePage(array $pages, string $current): string
{
    return in_array($current, $pages, true) ? 'active' : '';
}

function buildFolderTree(array $folders): array
{
    $tree = [];

    foreach ($folders as $folder) {
        $parentId = isset($folder['parent_folder_id']) && $folder['parent_folder_id'] !== null
            ? (int)$folder['parent_folder_id']
            : 0;

        if (!isset($tree[$parentId])) {
            $tree[$parentId] = [];
        }

        $tree[$parentId][] = $folder;
    }

    return $tree;
}

function folderHasActiveChild(array $tree, int $folderId, int $currentFolderId): bool
{
    if (empty($tree[$folderId])) {
        return false;
    }

    foreach ($tree[$folderId] as $childFolder) {
        $childId = (int)$childFolder['id'];

        if ($childId === $currentFolderId) {
            return true;
        }

        if (folderHasActiveChild($tree, $childId, $currentFolderId)) {
            return true;
        }
    }

    return false;
}

function renderFolderTree(
    array $tree,
    array $folderFiles,
    int $parentId,
    string $workspace,
    string $current,
    int $currentFolderId,
    int $companyId = 0
): void {
    if (empty($tree[$parentId])) {
        return;
    }

    echo '<div class="tree-list">';

    foreach ($tree[$parentId] as $navFolder) {
        $fid = (int)$navFolder['id'];
        $folderKey = ($workspace === 'company')
            ? 'company-' . $companyId . '-' . $fid
            : 'personal-' . $fid;

        $isActiveFolder =
            ($current === 'folder_view.php') &&
            ($currentFolderId === $fid) &&
            (($_GET['workspace'] ?? 'personal') === $workspace) &&
            (
                $workspace !== 'company' ||
                ((int)($_GET['company_id'] ?? 0) === $companyId)
            );

        $filesInFolder = $folderFiles[$fid] ?? [];
        $hasChildren = !empty($tree[$fid]);
        $hasActiveDescendant = folderHasActiveChild($tree, $fid, $currentFolderId);
        $shouldOpen = $isActiveFolder || $hasActiveDescendant;

        echo '<div class="tree-item">';

        echo '<div class="tree-row ' . ($isActiveFolder ? 'active' : '') . '" oncontextmenu="openContextMenu(event, ' . $fid . ', \'folder\', \'' . htmlspecialchars($workspace, ENT_QUOTES) . '\', ' . $companyId . ')">';

        if ($hasChildren || !empty($filesInFolder)) {
            echo '<button type="button" class="tree-toggle" onclick="toggleFolder(event, \'' . htmlspecialchars($folderKey, ENT_QUOTES) . '\')">';
            echo '<span id="icon-' . htmlspecialchars($folderKey, ENT_QUOTES) . '" class="tree-chevron">' . ($shouldOpen ? '▾' : '▸') . '</span>';
            echo '</button>';
        } else {
            echo '<span class="tree-toggle"></span>';
        }

        $folderParams = [
            'id' => $fid,
            'workspace' => $workspace,
            'scope' => $workspace
        ];

        if ($workspace === 'company' && $companyId > 0) {
            $folderParams['company_id'] = $companyId;
        }

        echo '<a href="' . htmlspecialchars(buildUrl('folder_view.php', $folderParams)) . '" class="tree-link">';
        echo '<span class="nav-icon">📁</span>';
        echo '<span class="tree-label">' . htmlspecialchars($navFolder['folder_name']); 
        echo '</span>';
        echo '</a>';

        echo '<button type="button" class="mini-action-btn" onclick="toggleSubfolderForm(event, ' . $fid . ', \'' . htmlspecialchars($workspace, ENT_QUOTES) . '\', ' . $companyId . ')" title="Add subfolder">＋</button>';

        echo '</div>';

        echo '<div class="tree-actions-panel" id="subfolder-form-' . htmlspecialchars($workspace . '-' . $companyId . '-' . $fid, ENT_QUOTES) . '" style="display:none;">';
        echo '  <form method="POST" action="create_folder.php" class="mini-inline-form">';
        echo '      <input type="hidden" name="workspace" value="' . htmlspecialchars($workspace) . '">';
        if ($workspace === 'company' && $companyId > 0) {
            echo '      <input type="hidden" name="company_id" value="' . $companyId . '">';
        }
        echo '      <input type="hidden" name="parent_folder_id" value="' . $fid . '">';
        echo '      <input type="text" name="folder_name" placeholder="Create subfolder..." required>';
        echo '      <button type="submit" class="mini-save-btn">Save</button>';
        echo '  </form>';
        echo '</div>';

        echo '<div class="tree-children" id="folder-' . htmlspecialchars($folderKey, ENT_QUOTES) . '" style="' . ($shouldOpen ? 'display:block;' : 'display:none;') . '">';

        if (!empty($filesInFolder)) {
            foreach ($filesInFolder as $navFile) {
                $fileLabel = trim((string)($navFile['custom_name'] ?? '')) !== ''
                    ? $navFile['custom_name']
                    : ($navFile['original_file_name'] ?? 'Unnamed file');

                echo '<div class="tree-file-row" oncontextmenu="openContextMenu(event, ' . (int)$navFile['id'] . ', \'file\', \'' . htmlspecialchars($workspace, ENT_QUOTES) . '\', ' . $companyId . ')">';
                echo '  <a href="' . htmlspecialchars($navFile['file_path'] ?? '#') . '" target="_blank" class="tree-file" data-file-id="' . (int)$navFile['id'] . '">';
                echo '      <span class="nav-icon">📄</span>';
                echo '      <span class="tree-file-label">' . htmlspecialchars($fileLabel) . '</span>';
                echo '  </a>';
                echo '</div>';
            }
        }

        renderFolderTree($tree, $folderFiles, $fid, $workspace, $current, $currentFolderId, $companyId);

        echo '</div>';
        echo '</div>';
    }

    echo '</div>';
}

$personalFolders = [];
$personalFolderFiles = [];
$personalFolderTree = [];

$companyFoldersByCompany = [];
$companyFolderFilesByCompany = [];
$companyFolderTreeByCompany = [];

$currentFolderId = (int)($_GET['id'] ?? 0);

if (isset($db) && $db instanceof PDO) {
    if (isset($user_id) && (int)$user_id > 0) {
        $stmt = $db->prepare("
            SELECT id, folder_name, parent_folder_id
            FROM folders
            WHERE user_id = :user_id
              AND company_id IS NULL
            ORDER BY folder_name ASC
        ");
        $stmt->bindValue(':user_id', (int)$user_id, PDO::PARAM_INT);
        $stmt->execute();
        $personalFolders = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $personalFolderTree = buildFolderTree($personalFolders);

        if (!empty($personalFolders)) {
            $stmtFiles = $db->prepare("
                SELECT id, folder_id, custom_name, original_file_name, file_path
                FROM documents
                WHERE user_id = :user_id
                  AND company_id IS NULL
                  AND folder_id IS NOT NULL
                ORDER BY id DESC
            ");
            $stmtFiles->bindValue(':user_id', (int)$user_id, PDO::PARAM_INT);
            $stmtFiles->execute();
            $allPersonalFiles = $stmtFiles->fetchAll(PDO::FETCH_ASSOC);

            foreach ($allPersonalFiles as $navFile) {
                $fid = (int)($navFile['folder_id'] ?? 0);
                if ($fid > 0) {
                    $personalFolderFiles[$fid][] = $navFile;
                }
            }
        }
    }

    if (!empty($userCompanies)) {
        foreach ($userCompanies as $company) {
            $companyId = (int)($company['id'] ?? 0);
            if ($companyId <= 0) {
                continue;
            }

            $stmt = $db->prepare("
                SELECT id, folder_name, parent_folder_id
                FROM folders
                WHERE company_id = :company_id
                ORDER BY folder_name ASC
            ");
            $stmt->bindValue(':company_id', $companyId, PDO::PARAM_INT);
            $stmt->execute();
            $companyFolders = $stmt->fetchAll(PDO::FETCH_ASSOC);

            $companyFoldersByCompany[$companyId] = $companyFolders;
            $companyFolderTreeByCompany[$companyId] = buildFolderTree($companyFolders);
            $companyFolderFilesByCompany[$companyId] = [];

            if (!empty($companyFolders)) {
                $stmtFiles = $db->prepare("
                    SELECT id, folder_id, custom_name, original_file_name, file_path
                    FROM documents
                    WHERE company_id = :company_id
                      AND folder_id IS NOT NULL
                    ORDER BY id DESC
                ");
                $stmtFiles->bindValue(':company_id', $companyId, PDO::PARAM_INT);
                $stmtFiles->execute();
                $allCompanyFiles = $stmtFiles->fetchAll(PDO::FETCH_ASSOC);

                foreach ($allCompanyFiles as $navFile) {
                    $fid = (int)($navFile['folder_id'] ?? 0);
                    if ($fid > 0) {
                        $companyFolderFilesByCompany[$companyId][$fid][] = $navFile;
                    }
                }
            }
        }
    }
}
?>

<style>
/* =========================
   LAYOUT
========================= */

.layout {
    display: block;
    min-height: 100vh;
    margin-top: 0;
}

.main {
    margin-left: 260px;
    min-width: 0;
    min-height: 100vh;
    box-sizing: border-box;
}

/* =========================
   SIDEBAR (FULLY FIXED)
========================= */

.sidebar {
    position: fixed;
    top: 0;
    left: 0;
    bottom: 0;
    width: 260px;
    min-width: 260px;
    max-width: 260px;
    z-index: 1000;

    background: linear-gradient(180deg, #06101f 0%, #08142a 55%, #07101d 100%);
    color: #ffffff;

    padding: 14px 10px;
    display: flex;
    flex-direction: column;
    gap: 10px;

    box-sizing: border-box;
    overflow-y: auto;
}

.sidebar.compact-sidebar {
    width: 260px;
    padding: 14px 10px;
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.brand {
    margin-bottom: 4px;
}

.compact-brand {
    padding: 4px 8px 10px;
}

.brand-link {
    text-decoration: none;
    font-size: 44px;
    font-weight: 800;
    letter-spacing: -0.04em;
    line-height: 1;
    display: inline-block;
}

.brand-docu {
    color: #ffffff;
}

.brand-track {
    color: #60a5fa;
}

.sidebar-mini-user {
    padding: 0 8px 10px;
    border-bottom: 1px solid rgba(255,255,255,0.08);
    margin-bottom: 4px;
}

.sidebar-user-name {
    font-size: 14px;
    font-weight: 700;
    color: #fff;
    line-height: 1.2;
}

.sidebar-user-role {
    font-size: 12px;
    color: rgba(255,255,255,0.65);
    margin-top: 2px;
}

.sidebar-nav {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.explorer-nav {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.nav-group {
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.nav-group-title {
    font-size: 11px;
    font-weight: 700;
    letter-spacing: 0.08em;
    text-transform: uppercase;
    color: rgba(255,255,255,0.45);
    padding: 4px 10px;
}

.nav-link {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 8px 10px;
    border-radius: 8px;
    text-decoration: none;
    color: #e2e8f0;
    font-weight: 500;
    transition: all 0.2s ease;
    background: transparent;
}

.compact-link {
    display: flex;
    align-items: center;
    gap: 8px;
    min-height: 34px;
    padding: 8px 10px;
    border-radius: 8px;
    text-decoration: none;
    color: rgba(255,255,255,0.88);
    font-size: 14px;
    font-weight: 500;
    transition: background 0.18s ease, color 0.18s ease;
}

.nav-link:hover,
.compact-link:hover {
    background: rgba(255,255,255,0.08);
    color: #fff;
}

.nav-link.active,
.compact-link.active {
    background: rgba(255,255,255,0.14);
    color: #fff;
    box-shadow: none;
}

.nav-icon {
    width: 16px;
    min-width: 16px;
    text-align: center;
    flex-shrink: 0;
    font-size: 13px;
}

.sidebar-footer {
    margin-top: auto;
    padding-top: 8px;
}

.compact-footer {
    margin-top: auto;
    padding: 10px 8px 0;
}

.logout-btn {
    display: block;
    text-align: center;
    text-decoration: none;
    padding: 12px 14px;
    border-radius: 14px;
    background: rgba(239, 68, 68, 0.12);
    color: #fecaca;
    font-weight: 700;
    border: 1px solid rgba(239, 68, 68, 0.16);
    transition: all 0.2s ease;
}

.logout-btn:hover {
    background: rgba(239, 68, 68, 0.18);
}

.tree-section {
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.tree-section-header {
    display: flex;
    align-items: center;
    gap: 8px;
    min-height: 34px;
    padding: 8px 10px;
    border-radius: 8px;
    color: rgba(255,255,255,0.92);
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    user-select: none;
}

.tree-section-header:hover {
    background: rgba(255,255,255,0.08);
}

.tree-section-chevron,
.tree-chevron {
    width: 12px;
    min-width: 12px;
    text-align: center;
    color: rgba(255,255,255,0.7);
    flex-shrink: 0;
    font-size: 11px;
    line-height: 1;
}

.tree-section-title {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.tree-section-body {
    display: flex;
    flex-direction: column;
    gap: 2px;
}

.tree-list {
    display: flex;
    flex-direction: column;
    gap: 2px;
    margin-left: 10px;
}

.tree-item {
    display: flex;
    flex-direction: column;
}

.tree-row {
    display: flex;
    align-items: center;
    gap: 6px;
    min-height: 30px;
    padding: 2px 4px;
    border-radius: 6px;
}

.tree-row:hover {
    background: rgba(255,255,255,0.06);
}

.tree-row.active {
    background: rgba(255,255,255,0.12);
}

.tree-toggle {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 18px;
    min-width: 18px;
    height: 18px;
    padding: 0;
    margin: 0;
    cursor: pointer;
    user-select: none;
    background: transparent;
    border: none;
    line-height: 1;
    color: rgba(255,255,255,0.7);
}

.tree-link {
    display: flex;
    align-items: center;
    gap: 8px;
    flex: 1;
    min-width: 0;
    padding: 2px 0;
    text-decoration: none;
    color: rgba(255,255,255,0.92);
    font-size: 13px;
    font-weight: 500;
}

.tree-link:hover {
    color: #fff;
}

.tree-label,
.tree-file-label {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.tree-children {
    margin-left: 0;
    margin-top: 2px;
    padding-left: 14px;
    display: flex;
    flex-direction: column;
    gap: 4px;
    border-left: 1px solid rgba(255,255,255,0.10);
}

.tree-file-row {
    display: grid;
    grid-template-columns: minmax(0, 1fr);
    gap: 8px;
    align-items: center;
    padding-left: 14px;
}

.tree-file {
    display: flex;
    align-items: center;
    gap: 8px;
    min-width: 0;
    text-decoration: none;
    color: rgba(255,255,255,0.78);
    font-size: 13px;
    padding: 2px 0;
}

.tree-file:hover {
    color: #fff;
}

.tree-empty {
    padding: 4px 0 4px 24px;
    font-size: 12px;
    color: rgba(255,255,255,0.45);
}

.mini-action-btn {
    border: none;
    background: transparent;
    color: #cbd5e1;
    cursor: pointer;
    font-size: 16px;
    padding: 2px 6px;
    border-radius: 6px;
    width: auto;
    height: auto;
}

.mini-action-btn:hover {
    background: rgba(255,255,255,0.08);
}

.tree-actions-panel {
    margin: 6px 0 8px 26px;
    padding: 8px;
    border-radius: 10px;
    background: rgba(255,255,255,0.05);
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.mini-inline-form {
    display: flex;
    gap: 6px;
    align-items: center;
}

.mini-inline-form input[type="text"] {
    width: 100%;
    min-width: 0;
    height: 30px;
    padding: 4px 8px;
    border-radius: 8px;
    border: 1px solid rgba(255,255,255,0.14);
    background: rgba(255,255,255,0.08);
    color: #fff;
    font-size: 12px;
    box-shadow: none;
    outline: none;
}

.mini-inline-form input[type="text"]:focus {
    border-color: rgba(147,197,253,0.8);
    box-shadow: 0 0 0 2px rgba(147,197,253,0.15);
}

.mini-save-btn {
    background: #2563eb;
    color: #fff;
    border: none;
    border-radius: 8px;
    height: 30px;
    padding: 4px 10px;
    font-size: 12px;
    font-weight: 600;
    cursor: pointer;
    width: auto;
}

.mini-save-btn:hover {
    background: #1d4ed8;
}

.docs-header .tree-link {
    align-items: center;
    padding: 0;
}

.docs-header .tree-section-title {
    font-size: 14px;
    font-weight: 600;
}

.mobile-menu-toggle {
    display: none;
}

.mobile-overlay {
    display: none;
}

.context-menu {
    position: fixed;
    min-width: 180px;
    background: #1f2937;
    border: 1px solid rgba(255,255,255,0.12);
    border-radius: 10px;
    box-shadow: 0 12px 30px rgba(0,0,0,0.35);
    padding: 6px;
    z-index: 5000;
}

.context-menu button {
    display: block;
    width: 100%;
    text-align: left;
    background: transparent;
    border: none;
    color: #fff;
    padding: 10px 12px;
    border-radius: 8px;
    cursor: pointer;
    font-size: 13px;
}

.context-menu button:hover {
    background: rgba(255,255,255,0.08);
}

.section-add-btn {
    margin-left: auto;
}

.workspace-switcher {
    position: relative;
    padding: 8px;
}

.workspace-current {
    width: 100%;
    background: rgba(255,255,255,0.08);
    border: 1px solid rgba(255,255,255,0.15);
    color: #fff;
    padding: 8px 10px;
    border-radius: 10px;
    font-size: 13px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: pointer;
}

.workspace-current:hover {
    background: rgba(255,255,255,0.12);
}

.workspace-menu {
    display: none;
    position: absolute;
    top: 100%;
    left: 8px;
    right: 8px;
    background: #1f2937;
    border: 1px solid rgba(255,255,255,0.12);
    border-radius: 10px;
    margin-top: 6px;
    overflow: hidden;
    z-index: 999;
}

.workspace-item {
    padding: 10px 12px;
    cursor: pointer;
    font-size: 13px;
    color: #fff;
}

.workspace-item:hover {
    background: rgba(255,255,255,0.08);
}

.chevron {
    font-size: 12px;
    opacity: 0.7;
}

@media (max-width: 1024px) {
    .main {
        margin-left: 0;
    }

    .sidebar {
        position: fixed;
        top: 0;
        left: 0;
        width: 82%;
        max-width: 300px;
        height: 100vh;
        z-index: 1000;
        transform: translateX(-100%);
        transition: transform 0.25s ease;
        overflow-y: auto;
        border-radius: 0;
    }

    .sidebar.open {
        transform: translateX(0);
    }

    .mobile-overlay {
        position: fixed;
        inset: 0;
        background: rgba(0,0,0,0.4);
        z-index: 999;
        display: none;
    }

    .mobile-overlay.show {
        display: block;
    }

    .mobile-menu-toggle {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 44px;
        height: 44px;
        border: 1px solid #ddd;
        border-radius: 10px;
        background: #fff;
        font-size: 20px;
        margin-bottom: 12px;
        cursor: pointer;
    }
}

@media (max-width: 640px) {
    .brand-link {
        font-size: 34px;
    }
}
</style>

<aside class="sidebar compact-sidebar" id="sidebar">
    <div class="brand compact-brand">
        <a href="my_documents.php" class="brand-link">
            <span class="brand-docu">Docu</span><span class="brand-track">Track</span>
        </a>
    </div>

    <div class="sidebar-mini-user">
        <div class="sidebar-user-name"><?php echo htmlspecialchars($fullName); ?></div>
        <div class="sidebar-user-role"><?php echo htmlspecialchars(ucfirst($role)); ?></div>
    </div>
    <div class="workspace-switcher">
        <button type="button" class="workspace-current" onclick="toggleWorkspaceMenu()">
            <span>
                <?php if ($workspace === 'all'): ?>
                    🌐 All Workspaces
                <?php elseif ($workspace === 'company' && $selectedCompanyId): ?>
                    🏢
                    <?php
                    foreach ($userCompanies as $c) {
                        if ((int)$c['id'] === $selectedCompanyId) {
                            echo htmlspecialchars($c['company_name']);
                            break;
                        }
                    }
                    ?>
                <?php else: ?>
                    🧑 Personal Workspace
                <?php endif; ?>
            </span>
            <span class="chevron">▾</span>
        </button>

        <div id="workspaceMenu" class="workspace-menu">

            <!-- ALL WORKSPACES -->
            <div class="workspace-item"
                onclick="switchWorkspace('all')">
                🌐 All Workspaces
            </div>

            <!-- PERSONAL -->
            <div class="workspace-item"
                onclick="switchWorkspace('personal')">
                👤 Personal Workspace
            </div>

            <!-- COMPANIES -->
            <?php foreach ($userCompanies as $company): ?>
                <div class="workspace-item"
                    onclick="switchWorkspace('company', <?php echo (int)$company['id']; ?>)">
                    🏢 <?php echo htmlspecialchars($company['company_name']); ?>
                </div>
            <?php endforeach; ?>

        </div>
     </div>


    <nav class="sidebar-nav explorer-nav">
        <?php if ($isAdmin): ?>
        <div class="nav-group">
            <div class="nav-group-title">ADMIN</div>

            <a href="<?php echo htmlspecialchars(buildUrl('users.php')); ?>" class="nav-link compact-link <?php echo isActivePage(['users.php'], $current); ?>">
                <span class="nav-icon">👥</span>
                <span>Users</span>
            </a>

            <a href="<?php echo htmlspecialchars(buildUrl('companies.php')); ?>" class="nav-link compact-link <?php echo isActivePage(['companies.php'], $current); ?>">
                <span class="nav-icon">🏢</span>
                <span>Companies</span>
            </a>
        </div>
        <?php endif; ?>

        <?php if ($workspace === 'personal' || $workspace === 'all'): ?>
            <div class="nav-group">
                <div class="nav-group-title">
                    <?php echo $workspace === 'all' ? 'PERSONAL' : 'PERSONAL WORKSPACE'; ?>
                </div>

                <div class="tree-section">
                    <div class="tree-section-header" onclick="toggleSection('personal-folders-section')">
                        <span class="tree-section-chevron" id="section-icon-personal-folders-section">▾</span>
                        <span class="nav-icon">📁</span>
                        <span class="tree-section-title">Personal Folders</span>
                        <button
                            type="button"
                            class="mini-action-btn section-add-btn"
                            onclick="toggleRootFolderForm(event, 'personal')"
                            title="Add personal folder"
                        >＋</button>
                    </div>

                    <div class="tree-section-body" id="personal-folders-section" style="display:block;">
                        <div class="tree-actions-panel" id="root-folder-form-personal" style="display:none;">
                            <form method="POST" action="create_folder.php" class="mini-inline-form">
                                <input type="hidden" name="workspace" value="personal">
                                <input type="text" name="folder_name" placeholder="Create personal folder..." required>
                                <button type="submit" class="mini-save-btn">Save</button>
                            </form>
                        </div>

                        <?php if (!empty($personalFolders)): ?>
                            <?php renderFolderTree($personalFolderTree, $personalFolderFiles, 0, 'personal', $current, $currentFolderId); ?>
                        <?php else: ?>
                            <div class="tree-empty">No folders</div>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="tree-section">
                    <div class="tree-section-header docs-header">
                        <span class="tree-section-chevron" id="section-icon-personal-documents-section" onclick="toggleSection('personal-documents-section'); event.stopPropagation();">▸</span>
                        <a href="<?php echo htmlspecialchars(buildUrl('my_documents.php', [
    'workspace' => ($workspace === 'all' ? 'all' : 'personal'),
    'scope' => ($workspace === 'all' ? 'all' : 'personal')
])); ?>" class="nav-link compact-link">
                            <span class="nav-icon">▤</span>
                            <span>My Documents</span>
                        </a>
                    </div>
                    <div class="tree-section-body" id="personal-documents-section" style="display:none;"></div>
                </div>
            </div>
        <?php endif; ?>

      <?php if (($workspace === 'company' || $workspace === 'all') && $hasCompanyWorkspace && !empty($userCompanies)): ?>
            <?php foreach ($userCompanies as $company): ?>
    <?php
        $companyId = (int)$company['id'];

        // 🔥 skip other companies if one is selected
        if ($workspace === 'company' && $selectedCompanyId !== $companyId) {
            continue;
        }
    ?>
                <?php
                    $companyId = (int)($company['id'] ?? 0);
                    $companyTitle = trim((string)($company['company_name'] ?? 'Company Workspace'));
                    $companyFolders = $companyFoldersByCompany[$companyId] ?? [];
                    $companyFolderTree = $companyFolderTreeByCompany[$companyId] ?? [];
                    $companyFolderFiles = $companyFolderFilesByCompany[$companyId] ?? [];
                ?>
                <div class="nav-group">
                    <div class="nav-group-title"><?php echo htmlspecialchars($companyTitle); ?></div>

                    <div class="tree-section">
                        <div class="tree-section-header" onclick="toggleSection('company-folders-section-<?php echo $companyId; ?>')">
                            <span class="tree-section-chevron" id="section-icon-company-folders-section-<?php echo $companyId; ?>">▾</span>
                            <span class="nav-icon">📁</span>
                            <span class="tree-section-title">Company's Folders</span>
                            <button
                                type="button"
                                class="mini-action-btn section-add-btn"
                                onclick="toggleRootFolderForm(event, 'company-<?php echo $companyId; ?>')"
                                title="Add company folder"
                            >＋</button>
                        </div>

                        <div class="tree-section-body" id="company-folders-section-<?php echo $companyId; ?>" style="display:block;">
                            <div class="tree-actions-panel" id="root-folder-form-company-<?php echo $companyId; ?>" style="display:none;">
                                <form method="POST" action="create_folder.php" class="mini-inline-form">
                                    <input type="hidden" name="workspace" value="company">
                                    <input type="hidden" name="company_id" value="<?php echo $companyId; ?>">
                                    <input type="text" name="folder_name" placeholder="Create company folder..." required>
                                    <button type="submit" class="mini-save-btn">Save</button>
                                </form>
                            </div>

                            <?php if (!empty($companyFolders)): ?>
                                <?php renderFolderTree(
                                    $companyFolderTree,
                                    $companyFolderFiles,
                                    0,
                                    ($workspace === 'all' ? 'all' : 'company'),
                                    $current,
                                    $currentFolderId,
                                    $companyId
                                ); ?>
                            <?php else: ?>
                                <div class="tree-empty">No folders</div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="tree-section">
                        <div class="tree-section-header docs-header">
                            <span class="tree-section-chevron"
                                  id="section-icon-company-documents-section-<?php echo $companyId; ?>"
                                  onclick="toggleSection('company-documents-section-<?php echo $companyId; ?>'); event.stopPropagation();">▸</span>
                            <a href="<?php echo htmlspecialchars(buildUrl('my_documents.php', [
    'workspace' => ($workspace === 'all' ? 'all' : 'company'),
    'scope' => ($workspace === 'all' ? 'all' : 'company'),
    'company_id' => $companyId
])); ?>" class="nav-link compact-link">
                                <span class="nav-icon">▤</span>
                                <span>Company's Documents</span>
                            </a>
                        </div>
                        <div class="tree-section-body" id="company-documents-section-<?php echo $companyId; ?>" style="display:none;"></div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>

        <div class="nav-group">
            <div class="nav-group-title">GENERAL</div>
            <a href="<?php echo htmlspecialchars(buildUrl('reminders.php')); ?>" class="nav-link compact-link">
                <span class="nav-icon">⏰</span>
                <span>Reminders</span>
            </a>
        </div>
    </nav>

    <div class="sidebar-footer compact-footer">
        <a href="logout.php" class="logout-btn">Logout</a>
    </div>
</aside>

<div id="contextMenu" class="context-menu" style="display:none;">
    <button type="button" onclick="handleContextAction('new_folder')">New Folder</button>
    <button type="button" onclick="handleContextAction('new_file')">New File</button>
    <button type="button" onclick="handleContextAction('rename')">Rename</button>
    <button type="button" onclick="handleContextAction('delete')">Delete</button>
    <button type="button" onclick="handleContextAction('upload')">Upload</button>
    <button type="button" onclick="handleContextAction('download')">Download</button>
</div>

<form id="contextUploadForm" method="POST" action="upload_document.php" enctype="multipart/form-data" style="display:none;">
    <input type="hidden" name="workspace" id="contextUploadWorkspace">
    <input type="hidden" name="folder_id" id="contextUploadFolderId">
    <input type="hidden" name="company_id" id="contextUploadCompanyId">
    <input type="file" name="document_file" id="contextUploadInput" onchange="submitContextUpload()">
</form>

<script>
function toggleSidebar() {
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('mobileOverlay');
    const button = document.querySelector('.mobile-menu-toggle');

    sidebar.classList.toggle('open');
    if (overlay) overlay.classList.toggle('show');
    document.body.classList.toggle('sidebar-open');
    if (button) button.classList.toggle('is-open');
}

function closeSidebar() {
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('mobileOverlay');
    const button = document.querySelector('.mobile-menu-toggle');

    sidebar.classList.remove('open');
    if (overlay) overlay.classList.remove('show');
    document.body.classList.remove('sidebar-open');
    if (button) button.classList.remove('is-open');
}

function switchCompany(value) {
    if (value === 'personal') {
        window.location.href = 'my_documents.php?workspace=personal&scope=personal';
    } else {
        window.location.href = 'my_documents.php?workspace=company&scope=company&company_id=' + encodeURIComponent(value);
    }
}

function toggleSection(id) {
    const el = document.getElementById(id);
    const icon = document.getElementById('section-icon-' + id);

    if (!el || !icon) return;

    const isOpen = el.style.display === 'block';
    el.style.display = isOpen ? 'none' : 'block';
    icon.textContent = isOpen ? '▸' : '▾';
}

function toggleFolder(event, id) {
    event.stopPropagation();

    const el = document.getElementById('folder-' + id);
    const icon = document.getElementById('icon-' + id);

    if (!el || !icon) return;

    const isOpen = el.style.display === 'block';

    if (isOpen) {
        el.style.display = 'none';
        icon.textContent = '▸';
        saveFolderState(id, false);
    } else {
        el.style.display = 'block';
        icon.textContent = '▾';
        saveFolderState(id, true);
    }
}

function toggleSubfolderForm(event, folderId, workspace, companyId = 0) {
    event.stopPropagation();

    const id = 'subfolder-form-' + workspace + '-' + companyId + '-' + folderId;
    const form = document.getElementById(id);

    if (!form) return;

    form.style.display = (form.style.display === 'none' || form.style.display === '')
        ? 'flex'
        : 'none';
}

function saveFolderState(id, isOpen) {
    let state = JSON.parse(localStorage.getItem('folderState') || '{}');
    state[id] = isOpen;
    localStorage.setItem('folderState', JSON.stringify(state));
}

let contextTargetId = null;
let contextTargetType = null;
let contextWorkspace = 'personal';
let contextCompanyId = 0;

function openContextMenu(event, id, type, workspace, companyId = 0) {
    event.preventDefault();
    event.stopPropagation();

    contextTargetId = id;
    contextTargetType = type;
    contextWorkspace = workspace;
    contextCompanyId = companyId || 0;

    const menu = document.getElementById('contextMenu');
    if (!menu) return;

    menu.style.display = 'block';
    menu.style.top = event.clientY + 'px';
    menu.style.left = event.clientX + 'px';
}

function closeContextMenu() {
    const menu = document.getElementById('contextMenu');
    if (menu) menu.style.display = 'none';
}

document.addEventListener('click', function (e) {
    const menu = document.getElementById('contextMenu');

    if (!menu) return;

    if (!menu.contains(e.target)) {
        closeContextMenu();
    }
});

function handleContextAction(action) {
    closeContextMenu();

    const companyPart = (contextWorkspace === 'company' && contextCompanyId > 0)
        ? '&company_id=' + encodeURIComponent(contextCompanyId)
        : '';

    if (action === 'new_folder') {
        const folderName = prompt('Folder name');
        if (!folderName) return;

        const form = document.createElement('form');
        form.method = 'POST';
        form.action = 'create_folder.php';
        form.innerHTML = `
            <input type="hidden" name="folder_name" value="${escapeHtml(folderName)}">
            <input type="hidden" name="parent_folder_id" value="${contextTargetType === 'folder' ? contextTargetId : ''}">
            <input type="hidden" name="workspace" value="${contextWorkspace}">
            <input type="hidden" name="company_id" value="${contextCompanyId}">
        `;
        document.body.appendChild(form);
        form.submit();
    }

    if (action === 'rename') {
        if (contextTargetType === 'folder') {
            const newName = prompt('New folder name');
            if (!newName) return;

            const form = document.createElement('form');
            form.method = 'POST';
            form.action = 'folder_view.php?id=' + contextTargetId +
                '&workspace=' + encodeURIComponent(contextWorkspace) +
                '&scope=' + encodeURIComponent(contextWorkspace) +
                companyPart;
            form.innerHTML = `
                <input type="hidden" name="rename_folder" value="1">
                <input type="hidden" name="new_folder_name" value="${escapeHtml(newName)}">
            `;
            document.body.appendChild(form);
            form.submit();
        }
    }

    if (action === 'delete') {
        if (!confirm('Are you sure you want to delete this item?')) return;

        if (contextTargetType === 'folder') {
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = 'folder_view.php?id=' + contextTargetId +
                '&workspace=' + encodeURIComponent(contextWorkspace) +
                '&scope=' + encodeURIComponent(contextWorkspace) +
                companyPart;
            form.innerHTML = `
                <input type="hidden" name="delete_folder" value="1">
            `;
            document.body.appendChild(form);
            form.submit();
        }
    }

    if (action === 'upload') {
        if (contextTargetType !== 'folder') return;
        document.getElementById('contextUploadWorkspace').value = contextWorkspace;
        document.getElementById('contextUploadFolderId').value = contextTargetId;
        document.getElementById('contextUploadCompanyId').value = contextCompanyId;
        document.getElementById('contextUploadInput').click();
    }

    if (action === 'download') {
        if (contextTargetType === 'file') {
            const link = document.querySelector('[data-file-id="' + contextTargetId + '"]');
            if (link) window.open(link.getAttribute('href'), '_blank');
        }
    }

    if (action === 'new_file') {
        alert('New File action usually means open upload dialog or create empty file record.');
    }
}

function submitContextUpload() {
    const form = document.getElementById('contextUploadForm');
    if (form) form.submit();
}

function escapeHtml(value) {
    return String(value)
        .replace(/&/g, '&amp;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');
}

function toggleRootFolderForm(event, workspace) {
    event.stopPropagation();

    const id = 'root-folder-form-' + workspace;
    const form = document.getElementById(id);

    if (!form) return;

    form.style.display = (form.style.display === 'none' || form.style.display === '')
        ? 'flex'
        : 'none';
}
function toggleWorkspaceMenu() {
    const menu = document.getElementById('workspaceMenu');
    if (!menu) return;

    menu.style.display = (menu.style.display === 'block') ? 'none' : 'block';
}

// close when clicking outside
document.addEventListener('click', function (e) {
    const switcher = document.querySelector('.workspace-switcher');
    const menu = document.getElementById('workspaceMenu');

    if (!switcher || !menu) return;

    if (!switcher.contains(e.target) && !menu.contains(e.target)) {
        menu.style.display = 'none';
    }
});


document.addEventListener('DOMContentLoaded', function () {
    let state = JSON.parse(localStorage.getItem('folderState') || '{}');

    Object.keys(state).forEach(id => {
        if (state[id]) {
            const el = document.getElementById('folder-' + id);
            const icon = document.getElementById('icon-' + id);

            if (el) el.style.display = 'block';
            if (icon) icon.textContent = '▾';
        }
    });

    const sidebar = document.getElementById('sidebar');
    if (sidebar) {
        const savedScroll = sessionStorage.getItem('sidebarScrollTop');
        if (savedScroll !== null) {
            sidebar.scrollTop = parseInt(savedScroll, 10) || 0;
        }

        sidebar.addEventListener('scroll', function () {
            sessionStorage.setItem('sidebarScrollTop', String(sidebar.scrollTop));
        });

        sidebar.querySelectorAll('a, button').forEach(el => {
            el.addEventListener('click', function () {
                sessionStorage.setItem('sidebarScrollTop', String(sidebar.scrollTop));
            });
        });
    }
});

function switchWorkspace(type, companyId = null) {
    let url = '';

    if (type === 'all') {
        url = 'my_documents.php?workspace=all&scope=all';
    } else if (type === 'personal') {
        url = 'my_documents.php?workspace=personal&scope=personal';
    } else if (type === 'company' && companyId) {
        url = 'my_documents.php?workspace=company&scope=company&company_id=' + companyId;
    }

    window.location.href = url;
}
</script>   