<?php
$dir = isset($_GET['dir']) ? $_GET['dir'] : '.';
$file = isset($_GET['download']) ? $_GET['download'] : '';

// Handle file download
if($file && file_exists($file)) {
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    readfile($file);
    exit;
}

// Handle file upload
$uploadMessage = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
        $uploadFile = $dir . '/' . basename($_FILES['file']['name']);
        
        // Check if file already exists
        if (file_exists($uploadFile)) {
            $uploadMessage = '<span style="color: red;">Error: File already exists.</span>';
        } else {
            // Attempt to move the uploaded file
            if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
                $uploadMessage = '<span style="color: green;">File uploaded successfully.</span>';
            } else {
                $uploadMessage = '<span style="color: red;">Error uploading file.</span>';
            }
        }
    } elseif ($_FILES['file']['error'] === UPLOAD_ERR_INI_SIZE) {
        $uploadMessage = '<span style="color: red;">Error: File size exceeds server limit.</span>';
    } else {
        $uploadMessage = '<span style="color: red;">Error uploading file (code: ' . $_FILES['file']['error'] . ').</span>';
    }
}

// Display the page
echo "<!DOCTYPE html><html><head><title>Directory Browser</title></head><body>";
echo "<h2>Directory: " . htmlspecialchars($dir) . "</h2>";

// Display upload form
echo "<div style='margin-bottom: 20px; padding: 10px; border: 1px solid #ccc;'>";
echo "<h3>Upload File</h3>";
echo "<form method='post' enctype='multipart/form-data'>";
echo "<input type='file' name='file' required>";
echo "<input type='submit' value='Upload'>";
echo "</form>";
if ($uploadMessage) {
    echo "<p>" . $uploadMessage . "</p>";
}
echo "</div>";

// Navigation and file listing
echo "<a href='?dir=" . urlencode(dirname($dir)) . "'>.. (Parent Directory)</a><br><br>";

$files = scandir($dir);
foreach($files as $f) {
    if($f == '.' || $f == '..') continue;
    $fullPath = $dir . '/' . $f;
    if(is_dir($fullPath)) {
        echo "📁 <a href='?dir=" . urlencode($fullPath) . "'>" . htmlspecialchars($f) . "</a><br>";
    } else {
        echo "📄 <a href='?download=" . urlencode($fullPath) . "'>" . htmlspecialchars($f) . "</a> (" . filesize($fullPath) . " bytes)<br>";
    }
}

echo "</body></html>";
?>
