<?php
/**
 * Gerenciador de Arquivos Local (PHP)
 * Dark & Clean Theme
 */

$rootFolder = __DIR__;$currentSubPath = isset($_GET['dir']) ? trim($_GET['dir'], DIRECTORY_SEPARATOR) : '';

// Segurança básica contra Directory Traversal
$currentPath = realpath($rootFolder . DIRECTORY_SEPARATOR . $currentSubPath);
if ($currentPath === false || strpos($currentPath, realpath($rootFolder)) !== 0) {
    $currentPath =$rootFolder;
    $currentSubPath = '';
}

// Download de arquivo
if (isset($_GET['download'])) {$fileToDownload = realpath($currentPath . DIRECTORY_SEPARATOR . $_GET['download']);
    if ($fileToDownload && strpos($fileToDownload, $rootFolder) === 0 && is_file($fileToDownload)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . basename($fileToDownload) . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($fileToDownload));
        readfile($fileToDownload);
        exit;
    }
}

$folders = [];$files = [];

if ($handle = opendir($currentPath)) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry === '.' \vert{}\vert{}$entry === '..') continue;
        
        $fullPath = $currentPath . DIRECTORY_SEPARATOR . $entry;
        $relativePath = ($currentSubPath ? $currentSubPath . DIRECTORY_SEPARATOR : '') . $entry;
        
        if (is_dir($fullPath)) {$folders[] = [
                'name' => $entry,
                'path' => $relativePath
            ];
        } elseif (is_file($fullPath)) {
            $ext = strtolower(pathinfo($entry, PATHINFO_EXTENSION));
            $type = 'other';$icon = 'fa-file text-slate-400';

            if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'])) {
                $type = 'image';$icon = 'fa-file-image text-emerald-400';
            } elseif (in_array($ext, ['mp3', 'wav', 'ogg', 'flac', 'm4a'])) {$type = 'audio';
                $icon = 'fa-file-audio text-amber-400'; } elseif (in_array($ext, ['mp4', 'mkv', 'avi', 'mov', 'webm'])) {
                $type = 'video';$icon = 'fa-file-video text-rose-400';
            } elseif ($ext === 'pdf') {$type = 'pdf';
                $icon = 'fa-file-pdf text-red-400'; } elseif (in_array($ext, ['txt', 'md', 'doc', 'docx', 'rtf'])) {
                $type = 'text';$icon = 'fa-file-lines text-blue-400';
            } elseif (in_array($ext, ['php', 'js', 'html', 'css', 'json', 'py', 'sql'])) {$type = 'code';
                $icon = 'fa-file-code text-indigo-400'; } elseif (in_array($ext, ['zip', 'rar', 'tar', 'gz', '7z'])) {
                $type = 'archive';$icon = 'fa-file-zipper text-purple-400';
            }

            $files[] = [
                'name' => $entry,
                'path' => $relativePath,
                'type' => $type,
                'size' => filesize($fullPath),
                'size_formatted' => formatBytes(filesize($fullPath)),
                'date' => date('d/m/Y H:i', filemtime($fullPath)),
                'icon' => $icon
            ];
        }
    }
    closedir($handle);
}

usort($folders, fn($a,$b) => strcasecmp($a['name'],$b['name']));
usort($files, fn($a,$b) => strcasecmp($a['name'],$b['name']));

function formatBytes($bytes, $precision = 2) {$units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));$pow = min($pow, count($units) - 1);
    $bytes /= (1 << (10 * $pow));
    return round($bytes,$precision) . ' ' . $units[$pow];
}
?>
<!DOCTYPE html>
<html lang="pt-BR" class="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>FileBrowser PHP - Servidor Local</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <script>
        tailwind.config = {
            darkMode: 'class',
            theme: {
                extend: {
                    fontFamily: { sans: ['Inter', 'sans-serif'] }
                }
            }
        }
    </script>
</head>
<body class="bg-slate-950 text-slate-100 min-h-screen font-sans flex flex-col antialiased">

    <header class="bg-slate-900 border-b border-slate-800/80 sticky top-0 z-30 backdrop-blur-md bg-slate-900/90">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-16 flex items-center justify-between gap-4">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-blue-600 flex items-center justify-center text-white shadow-lg shadow-blue-500/20">
                    <i class="fa-solid fa-folder-open text-lg"></i>
                </div>
                <div>
                    <h1 class="font-bold text-slate-100 leading-tight">FileBrowser</h1>
                    <p class="text-xs text-slate-400">Varredura em Pasta Real</p>
                </div>
            </div>

            <div class="flex-1 max-w-xl mx-4">
                <div class="relative">
                    <span class="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none text-slate-400">
                        <i class="fa-solid fa-search"></i>
                    </span>
                    <input type="text" id="searchInput" placeholder="Pesquisar arquivos..." class="w-full pl-10 pr-4 py-2 bg-slate-950/80 border border-slate-800 rounded-xl text-sm text-slate-100 placeholder-slate-500 focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition">
                </div>
            </div>

            <div class="flex items-center gap-3">
                <button id="toggleFoldersBtn" onclick="toggleFoldersVisibility()" class="flex items-center gap-2 px-3.5 py-2 bg-slate-800 hover:bg-slate-700/80 text-slate-200 text-sm font-medium rounded-xl border border-slate-700/60 transition shadow-sm">
                    <i id="folderIcon" class="fa-solid fa-eye text-slate-400"></i>
                    <span id="folderBtnText" class="hidden sm:inline">Ocultar Pastas</span>
                </button>
            </div>
        </div>
    </header>

    <main class="flex-1 max-w-7xl w-full mx-auto px-4 sm:px-6 lg:px-8 py-6 flex flex-col gap-6">
        
        <?php if ($currentSubPath): ?>
            <div class="flex items-center gap-2 text-sm">
                <a href="?" class="text-slate-400 hover:text-slate-200 transition flex items-center gap-1.5 bg-slate-900 px-3 py-1.5 rounded-lg border border-slate-800">
                    <i class="fa-solid fa-house"></i> Raiz
                </a>
                <span class="text-slate-600">/</span>
                <span class="text-slate-200 font-medium px-2 py-1 bg-slate-900/60 rounded-lg border border-slate-800/60"><?php echo htmlspecialchars($currentSubPath); ?></span>
                <a href="?dir=<?php echo urlencode(dirname($currentSubPath) === '.' ? '' : dirname($currentSubPath)); ?>" class="ml-auto text-xs text-blue-400 hover:underline flex items-center gap-1">
                    <i class="fa-solid fa-arrow-left"></i> Voltar Pasta Acima
                </a>
            </div>
        <?php endif; ?>

        <section class="flex flex-col gap-3">
            <div class="flex items-center justify-between">
                <h2 class="text-xs font-semibold uppercase tracking-wider text-slate-400">Filtrar por Tipo</h2>
                <span id="fileCount" class="text-xs text-slate-500">0 arquivos</span>
            </div>
            
            <div id="filterContainer" class="flex flex-wrap gap-2">
                <button onclick="filterByType('all')" class="filter-btn active px-3.5 py-1.5 rounded-xl text-xs font-medium bg-blue-600 text-white shadow-md shadow-blue-600/20 transition flex items-center gap-2">
                    <i class="fa-solid fa-border-all"></i> Todos
                </button>
                <button onclick="filterByType('image')" class="filter-btn px-3.5 py-1.5 rounded-xl text-xs font-medium bg-slate-900 border border-slate-800 text-slate-300 hover:bg-slate-800 hover:text-white transition flex items-center gap-2">
                    <i class="fa-solid fa-image text-emerald-400"></i> Imagens
                </button>
                <button onclick="filterByType('audio')" class="filter-btn px-3.5 py-1.5 rounded-xl text-xs font-medium bg-slate-900 border border-slate-800 text-slate-300 hover:bg-slate-800 hover:text-white transition flex items-center gap-2">
                    <i class="fa-solid fa-music text-amber-400"></i> Áudios
                </button>
                <button onclick="filterByType('video')" class="filter-btn px-3.5 py-1.5 rounded-xl text-xs font-medium bg-slate-900 border border-slate-800 text-slate-300 hover:bg-slate-800 hover:text-white transition flex items-center gap-2">
                    <i class="fa-solid fa-video text-rose-400"></i> Vídeos
                </button>
                <button onclick="filterByType('pdf')" class="filter-btn px-3.5 py-1.5 rounded-xl text-xs font-medium bg-slate-900 border border-slate-800 text-slate-300 hover:bg-slate-800 hover:text-white transition flex items-center gap-2">
                    <i class="fa-solid fa-file-pdf text-red-400"></i> PDFs
                </button>
                <button onclick="filterByType('text')" class="filter-btn px-3.5 py-1.5 rounded-xl text-xs font-medium bg-slate-900 border border-slate-800 text-slate-300 hover:bg-slate-800 hover:text-white transition flex items-center gap-2">
                    <i class="fa-solid fa-file-lines text-blue-400"></i> Textos / Docs
                </button>
                <button onclick="filterByType('code')" class="filter-btn px-3.5 py-1.5 rounded-xl text-xs font-medium bg-slate-900 border border-slate-800 text-slate-300 hover:bg-slate-800 hover:text-white transition flex items-center gap-2">
                    <i class="fa-solid fa-code text-indigo-400"></i> Código
                </button>
                <button onclick="filterByType('archive')" class="filter-btn px-3.5 py-1.5 rounded-xl text-xs font-medium bg-slate-900 border border-slate-800 text-slate-300 hover:bg-slate-800 hover:text-white transition flex items-center gap-2">
                    <i class="fa-solid fa-file-zipper text-purple-400"></i> Compactados
                </button>
            </div>
        </section>

        <section id="foldersSection" class="flex flex-col gap-3 transition-all duration-300">
            <h2 class="text-xs font-semibold uppercase tracking-wider text-slate-400">Pastas</h2>
            <?php if (empty($folders)): ?>
                <p class="text-xs text-slate-500 italic bg-slate-900/40 p-3 rounded-xl border border-slate-900">Nenhuma subpasta encontrada.</p>
            <?php else: ?>
                <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-3">
                    <?php foreach ($folders as$folder): ?>
                        <a href="?dir=<?php echo urlencode($folder['path']); ?>" class="bg-slate-900 border border-slate-800 hover:border-slate-700 p-3.5 rounded-xl flex items-center gap-3 transition group">
                            <i class="fa-solid fa-folder text-blue-500 text-xl group-hover:scale-110 transition"></i>
                            <div class="overflow-hidden">
                                <p class="text-xs font-medium text-slate-200 truncate"><?php echo htmlspecialchars($folder['name']); ?></p>
                                <p class="text-[10px] text-slate-500">Pasta</p>
                            </div>
                        </a>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </section>

        <section class="flex flex-col gap-3 flex-1">
            <h2 class="text-xs font-semibold uppercase tracking-wider text-slate-400">Arquivos</h2>
            <div class="bg-slate-900 border border-slate-800 rounded-2xl overflow-hidden shadow-xl flex-1 flex flex-col">
                <div class="overflow-x-auto flex-1">
                    <table class="w-full text-left border-collapse">
                        <thead>
                            <tr class="border-b border-slate-800 text-xs text-slate-400 bg-slate-950/50">
                                <th class="py-3 px-4 font-medium">Nome</th>
                                <th class="py-3 px-4 font-medium hidden sm:table-cell">Tipo</th>
                                <th class="py-3 px-4 font-medium hidden md:table-cell">Tamanho</th>
                                <th class="py-3 px-4 font-medium hidden lg:table-cell">Modificado</th>
                                <th class="py-3 px-4 font-medium text-right">Ação</th>
                            </tr>
                        </thead>
                        <tbody id="fileTableBody" class="divide-y divide-slate-800/60 text-sm">
                            <?php if (empty($files)): ?>
                                <tr class="no-file-row">
                                    <td colspan="5" class="py-12 text-center text-slate-500">
                                        <div class="flex flex-col items-center justify-center">
                                            <i class="fa-solid fa-folder-open text-4xl mb-3"></i>
                                            <p class="text-sm font-medium">Nenhum arquivo nesta pasta</p>
                                        </div>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($files as$file): ?>
                                    <tr class="file-row hover:bg-slate-800/40 transition" data-type="<?php echo $file['type']; ?>" data-name="<?php echo strtolower($file['name']); ?>">
                                        <td class="py-3 px-4 font-medium text-slate-200 flex items-center gap-3">
                                            <i class="fa-solid <?php echo $file['icon']; ?> text-lg"></i>
                                            <span class="truncate max-w-[200px] sm:max-w-xs md:max-w-md"><?php echo htmlspecialchars($file['name']); ?></span>
                                        </td>
                                        <td class="py-3 px-4 text-xs text-slate-400 uppercase tracking-wider hidden sm:table-cell"><?php echo $file['type']; ?></td>
                                        <td class="py-3 px-4 text-xs text-slate-400 hidden md:table-cell"><?php echo $file['size_formatted']; ?></td>
                                        <td class="py-3 px-4 text-xs text-slate-400 hidden lg:table-cell"><?php echo $file['date']; ?></td>
                                        <td class="py-3 px-4 text-right">
                                            <a href="?dir=<?php echo urlencode($currentSubPath); ?>&download=<?php echo urlencode($file['name']); ?>" class="inline-flex items-center gap-1.5 px-3 py-1.5 bg-blue-600/10 hover:bg-blue-600 text-blue-400 hover:text-white text-xs font-medium rounded-lg border border-blue-500/20 transition shadow-sm">
                                                <i class="fa-solid fa-download"></i>
                                                <span class="hidden sm:inline">Baixar</span>
                                            </a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                <div id="noResults" class="hidden flex-col items-center justify-center p-12 text-center text-slate-500">
                    <i class="fa-solid fa-magnifying-glass text-4xl mb-3"></i>
                    <p class="text-sm font-medium">Nenhum arquivo corresponde à busca ou filtro</p>
                </div>
            </div>
        </section>

    </main>

    <script>
        let currentFilter = 'all';
        let searchQuery = '';
        let foldersHidden = false;

        function filterFiles() {
            const rows = document.querySelectorAll('.file-row');
            const noResults = document.getElementById('noResults');
            let visibleCount = 0;

            rows.forEach(row => {
                const type = row.getAttribute('data-type');
                const name = row.getAttribute('data-name');

                const matchesType = currentFilter === 'all' || type === currentFilter;
                const matchesSearch = name.includes(searchQuery.toLowerCase());

                if (matchesType && matchesSearch) {
                    row.style.display = '';
                    visibleCount++;
                } else {
                    row.style.display = 'none';
                }
            });

            document.getElementById('fileCount').textContent = `${visibleCount} ${visibleCount === 1 ? 'arquivo' : 'arquivos'}`;

            if (visibleCount === 0 && rows.length > 0) {
                noResults.classList.remove('hidden');
                noResults.classList.add('flex');
            } else {
                noResults.classList.remove('flex');
                noResults.classList.add('hidden');
            }
        }

        function filterByType(type) {
            currentFilter = type;
            document.querySelectorAll('.filter-btn').forEach(btn => {
                btn.classList.remove('active', 'bg-blue-600', 'text-white', 'shadow-md', 'shadow-blue-600/20');
                btn.classList.add('bg-slate-900', 'border', 'border-slate-800', 'text-slate-300');
            });
            event.currentTarget.classList.remove('bg-slate-900', 'border', 'border-slate-800', 'text-slate-300');
            event.currentTarget.classList.add('active', 'bg-blue-600', 'text-white', 'shadow-md', 'shadow-blue-600/20');
            filterFiles();
        }

        function toggleFoldersVisibility() {
            foldersHidden = !foldersHidden;
            const section = document.getElementById('foldersSection');
            const icon = document.getElementById('folderIcon');
            const text = document.getElementById('folderBtnText');

            if (foldersHidden) {
                section.style.opacity = '0';
                section.style.height = '0';
                section.style.overflow = 'hidden';
                section.style.marginBottom = '0';
                icon.className = 'fa-solid fa-eye-slash text-slate-400';
                text.textContent = 'Exibir Pastas';
            } else {
                section.style.opacity = '1';
                section.style.height = 'auto';
                section.style.overflow = 'visible';
                section.style.marginBottom = '';
                icon.className = 'fa-solid fa-eye text-slate-400';
                text.textContent = 'Ocultar Pastas';
            }
        }

        document.getElementById('searchInput').addEventListener('input', (e) => {
            searchQuery = e.target.value;
            filterFiles();
        });

        window.addEventListener('DOMContentLoaded', () => {
            filterFiles();
        });
    </script>
</body>
</html>