<?php
session_name('file_access_auth');
session_start();

// --- Config ---
$password = 'a'; // change this
$baseDir = realpath(__DIR__); // don't change
$dirParam = $_GET['dir'] ?? '';
$requestedDir = realpath($baseDir . '/' . $dirParam);

// --- Auth ---
if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: index.php");
    exit;
}

if (isset($_POST['password'])) {
    if ($_POST['password'] === $password) {
        $_SESSION['authenticated'] = true;
    } else {
        $error = "Incorrect password.";
    }
}

if (!isset($_SESSION['authenticated']) || $_SESSION['authenticated'] !== true) {
    ?>
    <form method="post">
        <input type="password" name="password" placeholder="Enter password" required>
        <input type="submit" value="Access">
    </form>
    <?php if (!empty($error)) echo "<p style='color:red;'>$error</p>"; ?>
    <?php exit;
}

// --- Validate path ---
if (!$requestedDir || strpos($requestedDir, $baseDir) !== 0 || !is_dir($requestedDir)) {
    die("Invalid path.");
}

// --- Show file listing ---
$files = scandir($requestedDir);
$currentDirDisplay = htmlspecialchars(str_replace($baseDir, '', $requestedDir));

echo "<h2>Browsing: /$currentDirDisplay</h2>";
if ($dirParam) {
    $parent = dirname($dirParam);
    echo "<p><a href='?dir=" . urlencode($parent) . "'>[Parent Directory]</a></p>";
}
echo "<ul>";

foreach ($files as $file) {
    if ($file === '.') continue;
    if ($file === '..') continue;
    
    $fullPath = $requestedDir . '/' . $file;
    $relativePath = ltrim($dirParam . '/' . $file, '/');
    
    if (is_dir($fullPath)) {
        echo "<li><strong><a href='?dir=" . urlencode($relativePath) . "'>$file/</a></strong></li>";
    } else {
        echo "<li><a href='" . htmlspecialchars($relativePath) . "' target='_blank'>$file</a></li>";
    }
}
echo "</ul><p><a href='?logout=1'>Logout</a></p>";
