<?php
// Mini File Manager - Improved Version
// Original functions kept, added: delete, rename, size, perms, better UI

// Optional simple password protection (change or remove if not needed)
$password = '123456'; // ← change this or comment out the block below
session_start();
if (!isset($_SESSION['auth']) && (!isset($_POST['p']) || $_POST['p'] !== $password)) {
    echo '<!DOCTYPE html><title>Login</title><style>body{font-family:Arial;margin:100px;text-align:center;background:#111;color:#eee}input,button{padding:12px;font-size:18px;border-radius:6px}</style>';
    echo '<form method="post"><input type="password" name="p" autofocus placeholder="Password"><br><br><button type="submit">Enter</button></form>';
    exit;
}
$_SESSION['auth'] = true;

// =============================================
// HELPER FUNCTIONS
// =============================================

function h($s) {
    return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8');
}

function formatSize($bytes) {
    if ($bytes <= 0) return '0 B';
    $units = ['B','KB','MB','GB','TB'];
    $i = (int)floor(log($bytes, 1024));
    return number_format($bytes / pow(1024, $i), 2) . ' ' . $units[$i];
}

function deleteItem($path) {
    if (!file_exists($path)) return false;
    if (is_dir($path)) {
        $it = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS);
        $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
        foreach ($files as $f) {
            is_dir($f) ? rmdir($f) : unlink($f);
        }
        return rmdir($path);
    }
    return unlink($path);
}

// =============================================
// MAIN FUNCTIONS (original kept + improved)
// =============================================

function listDirectory($dir) {
    $files = scandir($dir);
    $parent = dirname($dir);

    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>File Manager</title>
        <style>
            body{font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif; background:#fcfafa; color:#e0e0e0; margin:0; padding:20px; line-height:1.6;}
            h2{color:#4cc9f0; margin:0 0 15px;}
            .container{max-width:1200px; margin:0 auto;}
            .path{background:#1a1a1a; padding:12px 16px; border-radius:8px; font-family:monospace; margin-bottom:20px; word-break:break-all;}
            .actions{margin:20px 0;}
            .btn{padding:8px 16px; background:#4361ee; color:white; border:none; border-radius:6px; cursor:pointer; text-decoration:none; margin:0 6px 6px 0; display:inline-block;}
            .btn:hover{background:#3f37c9;}
            .btn-delete{background:#e63946;}
            .btn-delete:hover{background:#d00000;}
            .btn-rename{background:#7209b7;}
            input[type=text], input[type=file], textarea{padding:10px; border:1px solid #444; border-radius:6px; background:#1a1a1a; color:#eee; width:280px;}
            textarea{width:100%; height:400px; font-family:Consolas,monospace; font-size:14px;}
            table{width:100%; border-collapse:collapse; margin-top:10px; background: #2898f1;}
            th,td{padding:10px; text-align:left; border-bottom:1px solid #333;}
            th{background:#1a1a1a;}
            tr:hover{background:#222;}
            .size{text-align:right;}
            .perms{font-family:monospace; color:#9d9d9d;}
            .msg{padding:12px; border-radius:6px; margin:15px 0;}
            .success{background:#2a9d8f; color:white;}
            .error{background:#e63946; color:white;}
            .delete-form{display:inline;}
        </style>
    </head>
    <body>
    <div class="container">
        <h2>File Manager</h2>
        <div class="path">Current: <?= h($dir) ?></div>

        <?php
        if (isset($_GET['msg'])) {
            $type = $_GET['msg'] === 'success' ? 'success' : 'error';
            echo "<div class='msg $type'>" . h($_GET['text']) . "</div>";
        }
        ?>

        <div class="actions">
            <a href="?dir=<?= urlencode($parent) ?>" class="btn" <?= $dir === '/' ? 'style="display:none"' : '' ?>>← Go Back</a>
            <a href="?" class="btn">Home</a>
        </div>

        <!-- Create file -->
        <form method="post" class="actions">
            <input type="text" name="new_file_name" placeholder="New file name (e.g. script.php)" required>
            <input type="submit" name="create_file" value="Create File" class="btn">
        </form>

        <!-- Upload file -->
        <form method="post" enctype="multipart/form-data" class="actions">
            <input type="file" name="file_to_upload" required>
            <input type="submit" name="upload_file" value="Upload File" class="btn">
        </form>

        <table>
            <tr>
                <th>Name</th>
                <th>Type</th>
                <th class="size">Size</th>
                <th>Perms</th>
                <th>Actions</th>
            </tr>
            <?php foreach ($files as $file):
                if ($file === '.' || $file === '..') continue;
                $full = $dir . '/' . $file;
                $isDir = is_dir($full);
                $size = $isDir ? '—' : formatSize(filesize($full));
                $perms = substr(sprintf('%o', fileperms($full)), -4);
                $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
                $canEdit = !$isDir && in_array($ext, ['php','txt','html','css','js','json','xml','md','log','ini','env','htaccess']);
            ?>
            <tr>
                <td>
                    <?php if ($isDir): ?>
                        <strong><a href="?dir=<?= urlencode($full) ?>">[DIR] <?= h($file) ?>/</a></strong>
                    <?php else: ?>
                        [FILE] <?= h($file) ?>
                    <?php endif; ?>
                </td>
                <td><?= $isDir ? 'Directory' : 'File' ?></td>
                <td class="size"><?= $size ?></td>
                <td class="perms"><?= $perms ?></td>
                <td>
                    <?php if (!$isDir): ?>
                        <a href="?view=<?= urlencode($full) ?>" class="btn">View</a>
                        <?php if ($canEdit): ?>
                            <a href="?edit=<?= urlencode($full) ?>" class="btn">Edit</a>
                        <?php endif; ?>
                        <a href="?download=<?= urlencode($full) ?>" class="btn">Download</a>
                    <?php endif; ?>

                    <form method="post" class="delete-form" onsubmit="return confirm('Delete <?= h(addslashes($file)) ?> ? This cannot be undone.');">
                        <input type="hidden" name="delete_path" value="<?= h($full) ?>">
                        <input type="submit" value="Delete" class="btn btn-delete">
                    </form>

                    <form method="post" style="display:inline;">
                        <input type="hidden" name="rename_old" value="<?= h($full) ?>">
                        <input type="text" name="rename_new" value="<?= h($file) ?>" style="width:140px;">
                        <input type="submit" value="Rename" class="btn btn-rename">
                    </form>
                </td>
            </tr>
            <?php endforeach; ?>
        </table>
    </div>
    <?php
}

function createFile($dir, $fileName) {
    $path = rtrim($dir, '/') . '/' . $fileName;
    if (!file_exists($path)) {
        file_put_contents($path, "");
        header("Location: ?dir=" . urlencode($dir) . "&msg=success&text=File+created");
        exit;
    } else {
        header("Location: ?dir=" . urlencode($dir) . "&msg=error&text=File+already+exists");
        exit;
    }
}

function uploadFile($dir) {
    if (!isset($_FILES['file_to_upload']) || $_FILES['file_to_upload']['error'] != 0) {
        header("Location: ?dir=" . urlencode($dir) . "&msg=error&text=Upload+failed");
        exit;
    }
    $target = rtrim($dir, '/') . '/' . basename($_FILES['file_to_upload']['name']);
    if (move_uploaded_file($_FILES['file_to_upload']['tmp_name'], $target)) {
        header("Location: ?dir=" . urlencode($dir) . "&msg=success&text=File+uploaded");
        exit;
    } else {
        header("Location: ?dir=" . urlencode($dir) . "&msg=error&text=Upload+failed");
        exit;
    }
}

// =============================================
// ACTIONS
// =============================================

if (isset($_GET['download'])) {
    $path = realpath($_GET['download']);
    if ($path && file_exists($path) && is_file($path)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . basename($path) . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($path));
        readfile($path);
        exit;
    }
}

if (isset($_GET['view'])) {
    $path = realpath($_GET['view']);
    if ($path && file_exists($path) && is_file($path)) {
        echo "<h2>View: " . h(basename($path)) . "</h2>";
        echo "<pre>" . h(file_get_contents($path)) . "</pre>";
        echo '<a href="?dir=' . urlencode(dirname($path)) . '" class="btn">Back</a>';
        exit;
    }
}

if (isset($_GET['edit'])) {
    $path = realpath($_GET['edit']);
    if ($path && file_exists($path) && is_file($path)) {
        if (isset($_POST['content'])) {
            file_put_contents($path, $_POST['content']);
            header("Location: ?dir=" . urlencode(dirname($path)) . "&msg=success&text=File+saved");
            exit;
        }
        $content = file_get_contents($path);
        echo "<h2>Edit: " . h(basename($path)) . "</h2>";
        echo '<form method="post">';
        echo '<textarea name="content">' . h($content) . '</textarea><br>';
        echo '<input type="submit" value="Save" class="btn">';
        echo '</form>';
        echo '<a href="?dir=' . urlencode(dirname($path)) . '" class="btn">Back</a>';
        exit;
    }
}

// POST actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $current = isset($_GET['dir']) ? realpath($_GET['dir']) : realpath('.');
    if (!$current || !is_dir($current)) $current = realpath('.');

    if (isset($_POST['create_file']) && !empty($_POST['new_file_name'])) {
        createFile($current, $_POST['new_file_name']);
    }

    if (isset($_POST['upload_file'])) {
        uploadFile($current);
    }

    if (isset($_POST['delete_path'])) {
        $path = realpath($_POST['delete_path']);
        if ($path && strpos($path, realpath('.')) === 0 && deleteItem($path)) {
            header("Location: ?dir=" . urlencode(dirname($path)) . "&msg=success&text=Deleted");
        } else {
            header("Location: ?dir=" . urlencode($current) . "&msg=error&text=Delete+failed");
        }
        exit;
    }

    if (isset($_POST['rename_old'], $_POST['rename_new']) && trim($_POST['rename_new'])) {
        $old = realpath($_POST['rename_old']);
        $newName = trim($_POST['rename_new']);
        $new = dirname($old) . '/' . $newName;
        if ($old && file_exists($old) && !file_exists($new)) {
            rename($old, $new);
            header("Location: ?dir=" . urlencode(dirname($old)) . "&msg=success&text=Renamed");
            exit;
        } else {
            header("Location: ?dir=" . urlencode($current) . "&msg=error&text=Rename+failed");
            exit;
        }
    }
}

// Default listing
$currentDir = isset($_GET['dir']) ? realpath($_GET['dir']) : realpath('.');
if ($currentDir === false || !is_dir($currentDir)) {
    $currentDir = realpath('.');
}
listDirectory($currentDir);
?>
    </body>
    </html>