<?php
session_start();

// ==== CONFIGURATION ====
$username = 'admin';
$password = 'secret';
$baseDir = __DIR__; // Root directory
$baseUrl = '.';     // URL path

// ==== LOGIN HANDLER ====
if (isset($_POST['login'])) {
    if ($_POST['user'] === $username && $_POST['pass'] === $password) {
        $_SESSION['logged_in'] = true;
    } else {
        $error = "Invalid username or password.";
    }
}

if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: " . strtok($_SERVER["REQUEST_URI"], '?'));
    exit;
}

if (!isset($_SESSION['logged_in'])): ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
    <div class="container d-flex justify-content-center align-items-center vh-100">
        <div class="card p-4 shadow-sm" style="max-width: 400px; width: 100%;">
            <h3 class="card-title text-center mb-4">Login</h3>
            <?php if (!empty($error)) echo "<div class='alert alert-danger'>$error</div>"; ?>
            <form method="post">
                <div class="mb-3">
                    <label for="user" class="form-label">Username</label>
                    <input type="text" id="user" name="user" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label for="pass" class="form-label">Password</label>
                    <input type="password" id="pass" name="pass" class="form-control" required>
                </div>
                <button type="submit" name="login" class="btn btn-primary w-100">Login</button>
            </form>
        </div>
    </div>
</body>
</html>
<?php exit; endif;

// ==== DIRECTORY NAVIGATION ====
$relativeDir = isset($_GET['dir']) ? $_GET['dir'] : '';
$currentDir = realpath($baseDir . DIRECTORY_SEPARATOR . $relativeDir);

// Security check to prevent access outside baseDir
if ($currentDir === false || strpos($currentDir, $baseDir) !== 0 || !is_dir($currentDir)) {
    die("Invalid directory.");
}

// ==== FILE HANDLING ====
// Upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    $targetFile = $currentDir . DIRECTORY_SEPARATOR . basename($_FILES['file']['name']);
    if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFile)) {
        $message = "File uploaded successfully.";
    } else {
        $message = "File upload failed.";
    }
}

// List files and directories
$items = array_diff(scandir($currentDir), ['.', '..']);
$directories = [];
$files = [];
foreach ($items as $item) {
    $itemPath = $currentDir . DIRECTORY_SEPARATOR . $item;
    if (is_dir($itemPath)) {
        $directories[] = $item;
    } else {
        $files[] = $item;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Manager</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
    <div class="container my-4">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h1 class="h3">📁 File Manager</h1>
            <a href="?logout=1" class="btn btn-outline-danger">Logout</a>
        </div>

        <?php if (isset($message)) echo "<div class='alert alert-info'>$message</div>"; ?>

        <div class="mb-3">
            <form method="post" enctype="multipart/form-data" class="d-flex">
                <input type="file" name="file" class="form-control me-2" required>
                <button type="submit" class="btn btn-primary">Upload</button>
            </form>
        </div>

        <div class="mb-3">
            <?php
            // Show Back button only if not at root
            if ($relativeDir !== ''):
                $parentDir = dirname($relativeDir);
            ?>
            <a href="?dir=<?= urlencode($parentDir) ?>" class="btn btn-secondary">⬅️ Back</a>
            <?php endif; ?>
        </div>

        <div class="row">
            <!-- Display Folders -->
            <?php foreach ($directories as $dir): ?>
                <div class="col-6 col-md-4 col-lg-3 mb-3">
                    <div class="card">
                        <div class="card-body text-center">
                            <h5 class="card-title"><?= htmlspecialchars($dir) ?></h5>
                            <?php
                            $subdir = ltrim(str_replace($baseDir, '', $currentDir . DIRECTORY_SEPARATOR . $dir), DIRECTORY_SEPARATOR);
                            ?>
                            <a href="?dir=<?= urlencode($subdir) ?>" class="btn btn-link">Open Folder</a>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>

            <!-- Display Files -->
            <?php foreach ($files as $file): ?>
                <div class="col-6 col-md-4 col-lg-3 mb-3">
                    <div class="card">
                        <div class="card-body text-center">
                            <h5 class="card-title"><?= htmlspecialchars($file) ?></h5>
                            <?php
                            $relativePath = ltrim(str_replace($baseDir, '', $currentDir . DIRECTORY_SEPARATOR . $file), DIRECTORY_SEPARATOR);
                            $fileUrl = $baseUrl . '/' . str_replace(DIRECTORY_SEPARATOR, '/', $relativePath);
                            ?>
                            <a href="<?= htmlspecialchars($fileUrl) ?>" class="btn btn-link" download>Download</a>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</body>
</html>
