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

error_reporting(E_ALL);
ini_set('display_errors', 0);

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

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

// Visualização de Preview de Imagem ou Download
if (isset($_GET['file']) && !empty($_GET['file'])) {
    $fileName = basename($_GET['file']);
    $filePath = realpath($currentPath . DIRECTORY_SEPARATOR . $fileName);
    
    if ($filePath && strpos($filePath, $rootFolder) === 0 && is_file($filePath) && is_readable($filePath)) {
        $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
        $isImage = in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg']);
        
        if (isset($_GET['preview']) && $isImage) {
            $mimeTypes = [
                'jpg' => 'image/jpeg',
                'jpeg' => 'image/jpeg',
                'png' => 'image/png',
                'gif' => 'image/gif',
                'webp' => 'image/webp',
                'svg' => 'image/svg+xml'
            ];
            header('Content-Type: ' . ($mimeTypes[$ext] ?? 'application/octet-stream'));
            header('Content-Length: ' . filesize($filePath));
            readfile($filePath);
            exit;
        }
        
        if (isset($_GET['download'])) {
            if (ob_get_level()) ob_end_clean();
            header('Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="' . $fileName . '"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($filePath));
            readfile($filePath);
            exit;
        }
    }
}

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

if (is_readable($currentPath) && ($handle = opendir($currentPath))) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry === '.' || $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';$isImage = false;

            if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'])) {$type = 'image';
                $icon = 'fa-file-image text-emerald-400';$isImage = true;
            } 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';
            }

            $previewUrl =$isImage ? '?dir=' . urlencode($currentSubPath) . '&file=' . urlencode($entry) . '&preview=1' : '';

            $files[] = [
                'name' => $entry,
                'path' => $relativePath,
                'type' => $type,
                'size' => @filesize($fullPath) ?: 0,
                'size_formatted' => formatBytes(@filesize($fullPath) ?: 0),
                'date' => date('d/m/Y H:i', @filemtime($fullPath) ?: time()),
                'icon' => $icon,
                'is_image' => $isImage,
                'preview_url' => $previewUrl
            ];
        }
    }
    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) {
    if ($bytes <= 0) return '0 B';
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];$pow = floor(log($bytes) / 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 - Com Preview</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">Com Preview de Imagens</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): ?>
            <?php 
                $parentDir = dirname($currentSubPath);
                $parentParam = ($parentDir === '.' || $parentDir === DIRECTORY_SEPARATOR) ? '' :$parentDir;
            ?>
            <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($parentParam); ?>" 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">
                                            <?php if ($file['is_image']): ?>
                                                <div class="w-9 h-9 rounded-lg bg-slate-950 border border-slate-800 overflow-hidden flex-shrink-0 cursor-pointer hover:scale-105 transition" onclick="openModal('<?php echo $file['preview_url']; ?>', '<?php echo htmlspecialchars($file['name'], ENT_QUOTES); ?>')">
                                                    <img src="<?php echo $file['preview_url']; ?>" alt="<?php echo htmlspecialchars($file['name']); ?>" class="w-full h-full object-cover">
                                                </div>
                                            <?php else: ?>
                                                <div class="w-9 h-9 rounded-lg bg-slate-950 border border-slate-800 flex items-center justify-center flex-shrink-0">
                                                    <i class="fa-solid <?php echo $file['icon']; ?> text-base"></i>
                                                </div>
                                            <?php endif; ?>
                                            <span class="truncate max-w-[180px] sm:max-w-xs md:max-w-md">
                                                <?php if ($file['is_image']): ?>
                                                    <a href="#" onclick="openModal('<?php echo $file['preview_url']; ?>', '<?php echo htmlspecialchars($file['name'], ENT_QUOTES); ?>'); return false;" class="hover:text-blue-400 transition">
                                                        <?php echo htmlspecialchars($file['name']); ?>
                                                    </a>
                                                <?php else: ?>
                                                    <?php echo htmlspecialchars($file['name']); ?>
                                                <?php endif; ?>
                                            </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); ?>&file=<?php echo urlencode($file['name']); ?>&download=1" 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>

    <!-- Modal de Preview de Imagem -->
    <div id="imageModal" class="fixed inset-0 z-50 bg-slate-950/80 backdrop-blur-sm hidden flex items-center justify-center p-4" onclick="closeModal()">
        <div class="relative max-w-4xl max-h-[90vh] bg-slate-900 border border-slate-800 rounded-2xl overflow-hidden shadow-2xl flex flex-col" onclick="event.stopPropagation()">
            <div class="flex items-center justify-between px-4 py-3 border-b border-slate-800 bg-slate-950/50">
                <h3 id="modalTitle" class="text-xs font-medium text-slate-300 truncate max-w-md">Preview</h3>
                <button onclick="closeModal()" class="text-slate-400 hover:text-white transition p-1">
                    <i class="fa-solid fa-xmark text-lg"></i>
                </button>
            </div>
            <div class="p-4 flex items-center justify-center overflow-auto bg-slate-950">
                <img id="modalImage" src="" alt="Preview" class="max-h-[75vh] max-w-full object-contain rounded-lg">
            </div>
        </div>
    </div>

    <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';
            }
        }

        function openModal(url, title) {
            document.getElementById('modalImage').src = url;
            document.getElementById('modalTitle').textContent = title;
            document.getElementById('imageModal').classList.remove('hidden');
            document.getElementById('imageModal').classList.add('flex');
        }

        function closeModal() {
            document.getElementById('imageModal').classList.remove('flex');
            document.getElementById('imageModal').classList.add('hidden');
            document.getElementById('modalImage').src = '';
        }

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

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