<?php
/**
 * PART 1: Core Logic, SSH2 Connection, Clipboard (Copy/Cut/Paste) & Breadcrumbs
 */
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start(); // Required to keep the clipboard state between folders

define('FTP_BASE', '/home/cayenne/oldhkphoto/web2018/');
define('FTP_PUBKEY', '/home/cayenne/oldhkphoto/wp_user.pub');
define('FTP_PRIKEY', '/home/cayenne/oldhkphoto/wp_user');
define('FTP_USER', 'cayenne');
define('FTP_HOST', '127.0.0.1');



$connection = ssh2_connect(FTP_HOST, 22);
if (!$connection) { die("Network Error: Port 22 closed."); }
if (!ssh2_auth_pubkey_file($connection, FTP_USER, FTP_PUBKEY, FTP_PRIKEY)) {
    die("SSH Error: Key refused.");
}
$sftp = ssh2_sftp($connection);

$current_sub_dir = isset($_GET['dir']) ? str_replace(array('../', '..\\'), '', $_GET['dir']) : '';
$current_sub_dir = trim($current_sub_dir, '/');
$current_full_path = rtrim(FTP_BASE, '/') . ($current_sub_dir ? '/' . $current_sub_dir : '');

$message = '';
$editor_content = '';
$editor_file = '';
$php_output = '';

function delete_remote_item($connection, $target) {
    $stream = ssh2_exec($connection, "rm -rf " . escapeshellarg($target));
    if ($stream) { stream_set_blocking($stream, true); stream_get_contents($stream); fclose($stream); return true; }
    return false;
}

// === PHP CONSOLE EXECUTION ===
if (isset($_POST['action']) && $_POST['action'] === 'run_php' && !empty($_POST['php_code'])) {
    $clean_code = preg_replace('/^<\?php/', '', trim($_POST['php_code']));
    $cmd = "php -r " . escapeshellarg($clean_code) . " 2>&1";
    $stream = ssh2_exec($connection, $cmd);
    if ($stream) {
        stream_set_blocking($stream, true);
        $php_output = stream_get_contents($stream); fclose($stream);
        if (empty($php_output)) { $php_output = "[Code executed successfully, but returned no output]"; }
    } else { $php_output = "Error: Failed to call PHP CLI via SSH."; }
}

// === FILE DOWNLOAD ===
if (isset($_GET['download'])) {
    $file_to_download = str_replace(array('/', '\\'), '', $_GET['download']);
    $remote_file_path = $current_full_path . '/' . $file_to_download;
    $stream = ssh2_exec($connection, "cat " . escapeshellarg($remote_file_path));
    if ($stream) {
        stream_set_blocking($stream, true);
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $file_to_download . '"');
        fpassthru($stream); fclose($stream); exit;
    }
}

// === ARCHIVE EXTRACT ===
if (isset($_GET['unzip'])) {
    $archive_to_open = str_replace(array('/', '\\'), '', $_GET['unzip']);
    $archive_ext = strtolower(pathinfo($archive_to_open, PATHINFO_EXTENSION));
    $full_archive_path = $current_full_path . '/' . $archive_to_open;
    $cmd = ($archive_ext === 'zip') ? "unzip -o " . escapeshellarg($full_archive_path) . " -d " . escapeshellarg($current_full_path) : "tar -xzf " . escapeshellarg($full_archive_path) . " -C " . escapeshellarg($current_full_path);
    $stream = ssh2_exec($connection, $cmd);
    if ($stream) { stream_set_blocking($stream, true); stream_get_contents($stream); fclose($stream); $message = "<div class='success'>Archive extracted successfully!</div>"; }
}

// === SINGLE OPERATIONS ===
if (isset($_POST['action']) && $_POST['action'] === 'single_action') {
    $op = $_POST['op_type'];
    if ($op === 'mkdir' && !empty($_POST['folder_name'])) {
        $new_folder = $current_full_path . '/' . str_replace(array('/', '\\', '..'), '', $_POST['folder_name']);
        if (ssh2_sftp_mkdir($sftp, $new_folder, 0755)) { $message = "<div class='success'>Folder created!</div>"; }
    }
    if ($op === 'mkfile' && !empty($_POST['file_name'])) {
        $new_file = $current_full_path . '/' . str_replace(array('/', '\\', '..'), '', $_POST['file_name']);
        $stream = ssh2_exec($connection, "touch " . escapeshellarg($new_file) . " && chmod 0644 " . escapeshellarg($new_file));
        if ($stream) { fclose($stream); $message = "<div class='success'>File created!</div>"; }
    }
    if ($op === 'rename' && !empty($_POST['old_name']) && !empty($_POST['new_name'])) {
        $old_path = $current_full_path . '/' . str_replace(array('/', '\\', '..'), '', $_POST['old_name']);
        $new_path = $current_full_path . '/' . str_replace(array('/', '\\', '..'), '', $_POST['new_name']);
        if (ssh2_sftp_rename($sftp, $old_path, $new_path)) { $message = "<div class='success'>Item renamed!</div>"; }
    }
    if ($op === 'chmod' && !empty($_POST['item_name']) && !empty($_POST['chmod_val'])) {
        $target_path = $current_full_path . '/' . str_replace(array('/', '\\', '..'), '', $_POST['item_name']);
        $val = preg_replace('/[^0-7]/', '', $_POST['chmod_val']);
        $stream = ssh2_exec($connection, "chmod " . escapeshellarg($val) . " " . escapeshellarg($target_path));
        if ($stream) { fclose($stream); $message = "<div class='success'>Permissions changed to $val!</div>"; }
    }
}

// === CLEAR CLIPBOARD ===
if (isset($_GET['clear_clipboard'])) {
    unset($_SESSION['clipboard_items']); unset($_SESSION['clipboard_action']);
    header("Location: ?dir=" . urlencode($current_sub_dir)); exit;
}

// === FILE UPLOAD ===
if (isset($_POST['action']) && $_POST['action'] === 'upload' && isset($_FILES['file'])) {
    $remote_file = $current_full_path . '/' . basename($_FILES['file']['name']);
    if (ssh2_scp_send($connection, $_FILES['file']['tmp_name'], $remote_file, 0644)) { $message = "<div class='success'>File uploaded successfully!</div>"; }
}

// === SINGLE ITEM DELETE ===
if (isset($_GET['delete'])) {
    $remote_target = $current_full_path . '/' . str_replace(array('/', '\\'), '', $_GET['delete']);
    if (delete_remote_item($connection, $remote_target)) { header("Location: ?dir=" . urlencode($current_sub_dir)); exit; }
}

// === BULK OPERATIONS & CLIPBOARD HANDLING ===
if (isset($_POST['action']) && $_POST['action'] === 'bulk_action' && isset($_POST['bulk_items']) && is_array($_POST['bulk_items'])) {
    $bulk_action = $_POST['bulk_operation'];
    $success_count = 0;
    
    // CLIPBOARD ACTIONS (Copy / Cut)
    if ($bulk_action === 'copy' || $bulk_action === 'cut') {
        $_SESSION['clipboard_items'] = array();
        foreach ($_POST['bulk_items'] as $item) {
            $_SESSION['clipboard_items'][] = $current_full_path . '/' . str_replace(array('/', '\\', '..'), '', $item);
        }
        $_SESSION['clipboard_action'] = $bulk_action;
        $message = "<div class='success'>" . count($_SESSION['clipboard_items']) . " item(s) added to clipboard (" . strtoupper($bulk_action) . ")!</div>";
    }
    // BULK ARCHIVE TO TAR.GZ
    elseif ($bulk_action === 'zip') {
        $archive_name = !empty($_POST['bulk_zip_name']) ? preg_replace('/[^a-zA-Z0-9_\-]/', '', $_POST['bulk_zip_name']) : 'archive';
        $escaped_items = array();
        foreach ($_POST['bulk_items'] as $item) { $escaped_items[] = escapeshellarg(str_replace(array('/', '\\', '..'), '', $item)); }
        $archive_file = $current_full_path . '/' . $archive_name . '.tar.gz';
        $cmd = "cd " . escapeshellarg($current_full_path) . " && tar -czf " . escapeshellarg($archive_file) . " " . implode(' ', $escaped_items) . " && chmod 0644 " . escapeshellarg($archive_file);
        $stream = ssh2_exec($connection, $cmd);
        if ($stream) { stream_set_blocking($stream, true); stream_get_contents($stream); fclose($stream); $message = "<div class='success'>Archive <strong>$archive_name.tar.gz</strong> created!</div>"; }
    } 
    // BULK DELETE or CHMOD
    else {
        foreach ($_POST['bulk_items'] as $item) {
            $target_path = $current_full_path . '/' . str_replace(array('/', '\\', '..'), '', $item);
            if ($bulk_action === 'delete' && delete_remote_item($connection, $target_path)) { $success_count++; }
            if ($bulk_action === 'chmod' && !empty($_POST['bulk_chmod_val'])) {
                $val = preg_replace('/[^0-7]/', '', $_POST['bulk_chmod_val']);
                $stream = ssh2_exec($connection, "chmod " . escapeshellarg($val) . " " . escapeshellarg($target_path));
                if ($stream) { fclose($stream); $success_count++; }
            }
        }
        if ($success_count > 0) { $message = "<div class='success'>Bulk action ($bulk_action) completed for $success_count item(s)!</div>"; }
    }
}

// === PASTE OPERATION EXECUTION ===
if (isset($_POST['action']) && $_POST['action'] === 'paste_items' && isset($_SESSION['clipboard_items']) && is_array($_SESSION['clipboard_items'])) {
    $action_cmd = ($_SESSION['clipboard_action'] === 'copy') ? "cp -r" : "mv";
    $paste_count = 0;
    
    foreach ($_SESSION['clipboard_items'] as $source_path) {
        if (empty($source_path)) continue;
        $item_basename = basename($source_path);
        $destination_path = $current_full_path . '/' . $item_basename;
        
        // Prevent copying an item onto itself
        if ($source_path === $destination_path) continue;
        
        $cmd = "$action_cmd " . escapeshellarg($source_path) . " " . escapeshellarg($destination_path);
        $stream = ssh2_exec($connection, $cmd);
        if ($stream) { stream_set_blocking($stream, true); stream_get_contents($stream); fclose($stream); $paste_count++; }
    }
    
    if ($_SESSION['clipboard_action'] === 'cut') {
        unset($_SESSION['clipboard_items']); unset($_SESSION['clipboard_action']);
    }
    $message = "<div class='success'>Successfully pasted $paste_count item(s) into current directory!</div>";
}

// === FILE EDITOR SAVING ===
if (isset($_POST['action']) && $_POST['action'] === 'save_file' && !empty($_POST['edit_file'])) {
    // Безопасно изолируем имя файла от инъекций путей
    $edit_file_basename = basename($_POST['edit_file']);
    $remote_file_path = $current_full_path . '/' . $edit_file_basename;
    
    // Создаем временный локальный файл для записи нового содержимого
    $tmp_file = tempnam(sys_get_temp_dir(), 'sftp_'); 
    file_put_contents($tmp_file, $_POST['content']);
    
    // Передаем файл по протоколу SCP/SFTP от имени cayenne
    if (ssh2_scp_send($connection, $tmp_file, $remote_file_path, 0644)) { 
        $message = "<div class='success'>File saved successfully!</div>"; 
    } else {
        $message = "<div class='error'>Error: Failed to write to file. Check permissions.</div>";
    }
    @unlink($tmp_file);
}

// === READ EDITOR CONTENT ===
if (isset($_GET['edit'])) {
    $editor_file = str_replace(array('/', '\\'), '', $_GET['edit']);
    $remote_file_path = $current_full_path . '/' . $editor_file;
    
    // Используем SSH команду cat для быстрого и надежного чтения контента
    $stream = ssh2_exec($connection, "cat " . escapeshellarg($remote_file_path));
    if ($stream) { 
        stream_set_blocking($stream, true); 
        $editor_content = stream_get_contents($stream); 
        fclose($stream); 
    }
}

// === DIRECTORY LISTING ===
$files_list = array();
$cmd = "code_format() { for f in \"\$1\"/*; do [ -e \"\$f\" ] || continue; if [ -d \"\$f\" ]; then echo \"d|0|$(stat -c '%Y' \"\$f\")|$(stat -c '%a' \"\$f\")|$(stat -c '%U:%G' \"\$f\")|$(basename \"\$f\")\"; else echo \"f|$(stat -c '%s' \"\$f\")|$(stat -c '%Y' \"\$f\")|$(stat -c '%a' \"\$f\")|$(stat -c '%U:%G' \"\$f\")|$(basename \"\$f\")\"; fi; done; }; code_format " . escapeshellarg($current_full_path);
$stream = ssh2_exec($connection, $cmd);
stream_set_blocking($stream, true); $output = stream_get_contents($stream); fclose($stream);

if (!empty($output)) {
    foreach (explode("\n", trim($output)) as $line) {
        $parts = explode('|', $line, 6); if (count($parts) < 6) continue;
        
        $files_list[] = array(
            'is_dir' => ($parts[0] === 'd'),
            'size'   => ($parts[0] === 'd' ? '-' : round((int)$parts[1] / 1024, 2) . ' KB'),
            'mtime'  => date('Y-m-d H:i:s', (int)$parts[2]),
            'perms'  => $parts[3],
            'owner'  => $parts[4],
            'name'   => $parts[5]
        );
    }
    
    // Безопасная сортировка: сначала папки, затем файлы
    usort($files_list, function($a, $b) { 
        if ($a['is_dir'] && !$b['is_dir']) return -1; 
        if (!$a['is_dir'] && $b['is_dir']) return 1; 
        return strcasecmp($a['name'], $b['name']); 
    });
}

$parent_dir = '';
if (!empty($current_sub_dir)) { 
    $dir_parts = explode('/', $current_sub_dir); 
    array_pop($dir_parts); 
    $parent_dir = implode('/', $dir_parts); 
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ultimate SSH2 SFTP File Manager</title>
    <style>
        body { font-family: system-ui, sans-serif; background: #f3f4f6; padding: 20px; margin: 0; color: #1f2937; }
        .wrapper { max-width: 1200px; margin: 0 auto; background: #fff; padding: 20px; border-radius: 6px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
        .path { background: #f9fafb; border: 1px solid #e5e7eb; padding: 10px 14px; border-radius: 4px; font-family: monospace; margin: 15px 0; font-size: 14px; word-break: break-all; }
        .path a { color: #2563eb; text-decoration: none; font-weight: bold; padding: 2px 4px; border-radius: 3px; }
        .path a:hover { background: #dbeafe; text-decoration: underline; }
        .panel { display: flex; gap: 10px; background: #f4f4f5; padding: 12px; border-radius: 4px; margin-bottom: 15px; flex-wrap: wrap; align-items: center; border: 1px solid #e5e7eb; }
        .bulk-bar { background: #eff6ff; border: 1px solid #bfdbfe; padding: 12px; border-radius: 4px; margin-bottom: 15px; display: flex; align-items: center; gap: 10px; font-size: 14px; }
        .clipboard-bar { background: #fef3c7; border: 1px solid #fde68a; color: #92400e; padding: 12px; border-radius: 4px; margin-bottom: 15px; display: flex; align-items: center; gap: 15px; font-size: 14px; }
        input[type="text"], input[type="file"], select { padding: 5px 10px; border: 1px solid #d1d5db; border-radius: 4px; font-size: 13px; background: #fff; }
        button { background: #2563eb; color: white; border: none; padding: 6px 12px; border-radius: 4px; cursor: pointer; font-size: 13px; font-weight: 500; }
        button:hover { background: #1d4ed8; }
        .btn-success { background: #16a34a; } .btn-success:hover { background: #15803d; }
        .btn-danger { background: #dc2626; } .btn-danger:hover { background: #b91c1c; }
        .btn-warning { background: #d97706; color: white; } .btn-warning:hover { background: #b45309; }
        table { width: 100%; border-collapse: collapse; margin-top: 10px; }
        th, td { padding: 10px; text-align: left; border-bottom: 1px solid #e5e7eb; font-size: 14px; vertical-align: middle; }
        th { background: #f9fafb; color: #4b5563; }
        tr:hover { background: #f9fafb; }
        .success { background: #def7ec; color: #03543f; padding: 10px; border-radius: 4px; margin-bottom: 10px; font-size: 14px; }
        .error { background: #fde8e8; color: #9b1c1c; padding: 10px; border-radius: 4px; margin-bottom: 10px; font-size: 14px; }
        .editor-box, .console-box { background: #fff; border: 1px solid #2563eb; border-radius: 6px; padding: 15px; margin-bottom: 20px; }
        .console-box { border-color: #4b5563; background: #1f2937; color: #f9fafb; }
        textarea { width: 100%; height: 300px; font-family: monospace; font-size: 14px; margin: 10px 0; padding: 10px; border: 1px solid #ccc; box-sizing: border-box; border-radius: 4px; background: #f8f9fa; }
        .console-box textarea { background: #111827; color: #10b981; border-color: #374151; height: 150px; }
        .console-output { background: #111827; color: #f3f4f6; font-family: monospace; padding: 15px; border-radius: 4px; border: 1px solid #374151; white-space: pre-wrap; max-height: 200px; overflow-y: auto; margin-top: 10px; }
        .action-links a { margin-right: 8px; text-decoration: none; color: #2563eb; font-size: 13px; cursor: pointer; }
        .action-links a:hover { text-decoration: underline; }
        .action-links a.del { color: #dc2626; }
        .inline-panel { display: none; background: #f9fafb; padding: 8px; border: 1px solid #e5e7eb; margin-top: 5px; border-radius: 4px; }
    </style>
    <script>
        function toggleInline(id) {
            var el = document.getElementById(id);
            if (el.style.display === 'block') { el.style.display = 'none'; } 
            else {
                var panels = document.getElementsByClassName('inline-panel');
                for (var i = 0; i < panels.length; i++) panels[i].style.display = 'none';
                el.style.display = 'block';
            }
        }
        function toggleSelectAll(master) {
            var checkboxes = document.getElementsByClassName('bulk-checkbox');
            for (var i = 0; i < checkboxes.length; i++) { checkboxes[i].checked = master.checked; }
        }
        function handleBulkSelect(selectEl) {
            var chmodInput = document.getElementById('bulk-chmod-container');
            var zipInput = document.getElementById('bulk-zip-container');
            chmodInput.style.display = 'none'; document.getElementById('bulk-chmod-val').required = false;
            zipInput.style.display = 'none'; document.getElementById('bulk-zip-name').required = false;
            if (selectEl.value === 'chmod') {
                chmodInput.style.display = 'inline-block'; document.getElementById('bulk-chmod-val').required = true;
            } else if (selectEl.value === 'zip') {
                zipInput.style.display = 'inline-block'; document.getElementById('bulk-zip-name').required = true;
            }
        }
    </script>
</head>
<body>

<div class="wrapper">
    <h3 style="margin-top:0;">📂 Pro SSH2 File Manager (Clipboard & Breadcrumbs Enabled)</h3>
    
    <?php if (!empty($message)) echo $message; ?>

    <!-- GLOBAL HIDDEN FORM FOR SINGLE OPERATIONS -->
    <form id="single-action-form" method="POST" style="display:none;">
        <input type="hidden" name="action" value="single_action">
        <input type="hidden" id="op_type" name="op_type" value="">
        <input type="hidden" id="old_name" name="old_name" value="">
        <input type="hidden" id="new_name" name="new_name" value="">
        <input type="hidden" id="item_name" name="item_name" value="">
        <input type="hidden" id="chmod_val" name="chmod_val" value="">
        <input type="hidden" id="folder_name" name="folder_name" value="">
        <input type="hidden" id="file_name" name="file_name" value="">
    </form>
    <script>
        function submitMkdir() {
            var val = document.getElementById('top_folder_name').value; if(!val) return;
            document.getElementById('op_type').value = 'mkdir'; document.getElementById('folder_name').value = val;
            document.getElementById('single-action-form').submit();
        }
        function submitMkfile() {
            var val = document.getElementById('top_file_name').value; if(!val) return;
            document.getElementById('op_type').value = 'mkfile'; document.getElementById('file_name').value = val;
            document.getElementById('single-action-form').submit();
        }
        function submitRename(index, oldName) {
            var val = document.getElementById('input-ren-' + index).value; if(!val) return;
            document.getElementById('op_type').value = 'rename'; document.getElementById('old_name').value = oldName; document.getElementById('new_name').value = val;
            document.getElementById('single-action-form').submit();
        }
        function submitChmod(index, itemName) {
            var val = document.getElementById('input-chm-' + index).value; if(!val) return;
            document.getElementById('op_type').value = 'chmod'; document.getElementById('item_name').value = itemName; document.getElementById('chmod_val').value = val;
            document.getElementById('single-action-form').submit();
        }
    </script>

    <!-- FILE EDITOR -->
    <?php if (!empty($editor_file)): ?>
    <div class="editor-box">
        <strong>📝 Editing File:</strong> <span style="font-family: monospace;"><?php echo htmlspecialchars($editor_file); ?></span>
        <form method="POST">
            <input type="hidden" name="action" value="save_file">
            <input type="hidden" name="edit_file" value="<?php echo htmlspecialchars($editor_file); ?>">
            <textarea name="content"><?php echo htmlspecialchars($editor_content); ?></textarea>
            <button type="submit" class="btn-success">💾 Save Changes</button>
            <a href="?dir=<?php echo urlencode($current_sub_dir); ?>" style="margin-left: 10px; color: #4b5563; text-decoration: none; font-size: 14px;">Cancel</a>
        </form>
    </div>
    <?php endif; ?>

    <!-- CLICKABLE BREADCRUMBS GENERATOR -->
    <div class="path">
        <strong>Location:</strong>
        <a href="?dir=">Root</a> /
        <?php 
        if (!empty($current_sub_dir)) {
            $parts = explode('/', $current_sub_dir);
            $accumulated = '';
            foreach ($parts as $idx => $part) {
                if (empty($part)) continue;
                $accumulated .= ($idx == 0 ? '' : '/') . $part;
                echo '<a href="?dir=' . urlencode($accumulated) . '">' . htmlspecialchars($part) . '</a> / ';
            }
        } else {
            echo '<span style="color:#6b7280;">(web2018 core)</span>';
        }
        ?>
    </div>

    <!-- PERSISTENT CLIPBOARD NOTIFICATION & ACTION BAR -->
    <?php if (isset($_SESSION['clipboard_items']) && count($_SESSION['clipboard_items']) > 0): ?>
    <div class="clipboard-bar">
        <span>📋 <strong>Clipboard Status:</strong> <?php echo count($_SESSION['clipboard_items']); ?> item(s) are ready to be <strong><?php echo strtoupper($_SESSION['clipboard_action']); ?>ED</strong>.</span>
        <form method="POST" style="margin:0; display:inline;">
            <input type="hidden" name="action" value="paste_items">
            <button type="submit" class="btn-warning" style="font-weight:bold;">📋 Paste Here</button>
        </form>
        <a href="?dir=<?php echo urlencode($current_sub_dir); ?>&clear_clipboard=1" style="color:#dc2626; font-size:13px; text-decoration:none;">[Clear Clipboard]</a>
    </div>
    <?php endif; ?>

    <!-- CONTROL PANEL TOOLS -->
    <div class="panel">
        <div style="display:flex; gap:5px; align-items:center; border-right:1px solid #d1d5db; padding-right:10px;">
            <input type="text" id="top_folder_name" placeholder="New Folder Name">
            <button type="button" onclick="submitMkdir()">Create Folder</button>
        </div>
        <div style="display:flex; gap:5px; align-items:center; border-right:1px solid #d1d5db; padding-right:10px;">
            <input type="text" id="top_file_name" placeholder="New File Name">
            <button type="button" onclick="submitMkfile()">Create File</button>
        </div>
        <form method="POST" enctype="multipart/form-data" style="display:flex; gap:5px; align-items:center;">
            <input type="hidden" name="action" value="upload">
            <input type="file" name="file" required>
            <button type="submit">Upload File</button>
        </form>
    </div>

    <!-- BULK ACTIONS FORM -->
    <form method="POST">
        <input type="hidden" name="action" value="bulk_action">
        
        <div class="bulk-bar">
            <strong>With Selected Items:</strong>
            <select name="bulk_operation" onchange="handleBulkSelect(this)">
                <option value="copy">📋 Copy Items</option>
                <option value="cut">✂️ Cut (Move) Items</option>
                <option value="delete">❌ Delete Items Permanently</option>
                <option value="chmod">🔑 Change Permissions (CHMOD)</option>
                <option value="zip">📦 Pack into Tar.Gz Archive</option>
            </select>
            
            <div id="bulk-chmod-container" style="display:none;">
                <input type="text" id="bulk-chmod-val" name="bulk_chmod_val" placeholder="e.g. 755" style="width:80px;" maxlength="4">
            </div>
            
            <div id="bulk-zip-container" style="display:none;">
                <input type="text" id="bulk-zip-name" name="bulk_zip_name" placeholder="Archive name" style="width:180px;">
            </div>
            
            <button type="submit" class="btn-danger" onclick="return confirm('Apply this bulk action?');">Apply Action</button>
        </div>
        <table>
            <thead>
                <tr>
                    <th style="width: 30px;"><input type="checkbox" onclick="toggleSelectAll(this)"></th>
                    <th>Name</th>
                    <th style="width: 140px;">Owner:Group</th>
                    <th style="width: 70px;">Chmod</th>
                    <th style="width: 90px;">Size</th>
                    <th style="width: 150px;">Last Modified</th>
                    <th style="width: 340px;">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!empty($current_sub_dir)): ?>
                <tr>
                    <td></td>
                    <td colspan="6">📁 <a href="?dir=<?php echo urlencode($parent_dir); ?>"><strong>.. (Up to Parent Directory)</strong></a></td>
                </tr>
                <?php endif; ?>

                <?php if (empty($files_list)): ?>
                <tr><td colspan="7" style="text-align:center; color:#9ca3af; padding: 20px;">This directory is empty</td></tr>
                <?php else: ?>
                    <?php foreach ($files_list as $index => $item): ?>
                    <tr>
                        <td>
                            <input type="checkbox" name="bulk_items[]" value="<?php echo htmlspecialchars($item['name']); ?>" class="bulk-checkbox">
                        </td>
                        <td>
                            <?php if ($item['is_dir']): ?>
                                📁 <?php $next_link = empty($current_sub_dir) ? $item['name'] : $current_sub_dir . '/' . $item['name']; ?>
                                <a href="?dir=<?php echo urlencode($next_link); ?>"><strong><?php echo htmlspecialchars($item['name']); ?></strong></a>
                            <?php else: ?>
                                📄 <?php echo htmlspecialchars($item['name']); ?>
                            <?php endif; ?>

                            <!-- Inline form layer for rename -->
                            <div id="pnl-ren-<?php echo $index; ?>" class="inline-panel">
                                <div style="display:flex; gap:5px; margin:0; padding:0;">
                                    <input type="text" id="input-ren-<?php echo $index; ?>" value="<?php echo htmlspecialchars($item['name']); ?>" style="width:180px;">
                                    <button type="button" class="btn-success" onclick="submitRename(<?php echo $index; ?>, '<?php echo addslashes($item['name']); ?>')">OK</button>
                                </div>
                            </div>

                            <!-- Inline form layer for chmod -->
                            <div id="pnl-chm-<?php echo $index; ?>" class="inline-panel">
                                <div style="display:flex; gap:5px; margin:0; padding:0;">
                                    <input type="text" id="input-chm-<?php echo $index; ?>" value="<?php echo htmlspecialchars($item['perms']); ?>" style="width:60px;" maxlength="4">
                                    <button type="button" class="btn-success" onclick="submitChmod(<?php echo $index; ?>, '<?php echo addslashes($item['name']); ?>')">OK</button>
                                </div>
                            </div>
                        </td>
                        <td style="font-family: monospace; color: #4b5563;">
                            <?php echo htmlspecialchars($item['owner']); ?>
                        </td>
                        <td style="font-family: monospace; font-weight: bold; color: #1e3a8a;">
                            <?php echo htmlspecialchars($item['perms']); ?>
                        </td>
                        <td><?php echo $item['size']; ?></td>
                        <td style="color: #6b7280; font-size: 13px;"><?php echo $item['mtime']; ?></td>
                        <td class="action-links">
                            <?php if (!$item['is_dir']): ?>
                                <a href="?dir=<?php echo urlencode($current_sub_dir); ?>&edit=<?php echo urlencode($item['name']); ?>">✏️ Edit</a>
                                <a href="?dir=<?php echo urlencode($current_sub_dir); ?>&download=<?php echo urlencode($item['name']); ?>">📥 Download</a>
                                <?php 
                                $ext = strtolower(pathinfo($item['name'], PATHINFO_EXTENSION));
                                if ($ext === 'zip' || $ext === 'gz'): 
                                ?>
                                    <a href="?dir=<?php echo urlencode($current_sub_dir); ?>&unzip=<?php echo urlencode($item['name']); ?>" style="color: #16a34a; font-weight: bold;">📦 Extract</a>
                                <?php endif; ?>
                            <?php endif; ?>
                            <a onclick="toggleInline('pnl-ren-<?php echo $index; ?>')">🔄 Rename</a>
                            <a onclick="toggleInline('pnl-chm-<?php echo $index; ?>')">🔑 Chmod</a>
                            <a href="?dir=<?php echo urlencode($current_sub_dir); ?>&delete=<?php echo urlencode($item['name']); ?>" class="del" onclick="return confirm('Delete this permanently?');">❌ Delete</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </form>

    <!-- LIVE PHP WEB SERVER CONSOLE -->
    <div class="console-box" style="margin-top: 40px;">
        <h4 style="margin: 0 0 10px 0; color: #10b981;">💻 Web Server Console (Execute Raw PHP CLI)</h4>
        <form method="POST">
            <input type="hidden" name="action" value="run_php">
            <textarea name="php_code" placeholder="// Enter your execution string here without tags. E.g.:&#10;echo 'System Root: ' . getcwd();&#10;print_r($_SERVER);"><?php echo isset($_POST['php_code']) ? htmlspecialchars($_POST['php_code']) : ''; ?></textarea>
            <button type="submit" class="btn-success">▶️ Run PHP Script</button>
        </form>
        
        <?php if (!empty($php_output) || isset($_POST['php_code'])): ?>
        <div class="console-output">
            <strong>Terminal Buffer Output:</strong><br>
            <?php echo htmlspecialchars($php_output); ?>
        </div>
        <?php endif; ?>
    </div>
</div>

</body>
</html>

