<?php
declare(strict_types=1);
/**
 * Safe File Manager + Login + Rename
 * ----------------------------------
 * Fitur:
 * ✅ Login awal (password: admin12345)
 * ✅ Navigasi folder
 * ✅ Upload / Download / Delete / Rename
 * ✅ Buat folder baru
 * ✅ Edit file teks
 * ✅ Aman (tanpa eval, exec, koneksi luar)
 */

const ROOT_DIR = __DIR__;
const LOGIN_PASSWORD = 'admin12345';
const MAX_UPLOAD = 8 * 1024 * 1024;
const ALLOWED_EXT = ['txt','php','html','json','css','js','md','csv','xml'];

session_start();

/* ==== Helpers ==== */
function esc(string $s): string { return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }
function clean_name(string $n): string { $n = basename($n); $n = preg_replace('/[^A-Za-z0-9._-]/', '_', $n); return $n ?: 'file'; }
function csrf(): string { if (empty($_SESSION['csrf'])) $_SESSION['csrf']=bin2hex(random_bytes(12)); return $_SESSION['csrf']; }
function csrf_check(string $t): void { if (!hash_equals(csrf(), $t)) { http_response_code(403); exit('Bad CSRF'); } }

/* ==== Login wajib ==== */
if (empty($_SESSION['logged'])) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['password'])) {
        if ($_POST['password'] === LOGIN_PASSWORD) {
            $_SESSION['logged'] = true;
            header('Location: ?'); exit;
        } else {
            $error = 'Password salah.';
        }
    }
    ?>
    <!doctype html><meta charset="utf-8">
    <title>LOGIN | Safe Manager</title>
    <style>
    body{font-family:Arial;margin:40px;text-align:center;background:#f9f9f9;color:#222}
    input{padding:8px;width:220px;font-size:14px}
    button{padding:8px 18px;margin-top:10px;cursor:pointer;background:#0078ff;color:#fff;border:none;border-radius:4px}
    .box{display:inline-block;padding:40px;background:#fff;border:1px solid #ccc;border-radius:8px;box-shadow:0 0 10px rgba(0,0,0,0.1)}
    h2{margin-bottom:10px}
    </style>
    <div class="box">
      <h2>🔐 LOGIN</h2>
      <?php if (!empty($error)) echo "<p style='color:red'>".esc($error)."</p>"; ?>
      <form method="post">
        <input type="password" name="password" placeholder="Masukkan password..." required><br>
        <button type="submit">LOGIN</button>
      </form>
    </div>
    <?php
    exit;
}

/* ==== Path navigasi ==== */
$base = realpath(ROOT_DIR);
$sub = $_GET['dir'] ?? '';
$target = realpath($base . '/' . $sub);
if ($target === false || strpos($target, $base) !== 0) $target = $base;

/* ==== Aksi ==== */
$msgs = [];
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['action'])) {
    csrf_check($_POST['csrf'] ?? '');

    if ($_POST['action']==='upload') {
        if (!empty($_FILES['file']['name'])) {
            $name = clean_name($_FILES['file']['name']);
            if ($_FILES['file']['size'] > MAX_UPLOAD) $msgs[]='❌ File terlalu besar.';
            else {
                $dest = $target.'/'.$name;
                if (move_uploaded_file($_FILES['file']['tmp_name'],$dest)) $msgs[]='✅ Upload sukses: '.$name;
                else $msgs[]='❌ Upload gagal.';
            }
        }
    } elseif ($_POST['action']==='delete') {
        $f = clean_name($_POST['file'] ?? '');
        $p = $target.'/'.$f;
        if (is_file($p) && unlink($p)) $msgs[]='🗑️ File dihapus: '.$f;
        elseif (is_dir($p) && rmdir($p)) $msgs[]='📂 Folder dihapus: '.$f;
        else $msgs[]='❌ Gagal hapus.';
    } elseif ($_POST['action']==='mkdir') {
        $name = clean_name($_POST['folder'] ?? '');
        if ($name) {
            $path = $target.'/'.$name;
            if (!file_exists($path) && mkdir($path,0755)) $msgs[]='📁 Folder dibuat: '.$name;
            else $msgs[]='❌ Gagal membuat folder.';
        }
    } elseif ($_POST['action']==='rename') {
        $old = clean_name($_POST['old']);
        $new = clean_name($_POST['new']);
        $oldPath = $target.'/'.$old;
        $newPath = $target.'/'.$new;
        if (file_exists($oldPath)) {
            if (rename($oldPath, $newPath)) $msgs[]="✏️ Nama diubah: $old → $new";
            else $msgs[]="❌ Gagal mengganti nama.";
        } else $msgs[]="❌ File tidak ditemukan.";
    } elseif ($_POST['action']==='save') {
        $file = $target.'/'.clean_name($_POST['file']);
        if (is_file($file) && is_writable($file)) {
            file_put_contents($file, $_POST['content']);
            $msgs[]='💾 Perubahan disimpan: '.basename($file);
        } else {
            $msgs[]='❌ Tidak bisa menulis file.';
        }
    } elseif ($_POST['action']==='logout') {
        session_destroy();
        header('Location:?'); exit;
    }
}

/* ==== Download ==== */
if (isset($_GET['download'])) {
    $f = clean_name($_GET['download']);
    $p = $target.'/'.$f;
    if (!is_file($p)) { http_response_code(404); exit('File tidak ditemukan'); }
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($f).'"');
    header('Content-Length: '.filesize($p));
    readfile($p); exit;
}

/* ==== Edit ==== */
$editFile = null; $editContent = '';
if (isset($_GET['edit'])) {
    $f = clean_name($_GET['edit']);
    $p = $target.'/'.$f;
    if (is_file($p) && filesize($p) < MAX_UPLOAD) {
        $ext = strtolower(pathinfo($p, PATHINFO_EXTENSION));
        if (in_array($ext, ALLOWED_EXT)) {
            $editFile = $f;
            $editContent = file_get_contents($p);
        } else $msgs[] = '⚠️ File ini tidak bisa diedit (bukan teks).';
    } else $msgs[] = '❌ File tidak ditemukan atau terlalu besar.';
}

/* ==== Daftar ==== */
$files = scandir($target) ?: [];
$csrf = csrf();
$current = trim(str_replace($base, '', $target), '/');
$breadcrumb = explode('/', $current);
?>
<!doctype html>
<html lang="id"><meta charset="utf-8">
<title>Safe Manager</title>
<style>
body{font-family:Arial;margin:20px;color:#111}
table{border-collapse:collapse;width:100%;margin-top:10px}
td,th{border:1px solid #eee;padding:6px}
button{cursor:pointer}
.msg{background:#eef;padding:8px;margin:6px 0;border-radius:4px}
textarea{width:100%;height:400px;font-family:monospace;font-size:14px}
a{text-decoration:none;color:#06c}
a:hover{text-decoration:underline}
</style>

<h1>Safe Manager</h1>
<form method="post" style="float:right">
  <input type="hidden" name="action" value="logout">
  <input type="hidden" name="csrf" value="<?=esc($csrf)?>">
  <button type="submit">Logout</button>
</form>
<div style="clear:both"></div>

<?php foreach($msgs as $m): ?><div class="msg"><?=esc($m)?></div><?php endforeach; ?>

<p><b>Lokasi:</b>
  <?php if ($current): ?>
    <a href="?">root</a> /
    <?php
    $pathSoFar = '';
    foreach ($breadcrumb as $i => $part):
      if (!$part) continue;
      $pathSoFar .= ($pathSoFar ? '/' : '') . $part;
      if ($i === count($breadcrumb)-1) echo esc($part);
      else echo '<a href="?dir='.urlencode($pathSoFar).'">'.esc($part).'</a> / ';
    endforeach;
    ?>
  <?php else: ?><b>root</b><?php endif; ?>
</p>

<?php if ($target !== $base): ?>
  <p><a href="?dir=<?=urlencode(dirname($current))?>">⬅️ Kembali</a></p>
<?php endif; ?>

<?php if ($editFile): ?>
  <h3>Edit File: <?=esc($editFile)?></h3>
  <form method="post">
    <input type="hidden" name="action" value="save">
    <input type="hidden" name="csrf" value="<?=esc($csrf)?>">
    <input type="hidden" name="file" value="<?=esc($editFile)?>">
    <textarea name="content"><?=esc($editContent)?></textarea><br>
    <button type="submit">💾 Simpan</button>
    <a href="?dir=<?=urlencode($current)?>">Batal</a>
  </form>
<?php else: ?>

  <h3>Buat Folder</h3>
  <form method="post">
    <input type="hidden" name="action" value="mkdir">
    <input type="hidden" name="csrf" value="<?=esc($csrf)?>">
    <input name="folder" placeholder="Nama folder" required>
    <button type="submit">Buat</button>
  </form>

  <h3>Upload File</h3>
  <form method="post" enctype="multipart/form-data">
    <input type="hidden" name="action" value="upload">
    <input type="hidden" name="csrf" value="<?=esc($csrf)?>">
    <input type="file" name="file" required>
    <button type="submit">Upload</button>
  </form>

  <h3>Isi Folder</h3>
  <table>
    <tr><th>Nama</th><th>Ukuran</th><th>Aksi</th></tr>
    <?php foreach($files as $f): if ($f==='.'||$f==='..') continue;
      $path = $target.'/'.$f; ?>
      <tr>
        <td>
          <?php if (is_dir($path)): ?>
            📁 <a href="?dir=<?=urlencode(trim(($current? $current.'/' : '').$f,'/'))?>"><?=esc($f)?></a>
          <?php else: ?>
            📄 <?=esc($f)?>
          <?php endif; ?>
        </td>
        <td><?=is_dir($path)?'-':number_format(filesize($path))?> B</td>
        <td>
          <?php if (!is_dir($path)): ?>
            <a href="?dir=<?=urlencode($current)?>&download=<?=urlencode($f)?>">Download</a> |
            <a href="?dir=<?=urlencode($current)?>&edit=<?=urlencode($f)?>">Edit</a>
          <?php endif; ?>
          <form method="post" style="display:inline">
            <input type="hidden" name="action" value="rename">
            <input type="hidden" name="csrf" value="<?=esc($csrf)?>">
            <input type="hidden" name="old" value="<?=esc($f)?>">
            <input type="text" name="new" value="<?=esc($f)?>" size="10">
            <button>Rename</button>
          </form>
          <form method="post" style="display:inline">
            <input type="hidden" name="action" value="delete">
            <input type="hidden" name="csrf" value="<?=esc($csrf)?>">
            <input type="hidden" name="file" value="<?=esc($f)?>">
            <button onclick="return confirm('Hapus <?=esc($f)?> ?')">Hapus</button>
          </form>
        </td>
      </tr>
    <?php endforeach; ?>
  </table>
<?php endif; ?>
