<?php
// Check if user is authenticated
if (!defined('AUTH_USER')) {
    header('Location: login.php');
    exit();
}

require_once 'libs/WordPressManager.php';
use WHP\WordPressManager;

// Helper function for permission checking
function check_permission($permission) {
    // For now, return true for basic permissions, root for admin permissions
    $adminPermissions = ['wordpress_manage_all', 'wordpress_recommendations'];
    if (in_array($permission, $adminPermissions)) {
        return AUTH_USER === 'root';
    }
    return true; // Basic permissions allowed for all users
}

// Simple permission check - for now, any authenticated user can access
// In the future, this could be expanded to use a proper permission system
if (!defined('AUTH_USER')) {
    die('Access denied. You must be logged in to access WordPress management.');
}

$wpManager = new WordPressManager();
$isRoot = AUTH_USER === 'root';

// Get database connection
$mysql = new mysqlmgmt();
$db = $mysql->getMySQLConnection();
$db->exec("USE whp");

if ($isRoot) {
    $stmt = $db->query("SELECT * FROM wordpress_sites ORDER BY user, domain");
} else {
    $stmt = $db->prepare("SELECT * FROM wordpress_sites WHERE user = ? ORDER BY domain");
    $stmt->execute([AUTH_USER]);
}
$sites = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get container types and their WP-CLI support status
$containerTypes = $wpManager->getWpCliContainerTypes();

// Get user sites that support WordPress (have WP-CLI enabled containers)
// For root, get all sites; for regular users, get their sites only
$userWordPressSites = $wpManager->getUserWordPressSites($isRoot ? 'root' : AUTH_USER);

// Get recommended plugins
$recommendedPlugins = $wpManager->getRecommendedPlugins();

// Get available backup targets for the user
$backupTargets = [];
if ($isRoot) {
    $stmt = $db->query("SELECT id, name, type, owner FROM backup_targets WHERE type != 'local' ORDER BY owner, name");
} else {
    $stmt = $db->prepare("SELECT id, name, type, owner FROM backup_targets WHERE (owner = ? OR is_global = 1) AND type != 'local' ORDER BY CASE WHEN owner = ? THEN 0 ELSE 1 END, name");
    $stmt->execute([AUTH_USER, AUTH_USER]);
}
$backupTargets = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-end align-items-center mb-4">
                <?php if ($isRoot): ?>
                <button class="btn btn-secondary me-2" data-bs-toggle="modal" data-bs-target="#recommendedPluginsModal">
                    <i class="fa fa-cog"></i> Manage Recommended Plugins
                </button>
                <?php endif; ?>
                <div class="btn-group">
                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#installModal">
                        <i class="fa fa-plus"></i> Install WordPress
                    </button>
                    <button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" aria-expanded="false">
                        <span class="visually-hidden">Toggle Dropdown</span>
                    </button>
                    <ul class="dropdown-menu">
                        <li><a class="dropdown-item" href="#" onclick="showInstallModal()">
                            <i class="fa fa-plus"></i> Install New WordPress
                        </a></li>
                        <li><a class="dropdown-item" href="#" onclick="showImportModal()">
                            <i class="fa fa-upload"></i> Import Existing WordPress
                        </a></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
    
    <?php if ($isRoot): ?>
    <!-- WP-CLI Container Support Management (collapsed by default; root-only admin tooling) -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="accordion" id="containerWpSupportAccordion">
                <div class="accordion-item">
                    <h2 class="accordion-header" id="containerWpSupportHeader">
                        <button class="accordion-button collapsed" type="button"
                                data-bs-toggle="collapse"
                                data-bs-target="#containerWpSupportBody"
                                aria-expanded="false"
                                aria-controls="containerWpSupportBody">
                            Container WordPress Support
                            <small class="text-muted ms-2">— Enable WP-CLI support for container types</small>
                        </button>
                    </h2>
                    <div id="containerWpSupportBody" class="accordion-collapse collapse"
                         aria-labelledby="containerWpSupportHeader"
                         data-bs-parent="#containerWpSupportAccordion">
                        <div class="accordion-body">
                            <table class="table table-sm mb-0">
                                <thead>
                                    <tr>
                                        <th>Container Type</th>
                                        <th>Description</th>
                                        <th>WordPress Support</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($containerTypes as $containerType): ?>
                                    <tr>
                                        <td><code><?php echo htmlspecialchars($containerType['name']); ?></code></td>
                                        <td><?php echo htmlspecialchars($containerType['description']); ?></td>
                                        <td>
                                            <div class="form-check form-switch">
                                                <input class="form-check-input wp-cli-toggle" type="checkbox"
                                                       data-container="<?php echo htmlspecialchars($containerType['name']); ?>"
                                                       <?php echo $containerType['wp_cli_enabled'] ? 'checked' : ''; ?>>
                                                <label class="form-check-label">
                                                    <?php echo $containerType['wp_cli_enabled'] ? 'Enabled' : 'Disabled'; ?>
                                                </label>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <!-- WordPress Sites -->
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">WordPress Sites</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($sites)): ?>
                        <p class="text-muted">No WordPress sites found. Click "Install WordPress" to create your first site.</p>
                    <?php else: ?>
                        <!-- Search and Filter Controls -->
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fa fa-search"></i></span>
                                    <input type="text" class="form-control" id="wpSearchInput" placeholder="Search WordPress sites...">
                                </div>
                            </div>
                            <?php if ($isRoot): ?>
                            <div class="col-md-3">
                                <select class="form-select" id="wpUserFilter">
                                    <option value="">All Users</option>
                                    <?php
                                    $users = array_unique(array_column($sites, 'user'));
                                    sort($users);
                                    foreach ($users as $user):
                                    ?>
                                    <option value="<?php echo htmlspecialchars($user); ?>"><?php echo htmlspecialchars($user); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <?php endif; ?>
                            <div class="col-md-<?php echo $isRoot ? '3' : '6'; ?> text-end">
                                <small class="text-muted" id="wpTableInfo"></small>
                            </div>
                        </div>

                        <div class="table-responsive">
                            <table class="table table-hover" id="wpSitesTable">
                                <thead>
                                    <tr>
                                        <?php if ($isRoot): ?><th>User</th><?php endif; ?>
                                        <th>Domain</th>
                                        <th>Version</th>
                                        <th>Status</th>
                                        <th>Auto Updates</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($sites as $site): ?>
                                    <tr data-site-id="<?php echo $site['id']; ?>" 
                                        data-container="<?php echo htmlspecialchars($site['container_name']); ?>"
                                        data-user="<?php echo htmlspecialchars($site['user']); ?>"
                                        data-backup-target-id="<?php echo htmlspecialchars($site['preferred_backup_target_id'] ?? ''); ?>"
                                        data-auto-backup="<?php echo $site['auto_backup_before_update'] ? 'true' : 'false'; ?>">
                                        <?php if ($isRoot): ?>
                                        <td><?php echo htmlspecialchars($site['user']); ?></td>
                                        <?php endif; ?>
                                        <td>
                                            <a href="https://<?php echo htmlspecialchars($site['domain']); ?>" target="_blank">
                                                <?php echo htmlspecialchars($site['domain']); ?>
                                            </a>
                                            <?php if ($site['is_staging']): ?>
                                            <span class="badge bg-warning ms-1">Staging</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="wp-version<?php echo empty($site['wp_version']) ? ' text-muted' : ''; ?>"
                                                  data-site-id="<?php echo $site['id']; ?>"
                                                  <?php if (!empty($site['wp_version_checked_at'])): ?>
                                                  title="Last checked <?php echo htmlspecialchars($site['wp_version_checked_at']); ?>"
                                                  <?php endif; ?>>
                                                <?php echo htmlspecialchars($site['wp_version'] ?: 'Unknown'); ?>
                                            </span>
                                            <a href="#" class="wp-version-refresh ms-1 text-muted small"
                                               data-site-id="<?php echo $site['id']; ?>"
                                               title="Refresh version from container"
                                               onclick="refreshWPVersion(<?php echo $site['id']; ?>); return false;">
                                                <i class="fa fa-refresh"></i>
                                            </a>
                                        </td>
                                        <td>
                                            <span class="badge bg-<?php echo $site['status'] === 'active' ? 'success' : 'warning'; ?>">
                                                <?php echo ucfirst($site['status']); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <div class="form-check form-switch form-check-inline">
                                                <input class="form-check-input auto-update-toggle" type="checkbox" 
                                                       data-type="core" <?php echo $site['auto_update_core'] ? 'checked' : ''; ?>>
                                                <label class="form-check-label small">Core</label>
                                            </div>
                                            <div class="form-check form-switch form-check-inline">
                                                <input class="form-check-input auto-update-toggle" type="checkbox" 
                                                       data-type="plugins" <?php echo $site['auto_update_plugins'] ? 'checked' : ''; ?>>
                                                <label class="form-check-label small">Plugins</label>
                                            </div>
                                            <div class="form-check form-switch form-check-inline">
                                                <input class="form-check-input auto-update-toggle" type="checkbox" 
                                                       data-type="themes" <?php echo $site['auto_update_themes'] ? 'checked' : ''; ?>>
                                                <label class="form-check-label small">Themes</label>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="dropdown">
                                                <button type="button" class="btn btn-sm btn-outline-primary dropdown-toggle" 
                                                        data-bs-toggle="dropdown" data-bs-auto-close="outside">
                                                    Actions
                                                </button>
                                                <ul class="dropdown-menu dropdown-menu-end">
                                                    <li>
                                                        <a class="dropdown-item" href="#" onclick="createLoginLink(<?php echo $site['id']; ?>)">
                                                            <i class="fa fa-sign-in-alt"></i> Auto Login
                                                        </a>
                                                    </li>
                                                    <li>
                                                        <a class="dropdown-item" href="#" onclick="showUpdateModal(<?php echo $site['id']; ?>)">
                                                            <i class="fa fa-sync"></i> Update Now
                                                        </a>
                                                    </li>
                                                    <li>
                                                        <a class="dropdown-item" href="#" onclick="showPasswordModal(<?php echo $site['id']; ?>)">
                                                            <i class="fa fa-key"></i> Reset Password
                                                        </a>
                                                    </li>
                                                    <li>
                                                        <a class="dropdown-item" href="#" onclick="showCloneModal(<?php echo $site['id']; ?>)">
                                                            <i class="fa fa-copy"></i> Clone Site
                                                        </a>
                                                    </li>
                                                    <li><hr class="dropdown-divider"></li>
                                                    <li>
                                                        <a class="dropdown-item" href="#" onclick="showSecurityModal(<?php echo $site['id']; ?>)">
                                                            <i class="fa fa-shield-alt"></i> Security Settings
                                                        </a>
                                                    </li>
                                                    <li>
                                                        <a class="dropdown-item" href="#" onclick="showSearchReplaceModal(<?php echo $site['id']; ?>)">
                                                            <i class="fa fa-search"></i> Search & Replace
                                                        </a>
                                                    </li>
                                                    <li>
                                                        <a class="dropdown-item" href="#" onclick="showForceHttpsModal(<?php echo $site['id']; ?>)">
                                                            <i class="fa fa-lock"></i> Force HTTPS
                                                        </a>
                                                    </li>
                                                    <li>
                                                        <a class="dropdown-item" href="#" onclick="backupNow(<?php echo $site['id']; ?>, '<?php echo htmlspecialchars($site['domain'], ENT_QUOTES); ?>')">
                                                            <i class="fa fa-cloud-upload-alt"></i> Backup Now
                                                        </a>
                                                    </li>
                                                    <li>
                                                        <a class="dropdown-item" href="#" onclick="showBackupSettingsModal(<?php echo $site['id']; ?>)">
                                                            <i class="fa fa-hdd"></i> Backup Settings
                                                        </a>
                                                    </li>
                                                    <li>
                                                        <a class="dropdown-item" href="#" onclick="showNotificationSettingsModal(<?php echo $site['id']; ?>)">
                                                            <i class="fa fa-envelope"></i> Notifications
                                                        </a>
                                                    </li>
                                                    <li>
                                                        <a class="dropdown-item" href="#" onclick="showRestoreModal(<?php echo $site['id']; ?>)">
                                                            <i class="fa fa-undo"></i> Restore from Backup
                                                        </a>
                                                    </li>
                                                    <li><hr class="dropdown-divider"></li>
                                                    <li>
                                                        <a class="dropdown-item" href="#" onclick="showPluginsModal(<?php echo $site['id']; ?>)">
                                                            <i class="fa fa-puzzle-piece"></i> Recommended Plugins
                                                        </a>
                                                    </li>
                                                    <li><hr class="dropdown-divider"></li>
                                                    <li>
                                                        <a class="dropdown-item text-danger" href="#" onclick="removeFromManagement(<?php echo $site['id']; ?>)">
                                                            <i class="fa fa-times"></i> Remove from Management
                                                        </a>
                                                    </li>
                                                </ul>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- Pagination Controls -->
                        <div class="d-flex justify-content-center mt-3">
                            <nav id="wpPagination"></nav>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Install WordPress Modal -->
<div class="modal fade" id="installModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="installModalTitle">Install WordPress</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="installForm">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Site</label>
                        <select class="form-select" name="site_id" id="siteSelect" required>
                            <option value="">Select a site...</option>
                            <?php foreach ($userWordPressSites as $site): ?>
                            <option value="<?php echo $site['id']; ?>" 
                                    data-domain="<?php echo htmlspecialchars($site['primary_fqdn']); ?>"
                                    data-container="<?php echo htmlspecialchars($site['container_type_name']); ?>"
                                    data-username="<?php echo htmlspecialchars($site['username']); ?>"
                                    data-site-name="<?php echo htmlspecialchars($site['site_name']); ?>">
                                <?php if ($isRoot): ?>
                                    <?php echo htmlspecialchars($site['username']); ?>/<?php echo htmlspecialchars($site['primary_fqdn']); ?> 
                                <?php else: ?>
                                    <?php echo htmlspecialchars($site['primary_fqdn']); ?> 
                                <?php endif; ?>
                                (<?php echo htmlspecialchars($site['container_type_name']); ?>)
                            </option>
                            <?php endforeach; ?>
                        </select>
                        <small class="form-text text-muted">
                            Only sites using WordPress-supported containers are shown. 
                            <?php if (empty($userWordPressSites)): ?>
                            Create a site on the Sites page first.
                            <?php endif; ?>
                        </small>
                    </div>
                    
                    <div id="installFields" style="display: none;">
                        <div class="mb-3">
                            <label class="form-label">Site Title</label>
                            <input type="text" class="form-control" name="title" required>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="form-label">Admin Username</label>
                                    <input type="text" class="form-control" name="admin_username" value="admin" required>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="form-label">Admin Password</label>
                                    <input type="password" class="form-control" name="admin_password" required>
                                    <small class="form-text text-muted">Strong password required</small>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="form-label">Admin Email</label>
                                    <input type="email" class="form-control" name="admin_email" required>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" name="create_database" value="1" checked>
                            <label class="form-check-label">
                                Create new database (recommended)
                            </label>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Backup Target</label>
                            <select class="form-select" name="backup_target_id">
                                <?php if (empty($backupTargets)): ?>
                                    <option value="">No backup targets configured</option>
                                <?php else: ?>
                                    <option value="">Use default backup target</option>
                                    <?php foreach ($backupTargets as $target): ?>
                                    <option value="<?php echo $target['id']; ?>">
                                        <?php echo htmlspecialchars($target['name']); ?>
                                        (<?php echo strtoupper($target['type']); ?>)
                                        <?php if ($isRoot && $target['owner']): ?>
                                            - <?php echo htmlspecialchars($target['owner']); ?>
                                        <?php endif; ?>
                                    </option>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </select>
                            <small class="form-text text-muted">
                                Select where WordPress backups should be stored
                                <?php if (empty($backupTargets)): ?>
                                    <br><span class="text-warning"><i class="fa fa-warning"></i> <strong>Warning:</strong> No backup targets configured. Auto-backups will be disabled until a backup target is configured.</span>
                                    <br><a href="index.php?page=backups" target="_blank"><i class="fa fa-external-link"></i> Create a backup target</a>
                                <?php else: ?>
                                    <br><a href="index.php?page=backups" target="_blank"><i class="fa fa-external-link"></i> Manage backup targets</a>
                                <?php endif; ?>
                            </small>
                        </div>
                    </div>
                    
                    <div id="importFields" style="display: none;">
                        <div id="importMessage" class="alert alert-info" style="display: none;">
                            <i class="fa fa-info-circle"></i>
                            <strong>WordPress Installation Detected</strong><br>
                            The following information will be imported automatically.
                        </div>
                        <div id="importInfo"></div>
                        
                        <div class="mb-3">
                            <label class="form-label">Backup Target</label>
                            <select class="form-select" name="import_backup_target_id">
                                <?php if (empty($backupTargets)): ?>
                                    <option value="">No backup targets configured</option>
                                <?php else: ?>
                                    <option value="">Use default backup target</option>
                                    <?php foreach ($backupTargets as $target): ?>
                                    <option value="<?php echo $target['id']; ?>">
                                        <?php echo htmlspecialchars($target['name']); ?>
                                        (<?php echo strtoupper($target['type']); ?>)
                                        <?php if ($isRoot && $target['owner']): ?>
                                            - <?php echo htmlspecialchars($target['owner']); ?>
                                        <?php endif; ?>
                                    </option>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </select>
                            <small class="form-text text-muted">
                                Select where WordPress backups should be stored
                                <?php if (empty($backupTargets)): ?>
                                    <br><span class="text-warning"><i class="fa fa-warning"></i> <strong>Warning:</strong> No backup targets configured. Auto-backups will be disabled until a backup target is configured.</span>
                                    <br><a href="index.php?page=backups" target="_blank"><i class="fa fa-external-link"></i> Create a backup target</a>
                                <?php else: ?>
                                    <br><a href="index.php?page=backups" target="_blank"><i class="fa fa-external-link"></i> Manage backup targets</a>
                                <?php endif; ?>
                            </small>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary" id="installSubmitBtn">
                        <i class="fa fa-download"></i> Install WordPress
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Password Reset Modal -->
<div class="modal fade" id="passwordModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Reset Admin Password</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="passwordForm">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">New Password</label>
                        <input type="password" class="form-control" name="new_password">
                        <small class="form-text text-muted">Leave blank to generate a random password</small>
                    </div>
                    <input type="hidden" name="site_id" id="passwordSiteId">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Reset Password</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Clone Site Modal -->
<div class="modal fade" id="cloneModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Clone WordPress Site</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="cloneForm">
                <div class="modal-body">
                    <div class="alert alert-info">
                        <i class="fa fa-info-circle"></i>
                        <strong>Clone WordPress Site</strong><br>
                        This will copy all files, database, and settings from this WordPress site to an existing empty site. The target site must already exist and have no WordPress installation.
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Source Site</label>
                        <input type="text" class="form-control" id="cloneSourceSiteName" readonly>
                        <small class="form-text text-muted">The WordPress site that will be cloned</small>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Target Site <span class="text-danger">*</span></label>
                        <select class="form-control" name="target_site_id" id="cloneTargetSiteId" required>
                            <option value="">Select a target site...</option>
                        </select>
                        <small class="form-text text-muted">Choose an existing site to clone WordPress into. The site must be empty.</small>
                    </div>

                    <div class="alert alert-warning">
                        <i class="fa fa-exclamation-triangle"></i>
                        <strong>Important:</strong>
                        <ul class="mb-0 mt-2">
                            <li>A new database will be created for the cloned site</li>
                            <li>All files will be copied to the target site</li>
                            <li>Database URLs and paths will be updated automatically</li>
                            <li>Security keys will be regenerated</li>
                            <li>This process cannot be undone</li>
                        </ul>
                    </div>

                    <input type="hidden" name="source_site_id" id="cloneSourceSiteId">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fa fa-copy"></i> Clone Site
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Search & Replace Modal -->
<div class="modal fade" id="searchReplaceModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Search & Replace in Database</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="searchReplaceForm">
                <div class="modal-body">
                    <div class="alert alert-warning">
                        <i class="fa fa-exclamation-triangle"></i> This will modify your database. Make sure you have a backup!
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Search For</label>
                        <input type="text" class="form-control" name="search" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Replace With</label>
                        <input type="text" class="form-control" name="replace" required>
                    </div>
                    <input type="hidden" name="site_id" id="searchReplaceSiteId">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Run Search & Replace</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Backup Settings Modal -->
<div class="modal fade" id="notificationSettingsModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Notifications</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="notificationSettingsForm">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Recipient email</label>
                        <input type="email" class="form-control" name="notification_email"
                               id="notificationEmailInput" placeholder="alerts@example.com">
                        <small class="form-text text-muted">
                            Notifications below are only sent if this address is set.
                            Independent of the WordPress admin email.
                        </small>
                    </div>
                    <div class="mb-2 fw-semibold">Send an email when:</div>
                    <div class="form-check mb-1">
                        <input class="form-check-input" type="checkbox" name="notify_backup_complete"
                               id="notifyBackupComplete" value="1">
                        <label class="form-check-label" for="notifyBackupComplete">
                            Backup completes successfully
                        </label>
                    </div>
                    <div class="form-check mb-1">
                        <input class="form-check-input" type="checkbox" name="notify_backup_failed"
                               id="notifyBackupFailed" value="1">
                        <label class="form-check-label" for="notifyBackupFailed">
                            Backup fails
                        </label>
                    </div>
                    <div class="form-check mb-1">
                        <input class="form-check-input" type="checkbox" name="notify_update_complete"
                               id="notifyUpdateComplete" value="1">
                        <label class="form-check-label" for="notifyUpdateComplete">
                            Update completes successfully
                        </label>
                    </div>
                    <div class="form-check mb-1">
                        <input class="form-check-input" type="checkbox" name="notify_update_failed"
                               id="notifyUpdateFailed" value="1">
                        <label class="form-check-label" for="notifyUpdateFailed">
                            Update fails
                        </label>
                    </div>
                    <input type="hidden" name="site_id" id="notificationSettingsSiteId">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="backupSettingsModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Backup Settings</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="backupSettingsForm">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Preferred Backup Target</label>
                        <select class="form-select" name="backup_target_id">
                            <?php if (empty($backupTargets)): ?>
                                <option value="">No backup targets configured</option>
                            <?php else: ?>
                                <option value="">Use default backup target</option>
                                <?php foreach ($backupTargets as $target): ?>
                                <option value="<?php echo $target['id']; ?>">
                                    <?php echo htmlspecialchars($target['name']); ?>
                                    (<?php echo strtoupper($target['type']); ?>)
                                    <?php if ($isRoot && $target['owner']): ?>
                                        - <?php echo htmlspecialchars($target['owner']); ?>
                                    <?php endif; ?>
                                </option>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </select>
                        <small class="form-text text-muted">
                            Select where automatic backups for this WordPress site should be stored
                            <?php if (empty($backupTargets)): ?>
                                <br><span class="text-warning"><i class="fa fa-warning"></i> <strong>Warning:</strong> No backup targets configured. Auto-backups will be disabled until a backup target is configured.</span>
                                <br><a href="index.php?page=backups" target="_blank"><i class="fa fa-external-link"></i> Create a backup target</a>
                            <?php else: ?>
                                <br><a href="index.php?page=backups" target="_blank"><i class="fa fa-external-link"></i> Manage backup targets</a>
                            <?php endif; ?>
                        </small>
                    </div>
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="auto_backup_before_update" id="autoBackupCheck">
                            <label class="form-check-label" for="autoBackupCheck">
                                Automatically backup before updates
                            </label>
                        </div>
                    </div>
                    <input type="hidden" name="site_id" id="backupSettingsSiteId">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save Settings</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Restore from Backup Modal -->
<div class="modal fade" id="restoreModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Restore from Backup</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-warning">
                    <i class="fa fa-exclamation-triangle"></i>
                    <strong>Important:</strong> Restoring from a backup will replace all current files and database content. This action cannot be undone.
                </div>

                <div id="restoreLoadingMessage" style="display: none;">
                    <div class="text-center">
                        <i class="fa fa-spinner fa-spin fa-2x mb-3"></i>
                        <p>Loading available backups...</p>
                    </div>
                </div>

                <div id="restoreNoBackups" style="display: none;">
                    <div class="alert alert-info">
                        <i class="fa fa-info-circle"></i> No backups found for this WordPress site.
                    </div>
                </div>

                <div id="restoreBackupsList" style="display: none;">
                    <div class="mb-3">
                        <label class="form-label">Select Backup to Restore</label>
                        <div class="list-group" id="backupsList">
                            <!-- Backups will be loaded here -->
                        </div>
                    </div>

                    <div id="backupDetails" style="display: none;" class="alert alert-light border">
                        <h6>Selected Backup Details:</h6>
                        <div id="backupDetailsContent"></div>
                    </div>
                </div>

                <input type="hidden" id="restoreSiteId">
                <input type="hidden" id="selectedBackupId">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="confirmRestoreBtn" disabled onclick="confirmRestore()">
                    <i class="fa fa-undo"></i> Restore Backup
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Recommended Plugins Modal -->
<div class="modal fade" id="pluginsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Recommended Plugins</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <?php foreach ($recommendedPlugins as $plugin): ?>
                    <div class="col-md-6 mb-3">
                        <div class="card h-100">
                            <div class="card-body">
                                <h6 class="card-title"><?php echo htmlspecialchars($plugin['name']); ?></h6>
                                <p class="card-text small"><?php echo htmlspecialchars($plugin['description']); ?></p>
                                <span class="badge bg-secondary"><?php echo htmlspecialchars($plugin['category']); ?></span>
                            </div>
                            <div class="card-footer">
                                <button class="btn btn-sm btn-primary install-plugin" 
                                        data-plugin-slug="<?php echo htmlspecialchars($plugin['slug']); ?>">
                                    <i class="fa fa-download"></i> Install
                                </button>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <input type="hidden" id="pluginsSiteId">
            </div>
        </div>
    </div>
</div>

<!-- Security Settings Modal -->
<div class="modal fade" id="securityModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Security Settings</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="securityForm">
                <div class="modal-body">
                    <div class="alert alert-info">
                        <i class="fa fa-shield-alt"></i> Configure WordPress security settings for enhanced protection.
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <h6 class="fw-bold mb-3">Core Security</h6>
                            
                            <div class="form-check form-switch mb-3">
                                <input class="form-check-input" type="checkbox" id="disableFileEditor" name="disable_file_editor">
                                <label class="form-check-label" for="disableFileEditor">
                                    <strong>Disable File Editor</strong>
                                    <small class="text-muted d-block">Prevents editing PHP files from WordPress admin</small>
                                </label>
                            </div>
                            
                            <div class="form-check form-switch mb-3">
                                <input class="form-check-input" type="checkbox" id="disableXmlrpc" name="disable_xmlrpc">
                                <label class="form-check-label" for="disableXmlrpc">
                                    <strong>Disable XML-RPC</strong>
                                    <small class="text-muted d-block">Blocks XML-RPC attacks and pingbacks</small>
                                </label>
                            </div>
                            
                            <div class="form-check form-switch mb-3">
                                <input class="form-check-input" type="checkbox" id="hideWpVersion" name="hide_wp_version">
                                <label class="form-check-label" for="hideWpVersion">
                                    <strong>Hide WordPress Version</strong>
                                    <small class="text-muted d-block">Remove version info from meta tags</small>
                                </label>
                            </div>
                            
                            <div class="form-check form-switch mb-3">
                                <input class="form-check-input" type="checkbox" id="disableDirectoryBrowsing" name="disable_directory_browsing">
                                <label class="form-check-label" for="disableDirectoryBrowsing">
                                    <strong>Disable Directory Browsing</strong>
                                    <small class="text-muted d-block">Prevent listing directory contents</small>
                                </label>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <h6 class="fw-bold mb-3">Advanced Security</h6>
                            
                            <div class="form-check form-switch mb-3">
                                <input class="form-check-input" type="checkbox" id="limitLoginAttempts" name="limit_login_attempts">
                                <label class="form-check-label" for="limitLoginAttempts">
                                    <strong>Limit Login Attempts</strong>
                                    <small class="text-muted d-block">Block brute force login attacks</small>
                                </label>
                            </div>
                            
                            <div class="form-check form-switch mb-3">
                                <input class="form-check-input" type="checkbox" id="securityHeaders" name="security_headers_enabled">
                                <label class="form-check-label" for="securityHeaders">
                                    <strong>Security Headers</strong>
                                    <small class="text-muted d-block">Add security HTTP headers</small>
                                </label>
                            </div>
                            
                            <div class="form-check form-switch mb-3">
                                <input class="form-check-input" type="checkbox" id="blockPhpUploads" name="block_php_uploads">
                                <label class="form-check-label" for="blockPhpUploads">
                                    <strong>Block PHP in Uploads</strong>
                                    <small class="text-muted d-block">Prevent PHP execution in uploads folder</small>
                                </label>
                            </div>
                            
                            <div class="form-check form-switch mb-3">
                                <input class="form-check-input" type="checkbox" id="forceStrongPasswords" name="force_strong_passwords">
                                <label class="form-check-label" for="forceStrongPasswords">
                                    <strong>Force Strong Passwords</strong>
                                    <small class="text-muted d-block">Require complex passwords for all users</small>
                                </label>
                            </div>
                        </div>
                    </div>
                    
                    <hr>
                    
                    <div class="row">
                        <div class="col-12">
                            <h6 class="fw-bold mb-3">Additional Actions</h6>
                            
                            <div class="d-flex flex-wrap gap-2">
                                <button type="button" class="btn btn-outline-warning btn-sm" id="shuffleSalts">
                                    <i class="fa fa-key"></i> Regenerate Security Keys
                                </button>
                                <button type="button" class="btn btn-outline-info btn-sm" id="updateHtaccess">
                                    <i class="fa fa-file-code"></i> Update .htaccess Rules
                                </button>
                                <button type="button" class="btn btn-outline-success btn-sm" id="scanForVulnerabilities">
                                    <i class="fa fa-search"></i> Security Scan
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <input type="hidden" name="site_id" id="securitySiteId">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fa fa-shield-alt"></i> Apply Security Settings
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Force HTTPS Modal -->
<div class="modal fade" id="forceHttpsModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fa fa-lock"></i> Force HTTPS
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="httpsStatusLoading" class="text-center py-3">
                    <i class="fa fa-spinner fa-spin fa-2x text-primary"></i>
                    <p class="mt-2 text-muted">Checking HTTPS redirect status...</p>
                </div>

                <div id="httpsStatusContent" style="display: none;">
                    <div class="alert alert-info">
                        <i class="fa fa-info-circle"></i>
                        <strong>About Force HTTPS:</strong><br>
                        This feature adds redirect rules to your .htaccess file that automatically redirect all HTTP requests to HTTPS.
                    </div>

                    <div class="mb-3">
                        <h6>Current Status:</h6>
                        <div id="httpsCurrentStatus" class="d-flex align-items-center">
                            <!-- Status will be loaded here -->
                        </div>
                    </div>

                    <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" id="forceHttpsToggle" style="width: 3em; height: 1.5em;">
                        <label class="form-check-label ms-2" for="forceHttpsToggle">
                            <strong id="forceHttpsToggleLabel">Enable Force HTTPS</strong>
                            <small class="text-muted d-block">Automatically redirect HTTP to HTTPS</small>
                        </label>
                    </div>

                    <div class="alert alert-warning mt-3" id="httpsWarning" style="display: none;">
                        <i class="fa fa-exclamation-triangle"></i>
                        <strong>Important:</strong> Make sure your domain has a valid SSL certificate before enabling this feature, or visitors may see security warnings.
                    </div>
                </div>

                <input type="hidden" id="forceHttpsSiteId">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="applyForceHttpsBtn" onclick="applyForceHttps()" style="display: none;">
                    <i class="fa fa-save"></i> Apply Changes
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Recommended Plugins Management Modal -->
<div class="modal fade" id="recommendedPluginsModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Manage Recommended Plugins</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-info">
                    <i class="fa fa-info-circle"></i> Manage the list of recommended WordPress plugins that appear during installation.
                </div>
                
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h6 class="mb-0">Current Recommended Plugins</h6>
                    <button type="button" class="btn btn-success btn-sm" id="addPluginBtn">
                        <i class="fa fa-plus"></i> Add Plugin
                    </button>
                </div>
                
                <div class="table-responsive">
                    <table class="table table-striped" id="recommendedPluginsTable">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Slug</th>
                                <th>Category</th>
                                <th>Description</th>
                                <th>Sort Order</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody id="pluginsTableBody">
                            <!-- Plugins will be loaded here -->
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- Add/Edit Plugin Modal -->
<div class="modal fade" id="pluginFormModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="pluginFormTitle">Add Plugin</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="pluginForm">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="pluginName" class="form-label">Plugin Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="pluginName" name="name" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="pluginSlug" class="form-label">Plugin Slug <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="pluginSlug" name="slug" required>
                        <div class="form-text">WordPress.org plugin directory slug (e.g., "wordfence")</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="pluginCategory" class="form-label">Category</label>
                        <select class="form-select" id="pluginCategory" name="category">
                            <option value="">Select Category</option>
                            <option value="Security">Security</option>
                            <option value="SEO">SEO</option>
                            <option value="Performance">Performance</option>
                            <option value="Backup">Backup</option>
                            <option value="Forms">Forms</option>
                            <option value="E-commerce">E-commerce</option>
                            <option value="Social">Social</option>
                            <option value="Content">Content</option>
                            <option value="Analytics">Analytics</option>
                            <option value="Utility">Utility</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label for="pluginDescription" class="form-label">Description</label>
                        <textarea class="form-control" id="pluginDescription" name="description" rows="3"></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label for="pluginInstallUrl" class="form-label">Install URL</label>
                        <input type="text" class="form-control" id="pluginInstallUrl" name="install_url">
                        <div class="form-text">Custom installation URL (leave blank for WordPress.org)</div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="pluginSortOrder" class="form-label">Sort Order</label>
                                <input type="number" class="form-control" id="pluginSortOrder" name="sort_order" value="0">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="pluginActive" name="is_active" checked>
                                    <label class="form-check-label" for="pluginActive">
                                        Active
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <input type="hidden" id="pluginId" name="plugin_id">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary" id="pluginSubmitBtn">Save Plugin</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Define CSRF token for AJAX requests
const nonce = '<?php echo get_csrf_token(); ?>';

// Helper function to escape HTML
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// On-demand refresh for a single site's cached WP version. Triggered by the
// refresh icon next to each row's version. Hits the wp container, writes the
// result back to the wordpress_sites row, and updates the DOM.
function refreshWPVersion(siteId) {
    const versionEl = document.querySelector(`.wp-version[data-site-id="${siteId}"]`);
    const refreshEl = document.querySelector(`.wp-version-refresh[data-site-id="${siteId}"]`);
    if (!versionEl) return;

    const originalText = versionEl.textContent;
    // Show spinner via DOM API (avoid innerHTML for trust-boundary cleanliness).
    while (versionEl.firstChild) versionEl.removeChild(versionEl.firstChild);
    const spinner = document.createElement('i');
    spinner.className = 'fa fa-spinner fa-spin text-muted';
    versionEl.appendChild(spinner);
    if (refreshEl) refreshEl.style.pointerEvents = 'none';

    const formData = new FormData();
    formData.append('action', 'refresh_wp_version');
    formData.append('site_id', siteId);

    fetch('/api/wordpress-ajax.php', {
        method: 'POST',
        headers: { 'X-CSRF-Token': nonce },
        body: formData
    })
    .then(r => r.json())
    .then(data => {
        if (data.success && data.version && data.version !== 'Unknown') {
            versionEl.textContent = data.version;
            versionEl.classList.remove('text-muted');
            if (data.checked_at) versionEl.title = `Last checked ${data.checked_at}`;
        } else {
            versionEl.textContent = 'Unknown';
            versionEl.classList.add('text-muted');
        }
    })
    .catch(err => {
        console.error('refresh_wp_version failed:', err);
        versionEl.textContent = originalText;
    })
    .finally(() => {
        if (refreshEl) refreshEl.style.pointerEvents = '';
    });
}

// Initialize when document is ready
document.addEventListener('DOMContentLoaded', function() {
    console.log('WordPress page JavaScript loaded');

    // WP versions are now rendered server-side from the cached
    // wordpress_sites.wp_version column (kept fresh by the hourly
    // refresh-wp-versions cron + inline writes from install/import/update),
    // so we no longer fetch them per-row at page load. Per-row refresh
    // button calls refreshWPVersion() on demand.
    // Site selection change handler
    document.getElementById('siteSelect').addEventListener('change', function() {
        const selectedOption = this.options[this.selectedIndex];
        const installFields = document.getElementById('installFields');
        const importFields = document.getElementById('importFields');
        const submitBtn = document.getElementById('installSubmitBtn');
        const modalTitle = document.getElementById('installModalTitle');
        
        if (this.value) {
            // Show immediate feedback and disable submit button
            submitBtn.disabled = true;
            
            // Check if we're in import mode to show appropriate loading message
            const isImportMode = importFields.style.display !== 'none';
            if (isImportMode) {
                document.getElementById('importInfo').innerHTML = '<div class="alert alert-info"><i class="fa fa-spinner fa-spin"></i> <strong>Analyzing site...</strong><br>Detecting WordPress installation and gathering configuration details...</div>';
            }
            
            // Check if WordPress is already installed
            const formData = new FormData();
            formData.append('action', 'check_wordpress');
            formData.append('site_id', this.value);
            
            fetch('/api/wordpress-ajax.php', {
                method: 'POST',
                headers: {
                    'X-CSRF-Token': '<?php echo get_csrf_token(); ?>'
                },
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                // Check if we're in import mode
                const isImportMode = importFields.style.display !== 'none';
                
                if (data.exists && isImportMode) {
                    // WordPress is installed and we're in import mode - show import info
                    document.getElementById('importMessage').style.display = 'block';
                    document.querySelector('#importFields .mb-3').style.display = 'block'; // Show backup target
                    submitBtn.disabled = false;
                    
                    // Show WordPress info
                    let infoHtml = '<h6>WordPress Information:</h6>';
                    infoHtml += '<ul class="list-unstyled">';
                    if (data.wp_version) infoHtml += `<li><strong>Version:</strong> ${data.wp_version}</li>`;
                    if (data.site_url) infoHtml += `<li><strong>Site URL:</strong> ${data.site_url}</li>`;
                    if (data.admin_username) infoHtml += `<li><strong>Admin User:</strong> ${data.admin_username}</li>`;
                    if (data.admin_email) infoHtml += `<li><strong>Admin Email:</strong> ${data.admin_email}</li>`;
                    if (data.db_name) infoHtml += `<li><strong>Database:</strong> ${data.db_name}</li>`;
                    infoHtml += '</ul>';
                    
                    document.getElementById('importInfo').innerHTML = infoHtml;
                } else if (!data.exists && isImportMode) {
                    // No WordPress found and we're in import mode
                    document.getElementById('importMessage').style.display = 'none';
                    document.querySelector('#importFields .mb-3').style.display = 'none';
                    submitBtn.disabled = true;
                    document.getElementById('importInfo').innerHTML = '<div class="alert alert-warning"><i class="fa fa-exclamation-triangle"></i> No WordPress installation found on this site.</div>';
                } else if (data.exists && !isImportMode) {
                    // WordPress is installed and we're in install mode - switch to import
                    modalTitle.textContent = 'Import WordPress Site';
                    installFields.style.display = 'none';
                    importFields.style.display = 'block';
                    submitBtn.innerHTML = '<i class="fa fa-upload"></i> Import WordPress';
                    
                    // Remove required attributes from hidden fields
                    installFields.querySelectorAll('[required]').forEach(field => field.removeAttribute('required'));
                    
                    // Show import info
                    document.getElementById('importMessage').style.display = 'block';
                    document.querySelector('#importFields .mb-3').style.display = 'block';
                    submitBtn.disabled = false;
                    
                    let infoHtml = '<h6>WordPress Information:</h6>';
                    infoHtml += '<ul class="list-unstyled">';
                    if (data.wp_version) infoHtml += `<li><strong>Version:</strong> ${data.wp_version}</li>`;
                    if (data.site_url) infoHtml += `<li><strong>Site URL:</strong> ${data.site_url}</li>`;
                    if (data.admin_username) infoHtml += `<li><strong>Admin User:</strong> ${data.admin_username}</li>`;
                    if (data.admin_email) infoHtml += `<li><strong>Admin Email:</strong> ${data.admin_email}</li>`;
                    if (data.db_name) infoHtml += `<li><strong>Database:</strong> ${data.db_name}</li>`;
                    infoHtml += '</ul>';
                    
                    document.getElementById('importInfo').innerHTML = infoHtml;
                } else {
                    // WordPress not installed - show install form
                    modalTitle.textContent = 'Install WordPress';
                    installFields.style.display = 'block';
                    importFields.style.display = 'none';
                    submitBtn.innerHTML = '<i class="fa fa-download"></i> Install WordPress';
                    submitBtn.disabled = false; // Enable the button for installation
                    
                    // Add required attributes back to visible fields
                    installFields.querySelectorAll('input[name="title"], input[name="admin_password"], input[name="admin_email"]').forEach(field => field.setAttribute('required', ''));
                    
                    // Pre-fill domain from site selection
                    const domain = selectedOption.dataset.domain;
                    if (domain) {
                        document.querySelector('input[name="title"]').value = domain;
                    }
                }
            })
            .catch(error => {
                showAlert('danger', 'Error checking WordPress status: ' + error.message);
                submitBtn.disabled = false; // Enable button on error so user can still try
            });
        } else {
            installFields.style.display = 'none';
            importFields.style.display = 'none';
            // Remove required attributes when no site is selected
            installFields.querySelectorAll('[required]').forEach(field => field.removeAttribute('required'));
        }
    });
    
    // WP-CLI support toggles (root only)
    document.querySelectorAll('.wp-cli-toggle').forEach(toggle => {
        toggle.addEventListener('change', function() {
            console.log('WP-CLI toggle clicked');
            const containerName = this.dataset.container;
            const enabled = this.checked;
            
            const formData = new FormData();
            formData.append('action', 'update_wp_cli_support');
            formData.append('container_name', containerName);
            formData.append('enabled', enabled);
            
            fetch('/api/wordpress-ajax.php', {
                method: 'POST',
                headers: {
                    'X-CSRF-Token': '<?php echo get_csrf_token(); ?>'
                },
                body: formData
            })
            .then(response => {
                console.log('WP-CLI Toggle Response Status:', response.status);
                return response.text().then(text => {
                    console.log('WP-CLI Toggle Raw Response:', text);
                    try {
                        return JSON.parse(text);
                    } catch (e) {
                        console.error('JSON Parse Error:', e);
                        console.error('Response Text:', text);
                        throw new Error('Invalid JSON response: ' + text.substring(0, 100));
                    }
                });
            })
            .then(data => {
                if (data.error) {
                    showAlert('danger', data.error);
                    // Revert toggle
                    this.checked = !enabled;
                } else {
                    const label = this.nextElementSibling;
                    label.textContent = enabled ? 'Enabled' : 'Disabled';
                    showAlert('success', `WordPress support ${enabled ? 'enabled' : 'disabled'} for ${containerName}`);
                }
            })
            .catch(error => {
                showAlert('danger', 'Error updating support: ' + error.message);
                this.checked = !enabled;
            });
        });
    });
    
    // Auto-update toggle handlers
    document.querySelectorAll('.auto-update-toggle').forEach(toggle => {
        toggle.addEventListener('change', function() {
            console.log('Auto-update toggle clicked');
            const siteRow = this.closest('tr');
            const siteId = siteRow.dataset.siteId;
            const updateType = this.dataset.type;
            const enabled = this.checked;
            
            const formData = new FormData();
            formData.append('action', 'update_auto_update_settings');
            formData.append('site_id', siteId);
            formData.append('update_type', updateType);
            formData.append('enabled', enabled ? '1' : '0');
            
            fetch('/api/wordpress-ajax.php', {
                method: 'POST',
                headers: {
                    'X-CSRF-Token': '<?php echo get_csrf_token(); ?>'
                },
                body: formData
            })
            .then(response => {
                console.log('Auto-update Toggle Response Status:', response.status);
                return response.text().then(text => {
                    console.log('Auto-update Toggle Raw Response:', text);
                    try {
                        return JSON.parse(text);
                    } catch (e) {
                        console.error('JSON Parse Error:', e);
                        console.error('Response Text:', text);
                        throw new Error('Invalid JSON response: ' + text.substring(0, 100));
                    }
                });
            })
            .then(data => {
                if (data.error) {
                    showAlert('danger', data.error);
                    // Revert toggle
                    this.checked = !enabled;
                } else {
                    showAlert('success', `Auto-update for ${updateType} ${enabled ? 'enabled' : 'disabled'}`);
                }
            })
            .catch(error => {
                showAlert('danger', 'Error updating auto-update setting: ' + error.message);
                this.checked = !enabled;
            });
        });
    });
    
    // Install WordPress form
    document.getElementById('installForm').addEventListener('submit', function(e) {
        e.preventDefault();
        console.log('WordPress install/import form submitted');
        
        const submitBtn = this.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;
        
        // Immediately show loading state
        submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Processing...';
        submitBtn.disabled = true;
        
        const formData = new FormData(this);
        
        // Determine if we're in install or import mode
        const isImportMode = document.getElementById('importFields').style.display !== 'none';
        const action = isImportMode ? 'import' : 'install';
        formData.append('action', action);
        
        console.log('Form mode:', action);
        
        // Update loading text based on action
        if (action === 'import') {
            submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Analyzing WordPress installation...';
            // Show processing message immediately
            showProcessing('Importing WordPress site... This may take a moment while we analyze the existing installation.');
        } else {
            submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Installing WordPress...';
            showProcessing('Installing WordPress... This may take a few minutes to download and configure WordPress.');
        }
        
        fetch('/api/wordpress-ajax.php', {
            method: 'POST',
            headers: {
                'X-CSRF-Token': nonce
            },
            body: formData
        })
        .then(response => {
            console.log('WordPress Install Response Status:', response.status);
            return response.text().then(text => {
                console.log('WordPress Install Raw Response:', text);
                try {
                    return JSON.parse(text);
                } catch (e) {
                    console.error('JSON Parse Error:', e);
                    console.error('Response Text:', text);
                    throw new Error('Invalid JSON response: ' + text.substring(0, 100));
                }
            });
        })
        .then(data => {
            if (data.error) {
                showAlert('danger', data.error);
            } else {
                const action = formData.get('action');
                const message = action === 'import' ? 'WordPress imported successfully!' : 'WordPress installed successfully!';
                showAlert('success', message);
                setTimeout(() => location.reload(), 2000);
            }
        })
        .catch(error => {
            showAlert('danger', 'Operation failed: ' + error.message);
        })
        .finally(() => {
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
        });
    });
    
    // Password reset form
    document.getElementById('passwordForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        // Show processing message
        showProcessing('Resetting WordPress admin password...');
        
        const formData = new FormData(this);
        formData.append('action', 'reset_password');
        
        fetch('/api/wordpress-ajax.php', {
            method: 'POST',
            headers: {
                'X-CSRF-Token': nonce
            },
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                showAlert('danger', data.error);
            } else {
                const modal = bootstrap.Modal.getInstance(document.getElementById('passwordModal'));
                modal.hide();
                
                // Show password in a copyable alert using the floating alert system
                const passwordMessage = `
                    <strong>Password reset successfully!</strong><br>
                    New password: <code id="newPassword">${data.password}</code>
                    <button type="button" class="btn btn-sm btn-secondary ms-2" onclick="copyPassword('${data.password}', this)">
                        <i class="fa fa-copy"></i> Copy
                    </button>
                `;
                showAlert('success', passwordMessage, false); // Don't auto-dismiss password alerts
            }
        })
        .catch(error => {
            showAlert('danger', 'Error: ' + error.message);
        });
    });
    
    // Search & Replace form
    document.getElementById('searchReplaceForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        if (!confirm('Are you sure you want to run search & replace? This will modify your database.')) {
            return;
        }
        
        // Show immediate processing message
        showProcessing('Running search & replace on database...');
        
        const siteId = document.getElementById('searchReplaceSiteId').value;
        const siteRow = document.querySelector(`tr[data-site-id="${siteId}"]`);
        const container = siteRow.dataset.container;
        const user = siteRow.dataset.user;
        
        const formData = new FormData(this);
        formData.append('action', 'search_replace');
        formData.append('container', container);
        formData.append('user', user);
        
        fetch('/api/wordpress-ajax.php', {
            method: 'POST',
            headers: {
                'X-CSRF-Token': nonce
            },
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                showAlert('danger', data.error);
            } else {
                showAlert('success', 'Search & replace completed successfully!');
                bootstrap.Modal.getInstance(document.getElementById('searchReplaceModal')).hide();
            }
        });
    });
    
    // Backup settings form
    document.getElementById('backupSettingsForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        // Show immediate processing message
        showProcessing('Updating backup settings...');
        
        const formData = new FormData(this);
        formData.append('action', 'update_backup_settings');
        
        fetch('/api/wordpress-ajax.php', {
            method: 'POST',
            headers: {
                'X-CSRF-Token': nonce
            },
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                showAlert('danger', data.error);
            } else {
                showAlert('success', 'Backup settings updated successfully!');
                bootstrap.Modal.getInstance(document.getElementById('backupSettingsModal')).hide();
                
                // Update data attributes on the row
                const siteId = formData.get('site_id');
                const siteRow = document.querySelector(`tr[data-site-id="${siteId}"]`);
                if (siteRow) {
                    siteRow.dataset.backupTargetId = formData.get('backup_target_id') || '';
                    siteRow.dataset.autoBackup = formData.get('auto_backup_before_update') ? 'true' : 'false';
                }
            }
        })
        .catch(error => {
            showAlert('danger', 'Error: ' + error.message);
        });
    });
    
    // Install plugin buttons
    document.querySelectorAll('.install-plugin').forEach(button => {
        button.addEventListener('click', function() {
            const pluginSlug = this.dataset.pluginSlug;
            const siteId = document.getElementById('pluginsSiteId').value;
            
            this.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Installing...';
            this.disabled = true;
            
            const formData = new FormData();
            formData.append('action', 'install_plugin');
            formData.append('site_id', siteId);
            formData.append('plugin_slug', pluginSlug);
            
            fetch('/api/wordpress-ajax.php', {
                method: 'POST',
                headers: {
                    'X-CSRF-Token': nonce
                },
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    showAlert('danger', data.error);
                    this.innerHTML = '<i class="fa fa-download"></i> Install';
                    this.disabled = false;
                } else {
                    this.innerHTML = '<i class="fa fa-check"></i> Installed';
                    this.classList.remove('btn-primary');
                    this.classList.add('btn-success');
                }
            });
        });
    });
    
    // Security form submission
    document.getElementById('securityForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        formData.append('action', 'update_security_settings');
        
        const submitBtn = this.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;
        submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Applying...';
        submitBtn.disabled = true;
        
        fetch('/api/wordpress-ajax.php', {
            method: 'POST',
            headers: {
                'X-CSRF-Token': nonce
            },
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                showAlert('danger', data.error);
            } else {
                showAlert('success', 'Security settings applied successfully!');
                bootstrap.Modal.getInstance(document.getElementById('securityModal')).hide();
            }
        })
        .catch(error => {
            showAlert('danger', 'Error applying security settings: ' + error.message);
        })
        .finally(() => {
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
        });
    });
    
    // Security action buttons
    document.getElementById('shuffleSalts').addEventListener('click', function() {
        const siteId = document.getElementById('securitySiteId').value;
        if (!siteId) return;
        
        if (confirm('Regenerate security keys? This will log out all users.')) {
            const formData = new FormData();
            formData.append('action', 'shuffle_salts');
            formData.append('site_id', siteId);
            
            this.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Processing...';
            this.disabled = true;
            
            fetch('/api/wordpress-ajax.php', {
                method: 'POST',
                headers: {
                    'X-CSRF-Token': nonce
                },
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    showAlert('danger', data.error);
                } else {
                    showAlert('success', 'Security keys regenerated successfully!');
                }
            })
            .finally(() => {
                this.innerHTML = '<i class="fa fa-key"></i> Regenerate Security Keys';
                this.disabled = false;
            });
        }
    });
    
    document.getElementById('updateHtaccess').addEventListener('click', function() {
        const siteId = document.getElementById('securitySiteId').value;
        if (!siteId) return;
        
        const formData = new FormData();
        formData.append('action', 'update_htaccess_rules');
        formData.append('site_id', siteId);
        
        this.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Updating...';
        this.disabled = true;
        
        fetch('/api/wordpress-ajax.php', {
            method: 'POST',
            headers: {
                'X-CSRF-Token': nonce
            },
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                showAlert('danger', data.error);
            } else {
                showAlert('success', '.htaccess rules updated successfully!');
            }
        })
        .finally(() => {
            this.innerHTML = '<i class="fa fa-file-code"></i> Update .htaccess Rules';
            this.disabled = false;
        });
    });
    
    document.getElementById('scanForVulnerabilities').addEventListener('click', function() {
        const siteId = document.getElementById('securitySiteId').value;
        if (!siteId) return;
        
        const formData = new FormData();
        formData.append('action', 'security_scan');
        formData.append('site_id', siteId);
        
        this.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Scanning...';
        this.disabled = true;
        
        fetch('/api/wordpress-ajax.php', {
            method: 'POST',
            headers: {
                'X-CSRF-Token': nonce
            },
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                showAlert('danger', data.error);
            } else {
                const issues = data.issues || [];
                if (issues.length === 0) {
                    showAlert('success', 'Security scan completed - no issues found!');
                } else {
                    const issueList = issues.map(issue => `• ${issue}`).join('<br>');
                    showAlert('warning', `Security scan completed. Issues found:<br>${issueList}`, false);
                }
            }
        })
        .finally(() => {
            this.innerHTML = '<i class="fa fa-search"></i> Security Scan';
            this.disabled = false;
        });
    });

    // ==============================
    // RECOMMENDED PLUGINS MANAGEMENT
    // ==============================
    
    // Load recommended plugins when modal opens
    document.getElementById('recommendedPluginsModal').addEventListener('shown.bs.modal', function() {
        loadRecommendedPlugins();
    });
    
    // Add plugin button
    document.getElementById('addPluginBtn').addEventListener('click', function() {
        showPluginForm();
    });
    
    // Plugin form submission
    document.getElementById('pluginForm').addEventListener('submit', function(e) {
        e.preventDefault();
        savePlugin();
    });
    
    function loadRecommendedPlugins() {
        console.log('Loading recommended plugins...');
        
        fetch('/api/wordpress-ajax.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-CSRF-Token': nonce
            },
            body: 'action=get_recommended_plugins'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                displayRecommendedPlugins(data.plugins);
            } else {
                showAlert('Error loading recommended plugins: ' + (data.message || 'Unknown error'), 'danger');
            }
        })
        .catch(error => {
            console.error('Error loading recommended plugins:', error);
            showAlert('Error loading recommended plugins', 'danger');
        });
    }
    
    function displayRecommendedPlugins(plugins) {
        const tbody = document.getElementById('pluginsTableBody');
        tbody.innerHTML = '';
        
        plugins.forEach(plugin => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${escapeHtml(plugin.name)}</td>
                <td><code>${escapeHtml(plugin.slug)}</code></td>
                <td><span class="badge bg-secondary">${escapeHtml(plugin.category || 'N/A')}</span></td>
                <td class="text-truncate" style="max-width: 200px;" title="${escapeHtml(plugin.description || '')}">${escapeHtml(plugin.description || 'No description')}</td>
                <td>${plugin.sort_order}</td>
                <td>
                    <span class="badge ${plugin.is_active ? 'bg-success' : 'bg-secondary'}">
                        ${plugin.is_active ? 'Active' : 'Inactive'}
                    </span>
                </td>
                <td>
                    <button class="btn btn-sm btn-outline-primary me-1" onclick="editPlugin(${plugin.id})">
                        <i class="fa fa-edit"></i>
                    </button>
                    <button class="btn btn-sm btn-outline-danger" onclick="deletePlugin(${plugin.id}, '${escapeHtml(plugin.name)}')">
                        <i class="fa fa-trash"></i>
                    </button>
                </td>
            `;
            tbody.appendChild(row);
        });
    }
    
    function showPluginForm(plugin = null) {
        const modal = new bootstrap.Modal(document.getElementById('pluginFormModal'));
        const form = document.getElementById('pluginForm');
        const title = document.getElementById('pluginFormTitle');
        
        if (plugin) {
            title.textContent = 'Edit Plugin';
            document.getElementById('pluginId').value = plugin.id;
            document.getElementById('pluginName').value = plugin.name;
            document.getElementById('pluginSlug').value = plugin.slug;
            document.getElementById('pluginCategory').value = plugin.category || '';
            document.getElementById('pluginDescription').value = plugin.description || '';
            document.getElementById('pluginInstallUrl').value = plugin.install_url || '';
            document.getElementById('pluginSortOrder').value = plugin.sort_order;
            document.getElementById('pluginActive').checked = plugin.is_active;
        } else {
            title.textContent = 'Add Plugin';
            form.reset();
            document.getElementById('pluginId').value = '';
            document.getElementById('pluginActive').checked = true;
        }
        
        modal.show();
    }
    
    function savePlugin() {
        const form = document.getElementById('pluginForm');
        const formData = new FormData(form);
        const pluginId = document.getElementById('pluginId').value;
        
        formData.append('action', pluginId ? 'update_recommended_plugin' : 'add_recommended_plugin');
        formData.append('is_active', document.getElementById('pluginActive').checked ? '1' : '0');
        
        const submitBtn = document.getElementById('pluginSubmitBtn');
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Saving...';
        
        fetch('/api/wordpress-ajax.php', {
            method: 'POST',
            headers: {
                'X-CSRF-Token': nonce
            },
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert(`Plugin ${pluginId ? 'updated' : 'added'} successfully`, 'success');
                bootstrap.Modal.getInstance(document.getElementById('pluginFormModal')).hide();
                loadRecommendedPlugins();
            } else {
                showAlert('Error saving plugin: ' + (data.message || 'Unknown error'), 'danger');
            }
        })
        .catch(error => {
            console.error('Error saving plugin:', error);
            showAlert('Error saving plugin', 'danger');
        })
        .finally(() => {
            submitBtn.disabled = false;
            submitBtn.innerHTML = 'Save Plugin';
        });
    }
    
    // Global functions for table actions
    window.editPlugin = function(pluginId) {
        fetch('/api/wordpress-ajax.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-CSRF-Token': nonce
            },
            body: `action=get_recommended_plugin&plugin_id=${pluginId}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showPluginForm(data.plugin);
            } else {
                showAlert('Error loading plugin: ' + (data.message || 'Unknown error'), 'danger');
            }
        })
        .catch(error => {
            console.error('Error loading plugin:', error);
            showAlert('Error loading plugin', 'danger');
        });
    };
    
    window.deletePlugin = function(pluginId, pluginName) {
        if (!confirm(`Are you sure you want to delete the plugin "${pluginName}"?`)) {
            return;
        }
        
        fetch('/api/wordpress-ajax.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-CSRF-Token': nonce
            },
            body: `action=delete_recommended_plugin&plugin_id=${pluginId}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('Plugin deleted successfully', 'success');
                loadRecommendedPlugins();
            } else {
                showAlert('Error deleting plugin: ' + (data.message || 'Unknown error'), 'danger');
            }
        })
        .catch(error => {
            console.error('Error deleting plugin:', error);
            showAlert('Error deleting plugin', 'danger');
        });
    };

}); // End of DOMContentLoaded

// Helper functions - Define outside DOMContentLoaded so they're globally accessible

// Copy to clipboard with fallback
function copyPassword(text, button) {
    if (navigator.clipboard && window.isSecureContext) {
        // Modern way
        navigator.clipboard.writeText(text).then(function() {
            button.innerHTML = 'Copied!';
            setTimeout(() => {
                button.innerHTML = '<i class="fa fa-copy"></i> Copy';
            }, 2000);
        }).catch(function(err) {
            // Fallback to old method
            fallbackCopyTextToClipboard(text, button);
        });
    } else {
        // Fallback for non-secure contexts or older browsers
        fallbackCopyTextToClipboard(text, button);
    }
}

function fallbackCopyTextToClipboard(text, button) {
    const textArea = document.createElement("textarea");
    textArea.value = text;
    textArea.style.position = "fixed";
    textArea.style.left = "-999999px";
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    
    try {
        document.execCommand('copy');
        button.innerHTML = 'Copied!';
        setTimeout(() => {
            button.innerHTML = '<i class="fa fa-copy"></i> Copy';
        }, 2000);
    } catch (err) {
        console.error('Unable to copy', err);
        // Select the text for manual copying
        const passwordElement = document.getElementById('newPassword');
        if (passwordElement) {
            const range = document.createRange();
            range.selectNode(passwordElement);
            window.getSelection().removeAllRanges();
            window.getSelection().addRange(range);
            button.innerHTML = 'Selected!';
        }
    }
    
    document.body.removeChild(textArea);
}
function createLoginLink(siteId) {
    // Show immediate processing message
    showProcessing('Creating auto-login link...');
    
    const formData = new FormData();
    formData.append('action', 'create_login');
    formData.append('site_id', siteId);
    
    fetch('/api/wordpress-ajax.php', {
        method: 'POST',
        headers: {
            'X-CSRF-Token': nonce
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Open login URL in new tab
            window.open(data.login_url, '_blank');
            showAlert('success', 'Login link created and opened in new tab. Expires at: ' + data.expires_at);
        } else {
            showAlert('danger', 'Error creating login link: ' + (data.message || 'Unknown error'));
        }
    })
    .catch(error => {
        console.error('Error creating login link:', error);
        showAlert('danger', 'Error creating login link');
    });
}

function showUpdateModal(siteId) {
    showWordPressUpdateModal(siteId, 'all');
}

function showCoreUpdateModal(siteId) {
    showWordPressUpdateModal(siteId, 'core');
}

function showWordPressUpdateModal(siteId, updateType = 'all') {
    const modalHtml = `
        <div class="modal fade" id="wpUpdateModal" tabindex="-1" aria-labelledby="wpUpdateModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="wpUpdateModalLabel">
                            <i class="fa fa-sync"></i> WordPress Update
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <h6>${updateType === 'core' ? 'Core Update' : 'Complete Update (Core, Plugins, Themes)'}</h6>
                            <p class="text-muted small">
                                ${updateType === 'core' ?
                                    'This will update WordPress core to the latest version.' :
                                    'This will update WordPress core, all plugins, and themes to their latest versions.'
                                }
                            </p>
                        </div>

                        <div class="alert alert-info">
                            <i class="fa fa-info-circle"></i>
                            <strong>Backup Recommendation:</strong> We strongly recommend creating a backup before updating.
                        </div>

                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" id="createBackupCheck" checked>
                            <label class="form-check-label" for="createBackupCheck">
                                <strong>Create backup before updating</strong>
                                <br>
                                <small class="text-muted">Backup will be created first, then update will start automatically when backup completes.</small>
                            </label>
                        </div>

                        <div class="alert alert-warning" id="noBackupWarning" style="display: none;">
                            <i class="fa fa-exclamation-triangle"></i>
                            <strong>Warning:</strong> Updating without a backup is risky. If something goes wrong, you may lose your site data.
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="button" class="btn btn-primary" onclick="executeWordPressUpdate(${siteId}, '${updateType}')">
                            <i class="fa fa-sync"></i> Start Update
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `;

    // Remove existing modal if present
    const existingModal = document.getElementById('wpUpdateModal');
    if (existingModal) {
        existingModal.remove();
    }

    // Add modal to DOM
    document.body.insertAdjacentHTML('beforeend', modalHtml);

    // Show warning when backup is unchecked
    const backupCheck = document.getElementById('createBackupCheck');
    const warningDiv = document.getElementById('noBackupWarning');

    backupCheck.addEventListener('change', function() {
        if (this.checked) {
            warningDiv.style.display = 'none';
        } else {
            warningDiv.style.display = 'block';
        }
    });

    // Show the modal
    const modal = new bootstrap.Modal(document.getElementById('wpUpdateModal'));
    modal.show();
}

function executeWordPressUpdate(siteId, updateType) {
    const createBackup = document.getElementById('createBackupCheck').checked;
    const modal = bootstrap.Modal.getInstance(document.getElementById('wpUpdateModal'));
    modal.hide();

    const formData = new FormData();
    formData.append('action', updateType === 'core' ? 'update_core' : 'update_all');
    formData.append('site_id', siteId);
    formData.append('create_backup', createBackup ? '1' : '0');

    // Show appropriate progress message
    const progressMessage = createBackup ?
        'WordPress update queued. Backup will be created first, then update will start automatically.' :
        'WordPress update started. This may take several minutes...';

    showAlert('info', progressMessage, false);

    fetch('/api/wordpress-ajax.php', {
        method: 'POST',
        headers: {
            'X-CSRF-Token': nonce
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            showAlert('danger', data.error);
        } else if (data.queue_mode) {
            // Queued mode - backup + update
            showAlert('success', `${data.message} (Backup ID: ${data.backup_id}, Update ID: ${data.update_id})`);
            // Could add polling for queued updates here if needed
        } else if (data.update_id) {
            // Immediate mode with polling
            pollUpdateStatus(data.update_id, siteId);
        } else {
            showAlert('success', data.message || 'WordPress update completed successfully!');
        }
    })
    .catch(error => {
        showAlert('danger', 'Error starting update: ' + error.message);
    });
}

function pollUpdateStatus(updateId, siteId) {
    const checkStatus = () => {
        const formData = new FormData();
        formData.append('action', 'check_update_status');
        formData.append('update_id', updateId);
        
        fetch('/api/wordpress-ajax.php', {
            method: 'POST',
            headers: {
                'X-CSRF-Token': nonce
            },
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                showAlert('danger', 'Error checking update status: ' + data.error);
                return;
            }
            
            if (data.status === 'completed') {
                showAlert('success', `WordPress updated successfully to version ${data.new_version}!`);
                // Reload the version for this specific site
                const versionElement = document.querySelector(`.wp-version[data-site-id="${siteId}"]`);
                if (versionElement) {
                    // Show loading state
                    versionElement.innerHTML = '<i class="fa fa-spinner fa-spin text-muted"></i> <span class="text-muted">Refreshing...</span>';
                    
                    // Fetch the updated version
                    const formData = new FormData();
                    formData.append('action', 'get_wordpress_versions');
                    formData.append('site_ids[]', siteId);
                    
                    fetch('/api/wordpress-ajax.php', {
                        method: 'POST',
                        headers: {
                            'X-CSRF-Token': nonce
                        },
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success && data.versions && data.versions[siteId]) {
                            versionElement.innerHTML = escapeHtml(data.versions[siteId]);
                            versionElement.classList.remove('text-muted');
                        } else {
                            versionElement.innerHTML = '<span class="text-muted">Unknown</span>';
                        }
                    })
                    .catch(error => {
                        console.error('Error refreshing version:', error);
                        versionElement.innerHTML = '<span class="text-muted">Unknown</span>';
                    });
                }
            } else if (data.status === 'failed') {
                showAlert('danger', `WordPress update failed: ${data.error_message || 'Unknown error'}`);
            } else if (data.status === 'in_progress') {
                // Continue polling
                setTimeout(checkStatus, 3000); // Check every 3 seconds
            }
        })
        .catch(error => {
            showAlert('danger', 'Error checking update status: ' + error.message);
        });
    };
    
    // Start checking after 2 seconds
    setTimeout(checkStatus, 2000);
}

function showPasswordModal(siteId) {
    document.getElementById('passwordSiteId').value = siteId;
    new bootstrap.Modal(document.getElementById('passwordModal')).show();
}

function showCloneModal(siteId) {
    document.getElementById('cloneSourceSiteId').value = siteId;

    // Get source site info from the table row
    const row = document.querySelector(`tr[data-site-id="${siteId}"]`);
    if (row) {
        const siteName = row.querySelector('td a').textContent.trim();
        document.getElementById('cloneSourceSiteName').value = siteName;
    }

    // Load available target sites
    loadAvailableTargetSites(siteId);

    new bootstrap.Modal(document.getElementById('cloneModal')).show();
}

function showSearchReplaceModal(siteId) {
    document.getElementById('searchReplaceSiteId').value = siteId;
    new bootstrap.Modal(document.getElementById('searchReplaceModal')).show();
}

function showPluginsModal(siteId) {
    document.getElementById('pluginsSiteId').value = siteId;
    new bootstrap.Modal(document.getElementById('pluginsModal')).show();
}

function showSecurityModal(siteId) {
    document.getElementById('securitySiteId').value = siteId;
    
    // Load current security settings for this site
    const formData = new FormData();
    formData.append('action', 'get_security_settings');
    formData.append('site_id', siteId);
    
    fetch('/api/wordpress-ajax.php', {
        method: 'POST',
        headers: {
            'X-CSRF-Token': nonce
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            showAlert('danger', data.error);
        } else {
            // Populate form with current settings
            const settings = data.settings || {};
            document.getElementById('disableFileEditor').checked = settings.disable_file_editor || false;
            document.getElementById('disableXmlrpc').checked = settings.disable_xmlrpc || false;
            document.getElementById('hideWpVersion').checked = settings.hide_wp_version || false;
            document.getElementById('disableDirectoryBrowsing').checked = settings.disable_directory_browsing || false;
            document.getElementById('limitLoginAttempts').checked = settings.limit_login_attempts || false;
            document.getElementById('securityHeaders').checked = settings.security_headers_enabled || false;
            document.getElementById('blockPhpUploads').checked = settings.block_php_uploads || settings.block_php_in_uploads || false;
            document.getElementById('forceStrongPasswords').checked = settings.force_strong_passwords || false;
            
            // Show the modal
            new bootstrap.Modal(document.getElementById('securityModal')).show();
        }
    })
    .catch(error => {
        console.error('Error loading security settings:', error);
        // Show modal anyway with default settings
        new bootstrap.Modal(document.getElementById('securityModal')).show();
    });
}

function showInstallModal() {
    // Reset the modal to install mode
    document.getElementById('installModalTitle').textContent = 'Install WordPress';
    document.getElementById('installFields').style.display = 'block';
    document.getElementById('importFields').style.display = 'none';
    document.getElementById('installSubmitBtn').innerHTML = '<i class="fa fa-download"></i> Install WordPress';
    
    // Reset form
    document.getElementById('installForm').reset();
    
    // Add required attributes to install fields
    document.querySelectorAll('#installFields input[name="title"], #installFields input[name="admin_password"], #installFields input[name="admin_email"]').forEach(field => {
        field.setAttribute('required', '');
    });
    
    // Show the modal
    new bootstrap.Modal(document.getElementById('installModal')).show();
}

function showImportModal() {
    // Reset the modal to import mode
    document.getElementById('installModalTitle').textContent = 'Import WordPress';
    document.getElementById('installFields').style.display = 'none';
    document.getElementById('importFields').style.display = 'block';
    document.getElementById('installSubmitBtn').innerHTML = '<i class="fa fa-upload"></i> Import WordPress';
    document.getElementById('installSubmitBtn').disabled = true; // Disable until WordPress is detected
    
    // Reset form
    document.getElementById('installForm').reset();
    
    // Remove required attributes from install fields since they're hidden
    document.querySelectorAll('#installFields input').forEach(field => {
        field.removeAttribute('required');
    });
    
    // Hide import message and backup fields initially
    document.getElementById('importMessage').style.display = 'none';
    document.querySelector('#importFields .mb-3').style.display = 'none'; // Hide backup target
    
    // Clear import info
    document.getElementById('importInfo').innerHTML = '<p class="text-muted">Select a site to scan for WordPress installation...</p>';
    
    // Show the modal
    new bootstrap.Modal(document.getElementById('installModal')).show();
}

function showForceHttpsModal(siteId) {
    document.getElementById('forceHttpsSiteId').value = siteId;

    // Show loading state
    document.getElementById('httpsStatusLoading').style.display = 'block';
    document.getElementById('httpsStatusContent').style.display = 'none';
    document.getElementById('applyForceHttpsBtn').style.display = 'none';

    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('forceHttpsModal'));
    modal.show();

    // Check current HTTPS status
    const formData = new FormData();
    formData.append('action', 'check_force_https_status');
    formData.append('site_id', siteId);

    fetch('/api/wordpress-ajax.php', {
        method: 'POST',
        headers: {
            'X-CSRF-Token': nonce
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const isEnabled = data.https_enabled;

            // Update status display
            const statusHtml = isEnabled ?
                '<span class="badge bg-success"><i class="fa fa-check-circle"></i> Enabled</span> <span class="text-muted ms-2">HTTPS redirects are active</span>' :
                '<span class="badge bg-secondary"><i class="fa fa-times-circle"></i> Disabled</span> <span class="text-muted ms-2">HTTPS redirects are not active</span>';
            document.getElementById('httpsCurrentStatus').innerHTML = statusHtml;

            // Set toggle state
            const toggle = document.getElementById('forceHttpsToggle');
            toggle.checked = isEnabled;
            toggle.dataset.originalState = isEnabled;

            // Update toggle label
            updateHttpsToggleLabel(isEnabled);

            // Show warning if enabling
            document.getElementById('httpsWarning').style.display = isEnabled ? 'none' : 'block';

            // Hide loading, show content
            document.getElementById('httpsStatusLoading').style.display = 'none';
            document.getElementById('httpsStatusContent').style.display = 'block';
        } else {
            showAlert('danger', 'Error checking HTTPS status: ' + (data.error || 'Unknown error'));
            modal.hide();
        }
    })
    .catch(error => {
        console.error('Error checking HTTPS status:', error);
        showAlert('danger', 'Error checking HTTPS status');
        modal.hide();
    });
}

function updateHttpsToggleLabel(enabled) {
    const label = document.getElementById('forceHttpsToggleLabel');
    label.textContent = enabled ? 'Disable Force HTTPS' : 'Enable Force HTTPS';

    // Show/hide apply button based on change
    const toggle = document.getElementById('forceHttpsToggle');
    const originalState = toggle.dataset.originalState === 'true';
    const changed = originalState !== toggle.checked;
    document.getElementById('applyForceHttpsBtn').style.display = changed ? 'block' : 'none';

    // Toggle warning visibility
    document.getElementById('httpsWarning').style.display = toggle.checked && !originalState ? 'block' : 'none';
}

// Add toggle change listener
document.addEventListener('DOMContentLoaded', function() {
    const toggle = document.getElementById('forceHttpsToggle');
    if (toggle) {
        toggle.addEventListener('change', function() {
            updateHttpsToggleLabel(this.checked);
        });
    }
});

function applyForceHttps() {
    const siteId = document.getElementById('forceHttpsSiteId').value;
    const toggle = document.getElementById('forceHttpsToggle');
    const enable = toggle.checked;
    const applyBtn = document.getElementById('applyForceHttpsBtn');

    // Disable button and show loading
    applyBtn.disabled = true;
    applyBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Applying...';

    const formData = new FormData();
    formData.append('action', enable ? 'force_https' : 'disable_force_https');
    formData.append('site_id', siteId);

    fetch('/api/wordpress-ajax.php', {
        method: 'POST',
        headers: {
            'X-CSRF-Token': nonce
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('success', data.message);

            // Update original state
            toggle.dataset.originalState = enable;

            // Update status display
            const statusHtml = enable ?
                '<span class="badge bg-success"><i class="fa fa-check-circle"></i> Enabled</span> <span class="text-muted ms-2">HTTPS redirects are active</span>' :
                '<span class="badge bg-secondary"><i class="fa fa-times-circle"></i> Disabled</span> <span class="text-muted ms-2">HTTPS redirects are not active</span>';
            document.getElementById('httpsCurrentStatus').innerHTML = statusHtml;

            // Hide apply button
            applyBtn.style.display = 'none';
            applyBtn.disabled = false;
            applyBtn.innerHTML = '<i class="fa fa-save"></i> Apply Changes';

            // Update label
            updateHttpsToggleLabel(enable);
        } else {
            showAlert('danger', 'Error: ' + (data.error || 'Unknown error'));
            applyBtn.disabled = false;
            applyBtn.innerHTML = '<i class="fa fa-save"></i> Apply Changes';
        }
    })
    .catch(error => {
        console.error('Error applying Force HTTPS:', error);
        showAlert('danger', 'Error applying Force HTTPS setting');
        applyBtn.disabled = false;
        applyBtn.innerHTML = '<i class="fa fa-save"></i> Apply Changes';
    });
}

function removeFromManagement(siteId) {
    if (!confirm('Are you sure you want to remove this site from WordPress management?\n\nThis will:\n• Remove the site from the WordPress management system\n• Stop auto-updates and other automated functions\n• NOT delete any files or databases\n\nThe WordPress site will continue to work normally.')) {
        return;
    }

    // Show immediate processing message
    showProcessing('Removing site from WordPress management...');

    const formData = new FormData();
    formData.append('action', 'remove_from_management');
    formData.append('site_id', siteId);

    fetch('/api/wordpress-ajax.php', {
        method: 'POST',
        headers: {
            'X-CSRF-Token': nonce
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('success', 'WordPress site removed from management successfully');
            // Reload the page to update the sites list
            setTimeout(() => {
                window.location.reload();
            }, 1500);
        } else {
            showAlert('danger', 'Error removing site from management: ' + (data.error || 'Unknown error'));
        }
    })
    .catch(error => {
        console.error('Error removing from management:', error);
        showAlert('danger', 'Error removing site from management');
    });
}

function showBackupSettingsModal(siteId) {
    document.getElementById('backupSettingsSiteId').value = siteId;
    
    // Get current settings for this site
    const siteRow = document.querySelector(`tr[data-site-id="${siteId}"]`);
    const currentTargetId = siteRow.dataset.backupTargetId || '';
    const autoBackup = siteRow.dataset.autoBackup === 'true';
    
    // Set current values
    document.querySelector('#backupSettingsForm select[name="backup_target_id"]').value = currentTargetId;
    document.querySelector('#backupSettingsForm input[name="auto_backup_before_update"]').checked = autoBackup;
    
    new bootstrap.Modal(document.getElementById('backupSettingsModal')).show();
}

// Trigger an ad-hoc backup for one site. The backup itself runs in the
// background worker; we just queue it here and tell the user. Completion or
// failure is delivered via the per-site notification email if enabled.
function backupNow(siteId, domain) {
    if (!confirm(`Queue a backup for ${domain} now? The backup worker will pick it up and run it in the background.`)) {
        return;
    }

    showProcessing(`Queueing backup for ${domain}...`);

    const formData = new FormData();
    formData.append('action', 'create_backup_now');
    formData.append('site_id', siteId);

    fetch('/api/wordpress-ajax.php', {
        method: 'POST',
        headers: { 'X-CSRF-Token': nonce },
        body: formData
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            showAlert('success',
                `Backup queued for ${domain} (#${data.backup_id || '?'}). ` +
                `Watch progress on the Backups page.`);
        } else {
            // The wordpress-ajax.php error handler returns {error: "..."}, while
            // success responses use {message: "..."}. Read both so the real,
            // actionable message surfaces instead of a useless "unknown error".
            showAlert('danger', `Failed to queue backup: ${data.error || data.message || 'unknown error'}`);
        }
    })
    .catch(err => {
        showAlert('danger', `Failed to queue backup: ${err.message}`);
    });
}

// Open the per-site Notifications modal — pulls current settings from the
// server (so we always show the latest persisted state, not stale row data).
function showNotificationSettingsModal(siteId) {
    document.getElementById('notificationSettingsSiteId').value = siteId;
    // Reset visible inputs while loading.
    document.getElementById('notificationEmailInput').value = '';
    document.getElementById('notifyBackupComplete').checked = false;
    document.getElementById('notifyBackupFailed').checked = false;
    document.getElementById('notifyUpdateComplete').checked = false;
    document.getElementById('notifyUpdateFailed').checked = false;

    const formData = new FormData();
    formData.append('action', 'get_notification_settings');
    formData.append('site_id', siteId);
    fetch('/api/wordpress-ajax.php', {
        method: 'POST',
        headers: { 'X-CSRF-Token': nonce },
        body: formData
    })
    .then(r => r.json())
    .then(data => {
        if (data.success && data.settings) {
            const s = data.settings;
            document.getElementById('notificationEmailInput').value = s.notification_email || '';
            document.getElementById('notifyBackupComplete').checked = !!s.notify_backup_complete;
            document.getElementById('notifyBackupFailed').checked = !!s.notify_backup_failed;
            document.getElementById('notifyUpdateComplete').checked = !!s.notify_update_complete;
            document.getElementById('notifyUpdateFailed').checked = !!s.notify_update_failed;
        }
    })
    .catch(err => console.error('get_notification_settings failed:', err));

    new bootstrap.Modal(document.getElementById('notificationSettingsModal')).show();
}

document.addEventListener('DOMContentLoaded', function () {
    const form = document.getElementById('notificationSettingsForm');
    if (!form) return;
    form.addEventListener('submit', function (e) {
        e.preventDefault();
        const fd = new FormData();
        fd.append('action', 'update_notification_settings');
        fd.append('site_id', document.getElementById('notificationSettingsSiteId').value);
        fd.append('notification_email', document.getElementById('notificationEmailInput').value);
        // Send "1" only when checked so the server's isset check works as intended.
        if (document.getElementById('notifyBackupComplete').checked) fd.append('notify_backup_complete', '1');
        if (document.getElementById('notifyBackupFailed').checked)   fd.append('notify_backup_failed',   '1');
        if (document.getElementById('notifyUpdateComplete').checked) fd.append('notify_update_complete', '1');
        if (document.getElementById('notifyUpdateFailed').checked)   fd.append('notify_update_failed',   '1');

        showProcessing('Saving notification settings...');
        fetch('/api/wordpress-ajax.php', {
            method: 'POST',
            headers: { 'X-CSRF-Token': nonce },
            body: fd
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                bootstrap.Modal.getInstance(document.getElementById('notificationSettingsModal')).hide();
                showAlert('success', 'Notification settings saved.');
            } else {
                showAlert('danger', 'Error: ' + (data.message || 'unknown error'));
            }
        })
        .catch(err => showAlert('danger', 'Error: ' + err.message));
    });
});

function showAlert(type, message, autoDismiss = true) {
    // Create or get alert container
    let alertContainer = document.getElementById('alert-container');
    if (!alertContainer) {
        alertContainer = document.createElement('div');
        alertContainer.id = 'alert-container';
        alertContainer.className = 'alert-container';
        document.body.appendChild(alertContainer);
    }

    // When showing a result alert (auto-dismissing success/danger), sweep any
    // pending non-dismissing "processing" alerts off the screen — they were
    // marking work-in-progress, the work just finished. Without this, every
    // handler that does showProcessing(...) + showAlert(success/danger, ...)
    // leaks the spinner forever (e.g., createLoginLink left "Processing...
    // Creating auto-login link..." on the page indefinitely after the success
    // notification faded).
    if (autoDismiss) {
        alertContainer.querySelectorAll('.alert-processing').forEach(el => el.remove());
    }

    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show floating-alert${autoDismiss ? '' : ' alert-processing'}`;
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    // Add to container
    alertContainer.appendChild(alertDiv);
    
    // Helper function to remove with animation
    const removeAlert = () => {
        alertDiv.classList.add('fade-out');
        setTimeout(() => {
            if (alertDiv.parentNode) {
                alertDiv.remove();
            }
        }, 300); // Wait for animation to complete
    };
    
    // Auto-dismiss after 5 seconds (unless disabled)
    if (autoDismiss) {
        setTimeout(removeAlert, 5000);
    }
    
    // Remove on close button click
    alertDiv.querySelector('.btn-close').addEventListener('click', removeAlert);
}

// Helper function to show processing/working messages
function showProcessing(message) {
    clearAlerts(); // Clear any existing alerts
    const processingHtml = `<i class="fa fa-spinner fa-spin me-2"></i><strong>Processing...</strong><br>${message}`;
    return showAlert('info', processingHtml, false); // Don't auto-dismiss processing messages
}

// Helper function to hide processing messages
function hideProcessing() {
    clearAlerts();
}

// Helper function to clear all alerts
function clearAlerts() {
    const alertContainer = document.getElementById('alert-container');
    if (alertContainer) {
        alertContainer.innerHTML = '';
    }
}

// Load available target sites for cloning
function loadAvailableTargetSites(sourceSiteId) {
    const targetSelect = document.getElementById('cloneTargetSiteId');
    targetSelect.innerHTML = '<option value="">Loading...</option>';

    // Make request to get available sites with CSRF token
    fetch('/pages/api/get-clone-target-sites.php?source_site_id=' + encodeURIComponent(sourceSiteId) + '&nonce=' + encodeURIComponent(nonce))
        .then(response => response.json())
        .then(data => {
            targetSelect.innerHTML = '<option value="">Select a target site...</option>';

            if (data.success && data.sites) {
                data.sites.forEach(site => {
                    const option = document.createElement('option');
                    option.value = site.id;
                    option.textContent = `${site.primary_fqdn} (${site.username})`;
                    targetSelect.appendChild(option);
                });

                if (data.sites.length === 0) {
                    targetSelect.innerHTML = '<option value="">No available target sites found</option>';
                }
            } else {
                targetSelect.innerHTML = '<option value="">Error loading sites</option>';
            }
        })
        .catch(error => {
            targetSelect.innerHTML = '<option value="">Error loading sites</option>';
            console.error('Error loading target sites:', error);
        });
}

// Clone form handler
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('cloneForm').addEventListener('submit', function(e) {
        e.preventDefault();

        const sourceSiteId = document.getElementById('cloneSourceSiteId').value;
        const targetSiteId = document.getElementById('cloneTargetSiteId').value;

        if (!targetSiteId) {
            showAlert('danger', 'Please select a target site.');
            return;
        }

        if (!confirm('Are you sure you want to clone this WordPress site? This will:\n\n• Create a new database\n• Copy all files to the target site\n• Update URLs and paths\n• Regenerate security keys\n\nThis process cannot be undone.')) {
            return;
        }

        // Disable the clone button and show processing
        const cloneButton = this.querySelector('button[type="submit"]');
        const originalButtonText = cloneButton.innerHTML;
        cloneButton.disabled = true;
        cloneButton.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Cloning...';

        // Show processing message
        showProcessing('Cloning WordPress site...');

        const formData = new FormData();
        formData.append('action', 'clone_site');
        formData.append('source_site_id', sourceSiteId);
        formData.append('target_site_id', targetSiteId);

        fetch('/api/wordpress-ajax.php', {
            method: 'POST',
            headers: {
                'X-CSRF-Token': nonce
            },
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            hideProcessing();

            if (data.success) {
                // Close modal
                const modal = bootstrap.Modal.getInstance(document.getElementById('cloneModal'));
                modal.hide();

                // Show success message
                showAlert('success', `WordPress site successfully cloned to ${data.target_domain}! The new site will appear in your WordPress sites list.`, false);

                // Refresh page after 3 seconds to show new site
                setTimeout(() => {
                    window.location.reload();
                }, 3000);
            } else {
                // Re-enable button on error
                cloneButton.disabled = false;
                cloneButton.innerHTML = originalButtonText;
                showAlert('danger', 'Clone failed: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            hideProcessing();
            // Re-enable button on error
            cloneButton.disabled = false;
            cloneButton.innerHTML = originalButtonText;
            showAlert('danger', 'Error: ' + error.message);
        });
    });
});

// ==============================
// RESTORE FROM BACKUP FUNCTIONS
// ==============================

function showRestoreModal(siteId) {
    const modal = new bootstrap.Modal(document.getElementById('restoreModal'));
    document.getElementById('restoreSiteId').value = siteId;
    document.getElementById('selectedBackupId').value = '';
    document.getElementById('confirmRestoreBtn').disabled = true;

    // Reset visibility
    document.getElementById('restoreLoadingMessage').style.display = 'block';
    document.getElementById('restoreNoBackups').style.display = 'none';
    document.getElementById('restoreBackupsList').style.display = 'none';
    document.getElementById('backupDetails').style.display = 'none';

    modal.show();

    // Load backups for this site
    loadSiteBackups(siteId);
}

function loadSiteBackups(siteId) {
    const formData = new FormData();
    formData.append('action', 'get_site_backups');
    formData.append('site_id', siteId);

    fetch('/api/wordpress-ajax.php', {
        method: 'POST',
        headers: {
            'X-CSRF-Token': nonce
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        document.getElementById('restoreLoadingMessage').style.display = 'none';

        if (data.success && data.backups && data.backups.length > 0) {
            displayBackupsList(data.backups);
            document.getElementById('restoreBackupsList').style.display = 'block';
        } else {
            document.getElementById('restoreNoBackups').style.display = 'block';
        }
    })
    .catch(error => {
        document.getElementById('restoreLoadingMessage').style.display = 'none';
        document.getElementById('restoreNoBackups').style.display = 'block';
        showAlert('danger', 'Error loading backups: ' + error.message);
    });
}

function displayBackupsList(backups) {
    const backupsList = document.getElementById('backupsList');
    backupsList.innerHTML = '';

    backups.forEach(backup => {
        const backupItem = document.createElement('a');
        backupItem.href = '#';
        backupItem.className = 'list-group-item list-group-item-action';
        backupItem.onclick = function(e) {
            e.preventDefault();
            selectBackup(backup);
        };

        const statusBadge = getStatusBadge(backup.status, backup.upload_status);
        const sizeMB = (backup.backup_size / (1024 * 1024)).toFixed(2);
        const createdDate = new Date(backup.started_at).toLocaleString();

        backupItem.innerHTML = `
            <div class="d-flex w-100 justify-content-between align-items-start">
                <div>
                    <h6 class="mb-1">${escapeHtml(backup.backup_name)}</h6>
                    <p class="mb-1 small text-muted">
                        <i class="fa fa-calendar"></i> ${createdDate}<br>
                        <i class="fa fa-hdd"></i> ${sizeMB} MB
                    </p>
                </div>
                <div class="text-end">
                    ${statusBadge}
                    ${backup.upload_status === 'uploaded' || backup.upload_status === 'pending' ?
                        '<span class="badge bg-success ms-1"><i class="fa fa-check"></i> Available</span>' :
                        '<span class="badge bg-warning ms-1"><i class="fa fa-clock"></i> Local Only</span>'}
                </div>
            </div>
        `;

        backupsList.appendChild(backupItem);
    });
}

function getStatusBadge(status, uploadStatus) {
    if (status === 'completed') {
        return '<span class="badge bg-success">Completed</span>';
    } else if (status === 'running') {
        return '<span class="badge bg-warning">Running</span>';
    } else if (status === 'failed') {
        return '<span class="badge bg-danger">Failed</span>';
    } else {
        return '<span class="badge bg-secondary">' + status + '</span>';
    }
}

function selectBackup(backup) {
    // Highlight selected backup
    document.querySelectorAll('#backupsList .list-group-item').forEach(item => {
        item.classList.remove('active');
    });
    event.target.closest('.list-group-item').classList.add('active');

    // Store selected backup ID
    document.getElementById('selectedBackupId').value = backup.id;

    // Show backup details
    const detailsContent = document.getElementById('backupDetailsContent');
    const sizeMB = (backup.backup_size / (1024 * 1024)).toFixed(2);
    const createdDate = new Date(backup.started_at).toLocaleString();

    detailsContent.innerHTML = `
        <ul class="mb-0">
            <li><strong>Backup Name:</strong> ${escapeHtml(backup.backup_name)}</li>
            <li><strong>Created:</strong> ${createdDate}</li>
            <li><strong>Size:</strong> ${sizeMB} MB</li>
            <li><strong>Type:</strong> ${escapeHtml(backup.backup_type)}</li>
            <li><strong>Status:</strong> ${backup.status} / ${backup.upload_status || 'N/A'}</li>
        </ul>
    `;

    document.getElementById('backupDetails').style.display = 'block';
    document.getElementById('confirmRestoreBtn').disabled = false;
}

function confirmRestore() {
    const siteId = document.getElementById('restoreSiteId').value;
    const backupId = document.getElementById('selectedBackupId').value;

    if (!backupId) {
        showAlert('warning', 'Please select a backup to restore');
        return;
    }

    if (!confirm('Are you sure you want to restore this backup? This will replace all current files and database content. This action cannot be undone.')) {
        return;
    }

    // Close modal and show processing
    bootstrap.Modal.getInstance(document.getElementById('restoreModal')).hide();
    showProcessing('Restoring WordPress from backup... This may take several minutes. Do not close this window.');

    const formData = new FormData();
    formData.append('action', 'restore_backup');
    formData.append('site_id', siteId);
    formData.append('backup_id', backupId);

    fetch('/api/wordpress-ajax.php', {
        method: 'POST',
        headers: {
            'X-CSRF-Token': nonce
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        hideProcessing();

        if (data.success) {
            showAlert('success', 'WordPress restored successfully from backup!');
            setTimeout(() => {
                window.location.reload();
            }, 2000);
        } else {
            showAlert('danger', 'Restore failed: ' + (data.message || data.error || 'Unknown error'));
        }
    })
    .catch(error => {
        hideProcessing();
        showAlert('danger', 'Error restoring backup: ' + error.message);
    });
}

// Initialize table pagination if sites exist
document.addEventListener('DOMContentLoaded', function() {
    const wpTable = document.getElementById('wpSitesTable');
    if (wpTable) {
        // Initialize pagination
        <?php if ($isRoot): ?>
        const wpPagination = new TablePagination({
            tableId: 'wpSitesTable',
            searchId: 'wpSearchInput',
            paginationId: 'wpPagination',
            infoId: 'wpTableInfo',
            filterSelectId: 'wpUserFilter',
            filterAttribute: 'user',
            itemsPerPage: 25
        });
        <?php else: ?>
        const wpPagination = new TablePagination({
            tableId: 'wpSitesTable',
            searchId: 'wpSearchInput',
            paginationId: 'wpPagination',
            infoId: 'wpTableInfo',
            itemsPerPage: 25
        });
        <?php endif; ?>

        // Load WordPress versions only for visible rows after pagination renders
        document.addEventListener('tablePaginationRendered', function(e) {
            // Load versions for visible rows only
            loadWordPressVersions();
        });

        // Initial load
        loadWordPressVersions();
    }
});
</script>

<script src="/js/table-pagination.js"></script>

<style>
/* Fix for dropdown truncation in responsive tables */
.table-responsive {
    overflow: visible !important;
}

/* Ensure dropdown menus appear above table content */
.dropdown-menu {
    position: absolute;
    z-index: 1050;
}

/* Optional: Add max height and scroll to very long dropdown menus */
.dropdown-menu {
    max-height: 400px;
    overflow-y: auto;
}

/* Floating alert container */
.alert-container {
    position: fixed;
    top: 20px;
    right: 20px;
    z-index: 1060;
    max-width: 400px;
    pointer-events: none;
}

/* Floating alerts */
.floating-alert {
    pointer-events: auto;
    margin-bottom: 10px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    border: none;
    animation: slideInRight 0.3s ease-out;
}

/* Ensure background colors for different alert types */
.floating-alert.alert-success {
    background-color: #d1e7dd;
    color: #0f5132;
    border-color: #badbcc;
}

.floating-alert.alert-danger {
    background-color: #f8d7da;
    color: #842029;
    border-color: #f5c2c7;
}

.floating-alert.alert-warning {
    background-color: #fff3cd;
    color: #664d03;
    border-color: #ffecb5;
}

.floating-alert.alert-info {
    background-color: #cff4fc;
    color: #055160;
    border-color: #b6effb;
}

/* Animation for alerts sliding in */
@keyframes slideInRight {
    from {
        transform: translateX(100%);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}

/* Animation for alerts sliding out */
.floating-alert.fade-out {
    animation: slideOutRight 0.3s ease-in forwards;
}

@keyframes slideOutRight {
    from {
        transform: translateX(0);
        opacity: 1;
    }
    to {
        transform: translateX(100%);
        opacity: 0;
    }
}
</style>