<?php
session_start();

$baseDir = __DIR__;
$envPassword = getenv('ADMIN_DIR_PASSWORD') ?: 'admin159753';
$passwordConfigured = $envPassword !== '';

function humanSize($bytes): string
{
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $unitIndex = 0;
    $size = (float) $bytes;

    while ($size >= 1024 && $unitIndex < count($units) - 1) {
        $size /= 1024;
        $unitIndex++;
    }

    return number_format($size, ($unitIndex === 0 ? 0 : 2), '.', '') . ' ' . $units[$unitIndex];
}

function safePath($baseDir, $candidate): string
{
    $resolved = realpath($baseDir . DIRECTORY_SEPARATOR . $candidate);
    if ($resolved === false) {
        return $baseDir;
    }

    if (strpos($resolved, $baseDir) !== 0) {
        return $baseDir;
    }

    return $resolved;
}

$requestedDir = trim($_GET['dir'] ?? '');
$dir = safePath($baseDir, $requestedDir);
$dir = rtrim($dir, DIRECTORY_SEPARATOR);
$submittedPassword = trim($_POST['password'] ?? '');
$authenticated = !empty($_SESSION['admin_dir_auth']);

if ($passwordConfigured && hash_equals($envPassword, $submittedPassword)) {
    $_SESSION['admin_dir_auth'] = true;
    $authenticated = true;
}

if (isset($_GET['download']) && $authenticated) {
    $downloadPath = base64_decode($_GET['download'], true);
    if ($downloadPath !== false) {
        $downloadPath = safePath($baseDir, $downloadPath);
        if (is_file($downloadPath) && strpos($downloadPath, $baseDir) === 0) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="' . basename($downloadPath) . '"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($downloadPath));
            readfile($downloadPath);
            exit;
        }
    }
}

$search = trim($_GET['q'] ?? '');
$order = $_GET['order'] ?? 'desc';
if (!in_array($order, ['asc', 'desc'], true)) {
    $order = 'desc';
}

$items = [];
if ($authenticated && is_dir($dir)) {
    $iterator = new FilesystemIterator($dir, FilesystemIterator::SKIP_DOTS);
    foreach ($iterator as $fileInfo) {
        if ($fileInfo->getFilename() === 'index.php') {
            continue;
        }

        $name = $fileInfo->getFilename();
        $isDir = $fileInfo->isDir();
        $mtime = $fileInfo->getMTime();

        if (!$isDir && strtolower(pathinfo($name, PATHINFO_EXTENSION)) === 'srt') {
            continue;
        }

        if ($search !== '' && stripos($name, $search) === false) {
            continue;
        }

        $items[] = [
            'name' => $name,
            'path' => $fileInfo->getPathname(),
            'isDir' => $isDir,
            'size' => $isDir ? null : $fileInfo->getSize(),
            'mtime' => $mtime,
        ];
    }
}

usort($items, function ($a, $b) use ($order) {
    $result = $a['mtime'] <=> $b['mtime'];
    return $order === 'asc' ? $result : -$result;
});

$currentRelative = str_replace($baseDir, '', $dir);
$currentRelative = ltrim($currentRelative, DIRECTORY_SEPARATOR);
$currentRelative = $currentRelative === '' ? 'Root' : $currentRelative;

$parentDir = dirname($dir);
$canGoUp = $parentDir !== $dir && strpos($parentDir, $baseDir) === 0;
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Admin File Viewer</title>
    <style>
        :root {
            --bg: #0f172a;
            --panel: #111827;
            --panel-2: #1f2937;
            --text: #e5e7eb;
            --muted: #94a3b8;
            --accent: #38bdf8;
            --accent-2: #22c55e;
            --danger: #ef4444;
            --border: rgba(255, 255, 255, 0.08);
        }

        * { box-sizing: border-box; }
        body {
            margin: 0;
            font-family: Arial, Helvetica, sans-serif;
            background: linear-gradient(135deg, #020617, #0f172a 45%, #111827);
            color: var(--text);
            min-height: 100vh;
        }

        .wrap {
            max-width: 1100px;
            margin: 25px auto;
            padding: 20px;
        }

        .card {
            background: rgba(17, 24, 39, 0.94);
            border: 1px solid var(--border);
            border-radius: 14px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.35);
            overflow: hidden;
        }

        .topbar {
            padding: 18px 20px;
            border-bottom: 1px solid var(--border);
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            align-items: center;
            justify-content: space-between;
        }

        .title {
            font-size: 1.3rem;
            font-weight: 700;
        }

        .toolbar {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            align-items: center;
        }

        input, select, button {
            border: 1px solid var(--border);
            background: #0b1220;
            color: var(--text);
            border-radius: 10px;
            padding: 10px 12px;
            font-size: 0.95rem;
        }

        input:focus, select:focus, button:focus {
            outline: 2px solid rgba(56, 189, 248, 0.5);
            outline-offset: 1px;
        }

        button {
            cursor: pointer;
            background: linear-gradient(135deg, var(--accent), #2563eb);
            border: none;
            font-weight: 700;
        }

        .table-wrap {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            table-layout: fixed;
        }

        th, td {
            text-align: left;
            padding: 14px 16px;
            border-bottom: 1px solid var(--border);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        th:nth-child(1), td:nth-child(1) {
            width: 55%;
        }

        th:nth-child(2), td:nth-child(2) {
            width: 15%;
        }

        th:nth-child(3), td:nth-child(3) {
            width: 20%;
        }

        th:nth-child(4), td:nth-child(4) {
            width: 10%;
        }

        th {
            background: rgba(31, 41, 55, 0.85);
            color: #cbd5e1;
            font-size: 0.9rem;
            text-transform: uppercase;
        }

        tr:hover {
            background: rgba(51, 65, 85, 0.35);
        }

        .muted { color: var(--muted); }
        .link {
            color: var(--accent);
            text-decoration: none;
            font-weight: 600;
        }

        .link:hover { text-decoration: underline; }

        td .link,
        td .copy-name {
            display: block;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .download {
            color: var(--accent-2);
        }

        .copy-name {
            background: transparent;
            border: none;
            color: var(--accent);
            text-decoration: none;
            font-weight: 600;
            cursor: pointer;
            padding: 0;
            font-size: 1rem;
        }

        .copy-name:hover {
            text-decoration: underline;
        }

        .status {
            padding: 15px 20px;
            color: var(--muted);
            border-top: 1px solid var(--border);
            background: rgba(15, 23, 42, 0.8);
        }

        .login-box {
            padding: 28px 22px;
            display: grid;
            gap: 14px;
        }

        .error {
            color: #fca5a5;
            font-weight: 700;
        }

        @media (max-width: 700px) {
            .topbar { align-items: stretch; }
            .toolbar { width: 100%; }
            input, select, button { width: 100%; }
        }
    </style>
</head>
<body>
    <div class="wrap">
        <div class="card">
            <?php if (!$authenticated): ?>
                <div class="login-box">
                    <div class="title">Login</div>
                    <div class="muted">Enter the password to access this directory.</div>
                    <?php if ($_SERVER['REQUEST_METHOD'] === 'POST' && $passwordConfigured): ?>
                        <div class="error">Incorrect password.</div>
                    <?php endif; ?>
                    <?php if (!$passwordConfigured): ?>
                        <div class="error">Set the ADMIN_DIR_PASSWORD environment variable on the host before using this page.</div>
                    <?php endif; ?>
                    <form method="post">
                        <input type="password" name="password" placeholder="Password" required style="width:100%;max-width:420px;" />
                        <div style="margin-top:12px;">
                            <button type="submit">Login</button>
                        </div>
                    </form>
                </div>
            <?php else: ?>
                <div class="topbar">
                    <div>
                        <div class="title">Admin File Viewer</div>
                        <div class="muted">Current folder: <?php echo htmlspecialchars($currentRelative); ?></div>
                    </div>
                    <div class="toolbar">
                        <?php if ($canGoUp): ?>
                            <a class="link" href="?dir=<?php echo urlencode(substr($dir, strlen($baseDir) + 1)); ?>">← Back</a>
                        <?php endif; ?>
                        <form method="get" style="display:flex;gap:10px;flex-wrap:wrap;">
                            <input type="hidden" name="dir" value="<?php echo htmlspecialchars($requestedDir); ?>" />
                            <input type="text" name="q" placeholder="Search files" value="<?php echo htmlspecialchars($search); ?>" />
                            <select name="order">
                                <option value="desc" <?php echo $order === 'desc' ? 'selected' : ''; ?>>Newest first</option>
                                <option value="asc" <?php echo $order === 'asc' ? 'selected' : ''; ?>>Oldest first</option>
                            </select>
                            <button type="submit">Filter</button>
                        </form>
                    </div>
                </div>

                <div class="table-wrap">
                    <table>
                        <thead>
                        <tr>
                            <th>Name</th>
                            <th>Size</th>
                            <th>Date</th>
                            <th>Action</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (empty($items)): ?>
                            <tr>
                                <td colspan="4" class="muted">No files found.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($items as $item): ?>
                                <?php
                                    $relativePath = ltrim(str_replace('\\', '/', substr($item['path'], strlen($baseDir))), '/');
                                ?>
                                <tr>
                                    <td>
                                        <?php if ($item['isDir']): ?>
                                            <a class="link" href="?dir=<?php echo urlencode(substr($item['path'], strlen($baseDir) + 1)); ?>"><?php echo htmlspecialchars($item['name']); ?></a>
                                        <?php else: ?>
                                            <button type="button" class="copy-name" data-copy="<?php echo htmlspecialchars($relativePath); ?>" data-label="<?php echo htmlspecialchars($item['name']); ?>"><?php echo htmlspecialchars($item['name']); ?></button>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo $item['isDir'] ? 'Folder' : humanSize($item['size']); ?></td>
                                    <td><?php echo date('Y-m-d H:i:s', $item['mtime']); ?></td>
                                    <td>
                                        <?php if ($item['isDir']): ?>
                                            <span class="muted">Open</span>
                                        <?php else: ?>
                                            <a class="link download" href="?download=<?php echo urlencode(base64_encode($item['path'])); ?>">Download</a>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <div class="status">
                    Showing <?php echo count($items); ?> item(s) in <?php echo htmlspecialchars($currentRelative); ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        document.addEventListener('click', async function (event) {
            const target = event.target.closest('.copy-name');
            if (!target) {
                return;
            }

            event.preventDefault();
            const value = target.getAttribute('data-copy') || '';
            const label = target.getAttribute('data-label') || value;

            try {
                await navigator.clipboard.writeText(value);
                target.textContent = 'Copied!';
                setTimeout(function () {
                    target.textContent = label;
                }, 1200);
            } catch (error) {
                target.textContent = 'Copy failed';
                setTimeout(function () {
                    target.textContent = label;
                }, 1200);
            }
        });
    </script>
</body>
</html>
