<?php
declare(strict_types=1);

$baseDir = realpath(__DIR__);
$requestedPath = $_GET['path'] ?? '';
$requestedPath = trim($requestedPath, '/');

$currentDir = realpath($baseDir . ($requestedPath ? DIRECTORY_SEPARATOR . $requestedPath : ''));

if ($currentDir === false || strpos($currentDir, $baseDir) !== 0 || !is_dir($currentDir)) {
    http_response_code(404);
    die('Nieprawidłowa ścieżka.');
}

/**
 * Podgląd plików jako tekst zamiast pobierania.
 * Przykład: ?view=katalog/test.sh
 */
$viewFile = $_GET['view'] ?? '';

if ($viewFile !== '') {
    $viewFile = trim($viewFile, '/');
    $fullFilePath = realpath($baseDir . DIRECTORY_SEPARATOR . $viewFile);

    if (
        $fullFilePath === false ||
        strpos($fullFilePath, $baseDir) !== 0 ||
        !is_file($fullFilePath)
    ) {
        http_response_code(404);
        die('Nieprawidłowy plik.');
    }

    $allowedPreview = [
        'txt',
        'sh',
        'log',
        'conf',
        'ini',
        'sql',
        'md',
        'yml',
        'yaml',
        'js',
        'css',
        'html',
        'htm',
        'py',
        'json',
        'xml',
        'csv'
    ];

    $ext = strtolower(pathinfo($fullFilePath, PATHINFO_EXTENSION));
    $fileName = basename($fullFilePath);

    if (in_array($ext, $allowedPreview, true)) {
        header('Content-Type: text/plain; charset=utf-8');
        header('Content-Disposition: inline; filename="' . addslashes($fileName) . '"');
        header('X-Content-Type-Options: nosniff');
        readfile($fullFilePath);
        exit;
    }

    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . addslashes($fileName) . '"');
    header('X-Content-Type-Options: nosniff');
    readfile($fullFilePath);
    exit;
}

function formatBytes(int $bytes): string
{
    if ($bytes < 1024) {
        return $bytes . ' B';
    }

    $units = ['KB', 'MB', 'GB', 'TB'];
    $size = $bytes / 1024;

    foreach ($units as $unit) {
        if ($size < 1024) {
            return number_format($size, 2, ',', ' ') . ' ' . $unit;
        }
        $size /= 1024;
    }

    return number_format($size, 2, ',', ' ') . ' PB';
}

function formatDate(int $timestamp): string
{
    return date('Y-m-d H:i:s', $timestamp);
}

function iconFor(string $name, bool $isDir): string
{
    if ($isDir) {
        return '📁';
    }

    $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));

    return match ($ext) {
        'jpg', 'jpeg', 'png', 'gif', 'webp', 'svg' => '🖼️',
        'pdf' => '📕',
        'zip', 'rar', '7z', 'tar', 'gz' => '🗜️',
        'mp3', 'wav', 'flac' => '🎵',
        'mp4', 'mkv', 'avi', 'mov' => '🎬',
        'php', 'js', 'css', 'html', 'py', 'sh', 'sql' => '🧾',
        'txt', 'md', 'log', 'ini', 'conf', 'yml', 'yaml', 'json', 'xml', 'csv' => '📄',
        default => '📄',
    };
}

function buildPathLink(string $path): string
{
    return '?path=' . rawurlencode(trim($path, '/'));
}

function buildViewLink(string $path): string
{
    return '?view=' . rawurlencode(trim($path, '/'));
}

$items = array_diff(scandir($currentDir), ['.', '..']);

$directories = [];
$files = [];

foreach ($items as $item) {
    $fullPath = $currentDir . DIRECTORY_SEPARATOR . $item;

    if (is_dir($fullPath)) {
        $directories[] = $item;
    } elseif (is_file($fullPath)) {
        $files[] = $item;
    }
}

natcasesort($directories);
natcasesort($files);

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

$breadcrumbs = [];
if ($relativePath !== '') {
    $parts = explode('/', $relativePath);
    $accumulated = '';
    foreach ($parts as $part) {
        $accumulated .= ($accumulated === '' ? '' : '/') . $part;
        $breadcrumbs[] = [
            'name' => $part,
            'path' => $accumulated
        ];
    }
}

$parentPath = '';
if ($relativePath !== '') {
    $parentPath = dirname($relativePath);
    if ($parentPath === '.') {
        $parentPath = '';
    }
}
?>
<!DOCTYPE html>
<html lang="pl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Index of /<?= htmlspecialchars($relativePath ?: '') ?></title>
    <style>
        * { box-sizing: border-box; }
        body {
            margin: 0;
            padding: 30px;
            background: #0f172a;
            color: #e2e8f0;
            font-family: Arial, sans-serif;
        }
        .wrap {
            max-width: 1100px;
            margin: 0 auto;
        }
        h1 {
            margin: 0 0 10px;
            font-size: 28px;
        }
        .breadcrumbs {
            margin-bottom: 25px;
            color: #94a3b8;
            font-size: 14px;
        }
        .breadcrumbs a {
            color: #7dd3fc;
            text-decoration: none;
        }
        .breadcrumbs a:hover {
            text-decoration: underline;
        }
        .card {
            background: #111827;
            border: 1px solid #1f2937;
            border-radius: 14px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0,0,0,0.25);
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        thead {
            background: #1e293b;
        }
        th, td {
            padding: 14px 16px;
            text-align: left;
        }
        th {
            font-size: 13px;
            text-transform: uppercase;
            letter-spacing: 0.04em;
            color: #94a3b8;
        }
        tbody tr {
            border-top: 1px solid #1f2937;
        }
        tbody tr:hover {
            background: #0b1220;
        }
        a.filelink {
            color: #e2e8f0;
            text-decoration: none;
        }
        a.filelink:hover {
            color: #7dd3fc;
        }
        .icon {
            width: 34px;
            display: inline-block;
        }
        .muted {
            color: #94a3b8;
        }
        .right {
            text-align: right;
            white-space: nowrap;
        }
        .empty {
            padding: 24px 16px;
            color: #94a3b8;
        }
        .footer {
            margin-top: 16px;
            color: #64748b;
            font-size: 13px;
        }
        @media (max-width: 700px) {
            body { padding: 15px; }
            th:nth-child(3), td:nth-child(3) {
                display: none;
            }
        }
        .hero {
            background: linear-gradient(135deg, #111827, #1e293b);
            border: 1px solid #1f2937;
            border-radius: 16px;
            padding: 24px;
            margin-bottom: 24px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.25);
        }

        .brand {
            display: flex;
            align-items: center;
            gap: 18px;
            margin-bottom: 20px;
        }

        .logo {
            width: 72px;
            height: auto;
            display: block;
        }

        .brand-name {
            font-size: 28px;
            font-weight: 700;
            color: #f8fafc;
            line-height: 1.1;
        }

        .brand-tagline {
            font-size: 14px;
            color: #94a3b8;
            margin-top: 4px;
        }

        .hero-text h1 {
            margin: 0 0 8px;
            font-size: 30px;
            color: #e2e8f0;
        }

        .hero-text p {
            margin: 0;
            color: #cbd5e1;
            font-size: 15px;
        }
    </style>
</head>
<body>
<div class="wrap">

<div class="hero">
    <div class="brand">
        <img src="https://pro-admin.pl/5502logo-1_preview_rev_1.png" alt="PRO-Admin Logo" class="logo">
        <div>
            <div class="brand-name">PRO-Admin</div>
            <div class="brand-tagline">Administracja serwerami i infrastruktura IT</div>
        </div>
    </div>

    <div class="hero-text">
        <h1>Index of /<?= htmlspecialchars($relativePath) ?></h1>
        <p>Uporządkowany dostęp do plików, kopii zapasowych i zasobów systemowych.</p>
    </div>
</div>

    <div class="breadcrumbs">
        <a href="?">root</a>
        <?php foreach ($breadcrumbs as $crumb): ?>
            / <a href="<?= htmlspecialchars(buildPathLink($crumb['path'])) ?>"><?= htmlspecialchars($crumb['name']) ?></a>
        <?php endforeach; ?>
    </div>

    <div class="card">
        <table>
            <thead>
                <tr>
                    <th>Nazwa</th>
                    <th class="right">Rozmiar</th>
                    <th>Data modyfikacji</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($relativePath !== ''): ?>
                    <tr>
                        <td>
                            <a class="filelink" href="<?= htmlspecialchars(buildPathLink($parentPath)) ?>">
                                <span class="icon">⬅️</span> ..
                            </a>
                        </td>
                        <td class="right muted">-</td>
                        <td class="muted">-</td>
                    </tr>
                <?php endif; ?>

                <?php foreach ($directories as $dir): ?>
                    <?php
                        $dirPath = $currentDir . DIRECTORY_SEPARATOR . $dir;
                        $childPath = ltrim(($relativePath ? $relativePath . '/' : '') . $dir, '/');
                    ?>
                    <tr>
                        <td>
                            <a class="filelink" href="<?= htmlspecialchars(buildPathLink($childPath)) ?>">
                                <span class="icon"><?= iconFor($dir, true) ?></span>
                                <?= htmlspecialchars($dir) ?>
                            </a>
                        </td>
                        <td class="right muted">katalog</td>
                        <td><?= htmlspecialchars(formatDate(filemtime($dirPath))) ?></td>
                    </tr>
                <?php endforeach; ?>

                <?php foreach ($files as $file): ?>
                    <?php
                        $filePath = $currentDir . DIRECTORY_SEPARATOR . $file;
                        $fileUrl = ($relativePath ? $relativePath . '/' : '') . $file;
                    ?>
                    <tr>
                        <td>
                            <a class="filelink" href="<?= htmlspecialchars(buildViewLink($fileUrl)) ?>">
                                <span class="icon"><?= iconFor($file, false) ?></span>
                                <?= htmlspecialchars($file) ?>
                            </a>
                        </td>
                        <td class="right"><?= htmlspecialchars(formatBytes(filesize($filePath))) ?></td>
                        <td><?= htmlspecialchars(formatDate(filemtime($filePath))) ?></td>
                    </tr>
                <?php endforeach; ?>

                <?php if (empty($directories) && empty($files)): ?>
                    <tr>
                        <td colspan="3" class="empty">Ten katalog jest pusty.</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <div class="footer">
        PRO-Admin.pl 2026
    </div>
</div>
</body>
</html>
