<?php
$dir = isset($_GET['dir']) ? realpath('./' . $_GET['dir']) : realpath('.');
$baseDir = realpath('.');

// Security: prevent directory traversal outside base
if ($dir === false || strpos($dir, $baseDir) !== 0) {
    $dir = $baseDir;
}

$relativePath = ltrim(str_replace($baseDir, '', $dir), DIRECTORY_SEPARATOR);

// Handle file viewing
if (isset($_GET['file'])) {
    $filePath = realpath('./' . $_GET['file']);
    if ($filePath && strpos($filePath, $baseDir) === 0 && is_file($filePath)) {
        $mime = mime_content_type($filePath);
        header('Content-Type: ' . $mime);
        readfile($filePath);
        exit;
    }
}

// Get directory contents
$items = scandir($dir);
$folders = [];
$files = [];

foreach ($items as $item) {
    if ($item === '.') continue;
    $fullPath = $dir . DIRECTORY_SEPARATOR . $item;
    $relPath = ltrim(str_replace($baseDir, '', $fullPath), DIRECTORY_SEPARATOR);

    if (is_dir($fullPath)) {
        $folders[] = ['name' => $item, 'path' => $relPath];
    } else {
        $size = filesize($fullPath);
        $modified = filemtime($fullPath);
        $ext = strtolower(pathinfo($item, PATHINFO_EXTENSION));
        $files[] = [
            'name'     => $item,
            'path'     => $relPath,
            'size'     => $size,
            'modified' => $modified,
            'ext'      => $ext,
        ];
    }
}

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

function fileIcon($ext) {
    $icons = [
        'pdf'  => '📄', 'doc' => '📝', 'docx' => '📝', 'txt' => '📃',
        'xls'  => '📊', 'xlsx' => '📊', 'csv' => '📊',
        'ppt'  => '📋', 'pptx' => '📋',
        'jpg'  => '🖼️', 'jpeg' => '🖼️', 'png' => '🖼️', 'gif' => '🖼️',
        'svg'  => '🖼️', 'webp' => '🖼️', 'ico' => '🖼️',
        'mp3'  => '🎵', 'wav' => '🎵', 'ogg' => '🎵', 'flac' => '🎵',
        'mp4'  => '🎬', 'avi' => '🎬', 'mov' => '🎬', 'mkv' => '🎬',
        'zip'  => '🗜️', 'tar' => '🗜️', 'gz' => '🗜️', 'rar' => '🗜️',
        'php'  => '⚙️', 'js' => '⚙️', 'ts' => '⚙️', 'py' => '⚙️',
        'html' => '🌐', 'htm' => '🌐', 'css' => '🎨',
        'json' => '📦', 'xml' => '📦', 'yaml' => '📦', 'yml' => '📦',
        'sh'   => '💻', 'bat' => '💻', 'cmd' => '💻',
        'sql'  => '🗃️',
    ];
    return $icons[$ext] ?? '📄';
}

$breadcrumbs = [];
if ($relativePath) {
    $parts = explode(DIRECTORY_SEPARATOR, $relativePath);
    $cumulative = '';
    foreach ($parts as $part) {
        $cumulative .= ($cumulative ? DIRECTORY_SEPARATOR : '') . $part;
        $breadcrumbs[] = ['name' => $part, 'path' => $cumulative];
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>📁 <?= htmlspecialchars($relativePath ?: 'Root') ?></title>
    <style>
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

        body {
            font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
            background: #0f1117;
            color: #e2e8f0;
            min-height: 100vh;
            padding: 2rem 1rem;
        }

        .container {
            max-width: 960px;
            margin: 0 auto;
        }

        header {
            margin-bottom: 2rem;
        }

        header h1 {
            font-size: 1.5rem;
            font-weight: 700;
            color: #f8fafc;
            margin-bottom: 0.75rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        /* Breadcrumbs */
        .breadcrumb {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            gap: 0.25rem;
            font-size: 0.85rem;
            color: #94a3b8;
        }

        .breadcrumb a {
            color: #60a5fa;
            text-decoration: none;
            padding: 0.2rem 0.4rem;
            border-radius: 4px;
            transition: background 0.15s;
        }

        .breadcrumb a:hover { background: #1e293b; }

        .breadcrumb .sep { color: #475569; }

        /* Stats bar */
        .stats {
            display: flex;
            gap: 1.5rem;
            font-size: 0.8rem;
            color: #64748b;
            margin-bottom: 1.5rem;
            padding: 0.75rem 1rem;
            background: #1e293b;
            border-radius: 8px;
            border: 1px solid #334155;
        }

        .stats span { display: flex; align-items: center; gap: 0.3rem; }

        /* File table */
        .file-table {
            background: #1a1f2e;
            border: 1px solid #2d3748;
            border-radius: 12px;
            overflow: hidden;
        }

        .file-table-header {
            display: grid;
            grid-template-columns: 1fr 100px 160px;
            padding: 0.75rem 1.25rem;
            background: #161b27;
            font-size: 0.75rem;
            font-weight: 600;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            border-bottom: 1px solid #2d3748;
        }

        .file-row {
            display: grid;
            grid-template-columns: 1fr 100px 160px;
            padding: 0.75rem 1.25rem;
            border-bottom: 1px solid #1e2535;
            transition: background 0.15s;
            align-items: center;
        }

        .file-row:last-child { border-bottom: none; }
        .file-row:hover { background: #1e2d45; }

        .file-row.folder { }

        .file-name {
            display: flex;
            align-items: center;
            gap: 0.65rem;
            min-width: 0;
        }

        .file-icon { font-size: 1.1rem; flex-shrink: 0; }

        .file-name a {
            color: #93c5fd;
            text-decoration: none;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            font-size: 0.9rem;
            transition: color 0.15s;
        }

        .file-row.folder .file-name a { color: #fbbf24; }

        .file-name a:hover { color: #fff; text-decoration: underline; }

        .file-size {
            font-size: 0.82rem;
            color: #64748b;
            text-align: right;
        }

        .file-date {
            font-size: 0.82rem;
            color: #64748b;
            text-align: right;
        }

        .ext-badge {
            font-size: 0.65rem;
            font-weight: 700;
            padding: 0.1rem 0.35rem;
            border-radius: 3px;
            background: #1e3a5f;
            color: #60a5fa;
            text-transform: uppercase;
            letter-spacing: 0.03em;
            flex-shrink: 0;
        }

        .section-label {
            padding: 0.5rem 1.25rem;
            font-size: 0.72rem;
            font-weight: 700;
            color: #475569;
            text-transform: uppercase;
            letter-spacing: 0.08em;
            background: #161b27;
            border-bottom: 1px solid #1e2535;
        }

        .empty {
            text-align: center;
            padding: 3rem;
            color: #475569;
            font-size: 0.9rem;
        }

        @media (max-width: 600px) {
            .file-table-header,
            .file-row {
                grid-template-columns: 1fr auto;
            }
            .file-date { display: none; }
            .file-table-header .col-date { display: none; }
        }
    </style>
</head>
<body>
<div class="container">
    <header>
        <h1>📁 File Browser</h1>
        <nav class="breadcrumb">
            <a href="?">Root</a>
            <?php foreach ($breadcrumbs as $crumb): ?>
                <span class="sep">/</span>
                <a href="?dir=<?= urlencode($crumb['path']) ?>"><?= htmlspecialchars($crumb['name']) ?></a>
            <?php endforeach; ?>
        </nav>
    </header>

    <div class="stats">
        <span>📁 <?= count($folders) ?> folder<?= count($folders) !== 1 ? 's' : '' ?></span>
        <span>📄 <?= count($files) ?> file<?= count($files) !== 1 ? 's' : '' ?></span>
        <?php if ($relativePath): ?>
            <span>📍 /<?= htmlspecialchars($relativePath) ?></span>
        <?php endif; ?>
    </div>

    <div class="file-table">
        <div class="file-table-header">
            <div>Name</div>
            <div style="text-align:right">Size</div>
            <div class="col-date" style="text-align:right">Modified</div>
        </div>

        <?php if (!$relativePath && empty($folders) && empty($files)): ?>
            <div class="empty">This directory is empty.</div>
        <?php endif; ?>

        <?php if ($relativePath): ?>
            <?php
                $parentPath = dirname($relativePath);
                $parentLink = ($parentPath === '.' || $parentPath === '') ? '?' : '?dir=' . urlencode($parentPath);
            ?>
            <div class="file-row folder">
                <div class="file-name">
                    <span class="file-icon">⬆️</span>
                    <a href="<?= $parentLink ?>">.. (Parent Directory)</a>
                </div>
                <div class="file-size">—</div>
                <div class="file-date">—</div>
            </div>
        <?php endif; ?>

        <?php if (!empty($folders)): ?>
            <div class="section-label">Folders</div>
            <?php foreach ($folders as $folder): ?>
                <div class="file-row folder">
                    <div class="file-name">
                        <span class="file-icon">📁</span>
                        <a href="?dir=<?= urlencode($folder['path']) ?>"><?= htmlspecialchars($folder['name']) ?></a>
                    </div>
                    <div class="file-size">—</div>
                    <div class="file-date">—</div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>

        <?php if (!empty($files)): ?>
            <div class="section-label">Files</div>
            <?php foreach ($files as $file): ?>
                <div class="file-row">
                    <div class="file-name">
                        <span class="file-icon"><?= fileIcon($file['ext']) ?></span>
                        <?php if ($file['ext']): ?>
                            <span class="ext-badge"><?= htmlspecialchars($file['ext']) ?></span>
                        <?php endif; ?>
                        <a href="?file=<?= urlencode($file['path']) ?>" target="_blank">
                            <?= htmlspecialchars($file['name']) ?>
                        </a>
                    </div>
                    <div class="file-size"><?= formatSize($file['size']) ?></div>
                    <div class="file-date"><?= date('M j, Y  H:i', $file['modified']) ?></div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>
</body>
</html>
