<?php
// Permission checking is now handled by the permission system in auto-prepend.php

require_once('/docker/whp/web/libs/emailmgmt.php');

$EmailMgmt = new emailmgmt();

$message = '';
$message_type = '';

// Test mail server connection and validate configuration
$mail_server_status = null;
$mail_server_available = false;
try {
    $mail_server_status = $EmailMgmt->testMailServerConnection();
    $mail_server_available = ($mail_server_status['status'] === 'success');
} catch (Exception $e) {
    $mail_server_status = [
        'status' => 'error',
        'message' => $e->getMessage()
    ];
}

// If mail server is not configured or not available, show configuration message
if (!$mail_server_available) {
    ?>
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">Email Management</h5>
                </div>
                <div class="card-body">
                    <div class="alert alert-warning">
                        <i class="fa fa-exclamation-triangle"></i>
                        <strong>Mail Server Configuration Required</strong>
                        <p class="mb-3">Email management requires a configured mail server. Please configure your mail server settings to continue.</p>
                        <p class="mb-3"><strong>Error:</strong> <?php echo htmlspecialchars($mail_server_status['message']); ?></p>
                        <?php if (AUTH_USER === 'root'): ?>
                        <a href="?page=server-settings" class="btn btn-primary">
                            <i class="fa fa-cog"></i> Configure Mail Server
                        </a>
                        <?php else: ?>
                        <p class="mb-0">Please contact your administrator to configure the mail server.</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php
    return;
}

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'create_email_account':
                if (!empty($_POST['email_address']) && !empty($_POST['password']) && !empty($_POST['domain_name'])) {
                    // Determine the target user (for root users creating accounts for others)
                    $target_user = AUTH_USER;
                    if (AUTH_USER === 'root' && !empty($_POST['target_user'])) {
                        $target_user = $_POST['target_user'];
                    } elseif (AUTH_USER === 'root' && !empty($_POST['username'])) {
                        // Fallback for the hidden username field from JS
                        $target_user = $_POST['username'];
                    }

                    $result = $EmailMgmt->createEmailAccount(
                        $target_user,
                        $_POST['email_address'],
                        $_POST['password'],
                        $_POST['domain_name'],
                        isset($_POST['quota_mb']) ? intval($_POST['quota_mb']) : 100
                    );

                    if ($result['status'] === '0') {
                        $message = $result['msg'];
                        $message_type = 'success';

                        // Optional: also enable Bichon archival on this brand-new mailbox.
                        // Push/journaling model: archival is an ingest-only NoSync account,
                        // so no mailbox password is handed to Bichon. enableArchival re-checks
                        // the target user's remaining seats internally — so a missing or
                        // zero quota becomes a non-fatal warning rather than rolling back
                        // the new account (root deliberately created it; we shouldn't
                        // delete it just because archival couldn't be turned on).
                        if (!empty($_POST['enable_archival_on_create']) && BichonClient::isConfigured() && !empty($result['email_id'])) {
                            $arch = $EmailMgmt->enableArchival((int)$result['email_id'], AUTH_USER);
                            if (($arch['status'] ?? '') === 'success') {
                                $message .= ' Archival enabled.';
                                if (!empty($arch['bichon_username'])) {
                                    $message .= ' Archive login username: ' . $arch['bichon_username'] . '.';
                                }
                            } else {
                                $message     .= ' (Account created, but archival could not be enabled: ' . ($arch['message'] ?? 'unknown error') . ')';
                                $message_type = 'warning';
                            }
                        }
                    } else {
                        $message = $result['msg'];
                        $message_type = 'danger';
                    }
                }
                break;
                
            case 'update_email_account':
                if (!empty($_POST['email_id'])) {
                    $email_id   = intval($_POST['email_id']);
                    $newPass    = $_POST['password'] ?? '';
                    $archAction = $_POST['archival_action'] ?? '';

                    // Determine current archival state for transition logic.
                    $cur = $EmailMgmt->getArchivalStatus($email_id);
                    $curEnabled = !empty($cur['archival_enabled']);
                    $curPaused  = $curEnabled && !empty($cur['archival_paused_at']);

                    // Enabling archival (push/journaling model) needs no mailbox
                    // password — it provisions an ingest-only NoSync account.
                    // Resuming a paused IMAP-era account still re-supplies the
                    // IMAP credential, so it requires a non-empty new password.
                    $turningOn  = ($archAction === 'on'  && !$curEnabled);
                    $resuming   = ($archAction === 'on'  && $curPaused);
                    $turningOff = ($archAction === 'off' && $curEnabled);

                    if ($resuming && empty($newPass)) {
                        $message      = 'Set a new password to resume archival — IMAP login is failing with the old one.';
                        $message_type = 'danger';
                        break;
                    }

                    // 1. Apply the email-account update first (password/quota/active).
                    $updates = [];
                    if (!empty($newPass))             { $updates['password'] = $newPass; }
                    if (isset($_POST['quota_mb']))    { $updates['quota_mb'] = intval($_POST['quota_mb']); }
                    if (isset($_POST['active']))      { $updates['active']   = $_POST['active'] === '1'; }

                    if (!empty($updates)) {
                        $result = $EmailMgmt->updateEmailAccount(
                            $email_id,
                            AUTH_USER,
                            $updates['password'] ?? null,
                            $updates['quota_mb'] ?? null,
                            $updates['active'] ?? null
                        );
                        if ($result['status'] !== '0') {
                            $message      = $result['msg'];
                            $message_type = 'danger';
                            break;
                        }
                        $message      = $result['msg'];
                        $message_type = 'success';
                    } else {
                        $message      = 'No mailbox changes';
                        $message_type = 'info';
                    }

                    // 2. Apply the archival transition, if any.
                    if ($turningOn) {
                        $r = $EmailMgmt->enableArchival($email_id, AUTH_USER, null);
                        if (($r['status'] ?? '') === 'success') {
                            $message      .= ' Archival enabled.';
                            if (!empty($r['bichon_username'])) {
                                $message .= ' Archive login username: ' . $r['bichon_username'] . '.';
                            }
                            $message_type  = 'success';
                        } else {
                            $message      .= ' (Archival enable failed: ' . ($r['message'] ?? 'unknown error') . ')';
                            $message_type  = 'warning';
                        }
                    } elseif ($resuming) {
                        $r = $EmailMgmt->resumeArchival($email_id, AUTH_USER, $newPass);
                        if (($r['status'] ?? '') === 'success') {
                            $message      .= ' Archival resumed.';
                            $message_type  = 'success';
                        } else {
                            $message      .= ' (Archival resume failed: ' . ($r['message'] ?? 'unknown error') . ')';
                            $message_type  = 'warning';
                        }
                    } elseif ($turningOff) {
                        $r = $EmailMgmt->disableArchival($email_id, AUTH_USER);
                        if (($r['status'] ?? '') === 'success') {
                            // Don't surface the 14-day retention window to customers — that's
                            // an admin-only implementation detail.
                            $message .= AUTH_USER === 'root'
                                ? ' Archival disabled (archive retained 14 days).'
                                : ' Archival disabled.';
                        } else {
                            $message      .= ' (Archival disable failed: ' . ($r['message'] ?? 'unknown error') . ')';
                            $message_type  = 'warning';
                        }
                    }
                }
                break;
                
            case 'delete_email_account':
                if (!empty($_POST['email_id'])) {
                    $result = $EmailMgmt->deleteEmailAccount(intval($_POST['email_id']), AUTH_USER);
                    
                    if ($result['status'] === '0') {
                        $message = $result['msg'];
                        $message_type = 'success';
                    } else {
                        $message = $result['msg'];
                        $message_type = 'danger';
                    }
                }
                break;
                
            case 'create_forwarder':
                if (!empty($_POST['source_email']) && !empty($_POST['destination_email'])) {
                    // Determine the target user (for root users creating forwarders for others)
                    $target_user = AUTH_USER;
                    if (AUTH_USER === 'root' && !empty($_POST['forwarding_target_user'])) {
                        $target_user = $_POST['forwarding_target_user'];
                    }
                    
                    $result = $EmailMgmt->createEmailForwarder(
                        $target_user,
                        $_POST['source_email'],
                        $_POST['destination_email']
                    );
                    
                    if ($result['status'] === '0') {
                        $message = $result['msg'];
                        $message_type = 'success';
                    } else {
                        $message = $result['msg'];
                        $message_type = 'danger';
                    }
                }
                break;
                
            case 'delete_forwarder':
                if (!empty($_POST['forwarder_id'])) {
                    $result = $EmailMgmt->deleteEmailForwarder(intval($_POST['forwarder_id']), AUTH_USER);
                    
                    if ($result['status'] === '0') {
                        $message = $result['msg'];
                        $message_type = 'success';
                    } else {
                        $message = $result['msg'];
                        $message_type = 'danger';
                    }
                }
                break;
                
            case 'create_alias':
                if (!empty($_POST['alias_email']) && !empty($_POST['target_email'])) {
                    // Determine the target user (for root users creating aliases for others)
                    $target_user = AUTH_USER;
                    if (AUTH_USER === 'root' && !empty($_POST['forwarding_target_user'])) {
                        $target_user = $_POST['forwarding_target_user'];
                    }
                    
                    $result = $EmailMgmt->createEmailAlias(
                        $target_user,
                        $_POST['alias_email'],
                        $_POST['target_email']
                    );
                    
                    if ($result['status'] === '0') {
                        $message = $result['msg'];
                        $message_type = 'success';
                    } else {
                        $message = $result['msg'];
                        $message_type = 'danger';
                    }
                }
                break;
                
            case 'delete_alias':
                if (!empty($_POST['alias_id'])) {
                    $result = $EmailMgmt->deleteEmailAlias(intval($_POST['alias_id']), AUTH_USER);
                    
                    if ($result['status'] === '0') {
                        $message = $result['msg'];
                        $message_type = 'success';
                    } else {
                        $message = $result['msg'];
                        $message_type = 'danger';
                    }
                }
                break;
                
            case 'update_domain':
                if (!empty($_POST['domain_name']) && AUTH_USER === 'root') {
                    $updates = [];
                    $updateable_fields = [
                        'forward', 'forward_domain', 'domain_bin', 'domain_bin_address',
                        'force_route', 'force_route_host', 'custom_outbound', 'outbound_ip',
                        'outbound_ehlo', 'reference_id', 'disabled', 'name'
                    ];
                    
                    foreach ($updateable_fields as $field) {
                        if (isset($_POST[$field])) {
                            // Convert checkbox values to proper boolean for disabled field
                            if ($field === 'disabled') {
                                $updates[$field] = ($_POST[$field] === '1');
                            } else {
                                $updates[$field] = $_POST[$field];
                            }
                        }
                    }
                    
                    if (!empty($updates)) {
                        $result = $EmailMgmt->updateMailServerDomain($_POST['domain_name'], $updates);
                        
                        if ($result['status'] === '0') {
                            $message = $result['msg'];
                            $message_type = 'success';
                        } else {
                            $message = $result['msg'];
                            $message_type = 'danger';
                        }
                    } else {
                        $message = 'No changes specified';
                        $message_type = 'warning';
                    }
                }
                break;
                
            case 'import_email_accounts':
                if (AUTH_USER === 'root' && !empty($_POST['import_domain'])) {
                    $result = $EmailMgmt->importEmailAccountsFromMailServer($_POST['import_domain']);
                    
                    if ($result['status'] === '0') {
                        $message = $result['msg'];
                        $message_type = 'success';
                    } else {
                        $message = $result['msg'];
                        $message_type = 'danger';
                    }
                }
                break;
        }
    }
}

// Get email accounts
$accounts_result = $EmailMgmt->getEmailAccounts(AUTH_USER);
$accounts = [];
if ($accounts_result['status'] === '0') {
    $accounts = $accounts_result['accounts'];
}

// Bichon archival pre-computations
require_once('/docker/whp/web/libs/BichonClient.php');
$bichon_configured  = BichonClient::isConfigured();
$archival_summary   = $EmailMgmt->canEnableArchival(AUTH_USER);
$archival_remaining = (int)($archival_summary['remaining'] ?? 0);
$archival_max       = (int)($archival_summary['max_allowed'] ?? 0);
$archival_current   = (int)($archival_summary['current_count'] ?? 0);

// Customer-facing Bichon WebUI URL (shown only if at least one row is archived).
$bichon_url = '';
if ($bichon_configured) {
    $bichon_cfg = BichonClient::loadConfig();
    if (is_array($bichon_cfg) && !empty($bichon_cfg['url'])) {
        $bichon_url = (string)$bichon_cfg['url'];
    }
}
$has_archived_mailbox = false;
if ($bichon_configured && !empty($accounts)) {
    foreach ($accounts as $_acct) {
        if (!empty($_acct['archival_enabled'])) { $has_archived_mailbox = true; break; }
    }
}

// For root: build a {username: remaining} map so the create-email modal can
// gate the "Enable archival" checkbox on the *target* user's remaining seats
// (not root's own). Empty for non-root.
$archival_seat_map = [];
if ($bichon_configured && AUTH_USER === 'root') {
    try {
        $_seat_db = (new mysqlmgmt())->getMySQLConnection();
        if ($_seat_db) {
            $rows = $_seat_db->query("
                SELECT ca.username,
                       COALESCE(ca.max_archived_mailboxes, 0) AS max_allowed,
                       COALESCE(SUM(CASE WHEN ea.archival_enabled = 1 THEN 1 ELSE 0 END), 0) AS used
                  FROM whp.client_allowances ca
                  LEFT JOIN whp.email_accounts ea ON ea.username = ca.username AND ea.active = 1
              GROUP BY ca.username, ca.max_archived_mailboxes
            ")->fetchAll(PDO::FETCH_ASSOC);
            foreach ($rows as $r) {
                $archival_seat_map[$r['username']] = [
                    'max'       => (int)$r['max_allowed'],
                    'used'      => (int)$r['used'],
                    'remaining' => max(0, (int)$r['max_allowed'] - (int)$r['used']),
                ];
            }
        }
    } catch (Exception $e) {
        error_log("email-management: failed to build archival seat map: " . $e->getMessage());
    }
}

// Get user domains for email creation
$domains_result = $EmailMgmt->getUserDomains(AUTH_USER);
$domains = [];
if ($domains_result['status'] === '0') {
    $domains = $domains_result['domains'];
}

// Get email usage statistics
$usage_result = $EmailMgmt->getEmailUsageStats(AUTH_USER);
$usage_stats = [];
if ($usage_result['status'] === '0') {
    $usage_stats = $usage_result;
}

// Get email forwarders
$forwarders_result = $EmailMgmt->getEmailForwarders(AUTH_USER);
$forwarders = [];
if ($forwarders_result['status'] === '0') {
    $forwarders = $forwarders_result['forwarders'];
}

// Get email aliases
$aliases_result = $EmailMgmt->getEmailAliases(AUTH_USER);
$aliases = [];
if ($aliases_result['status'] === '0') {
    $aliases = $aliases_result['aliases'];
}

// Check if user can create more email accounts (root bypasses this check)
$can_create = false;
$remaining_accounts = 0;
if (AUTH_USER === 'root') {
    $can_create = true; // Root can always create email accounts
} else {
    $can_create_result = $EmailMgmt->canCreateEmailAccount(AUTH_USER);
    if ($can_create_result['status'] === '0') {
        $can_create = $can_create_result['can_create'];
        $remaining_accounts = $can_create_result['remaining'];
    }
}

// Get domains from WHP database (for root users)
$whp_domains = [];
$valid_domain_count = 0;
if (AUTH_USER === 'root') {
    $domains_result = $EmailMgmt->getAllWhpDomains();
    if ($domains_result['status'] === '0') {
        $whp_domains = $domains_result['domains'];
        $valid_domain_count = count($whp_domains);
    }
}
?>

<div class="row">
    <div class="col-md-12">
        <?php if (!empty($message)): ?>
        <div class="alert alert-<?php echo $message_type; ?> alert-dismissible" role="alert">
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            <i class="fa fa-<?php echo $message_type === 'success' ? 'check' : 'exclamation-triangle'; ?>"></i>
            <?php echo nl2br(htmlspecialchars($message)); ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<?php
// Get mail server domain from settings
$mail_server_domain = 'mail.example.com';
$server_settings = [];
if (file_exists('/docker/whp/settings.json')) {
    $settings_content = file_get_contents('/docker/whp/settings.json');
    if ($settings_content) {
        $server_settings = json_decode($settings_content, true) ?: [];
        $mail_server_domain = $server_settings['mail_server'] ?? 'mail.example.com';
    }
}
?>

<?php if (AUTH_USER === 'root'): ?>
<!-- Mail Server Status -->
<div class="row mb-4">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">Mail Server Status</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="d-flex align-items-center">
                            <div class="me-3">
                                <i class="fa fa-<?php echo $mail_server_status['status'] === 'success' ? 'check-circle text-success' : 'times-circle text-danger'; ?> fa-2x"></i>
                            </div>
                            <div>
                                <h6 class="mb-1">Connection Status</h6>
                                <p class="mb-0 text-muted"><?php echo htmlspecialchars($mail_server_status['message']); ?></p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="d-flex align-items-center">
                            <div class="me-3">
                                <i class="fa fa-server fa-2x text-info"></i>
                            </div>
                            <div>
                                <h6 class="mb-1">Domains</h6>
                                <p class="mb-0 text-muted"><?php echo $valid_domain_count; ?> domains configured</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Mail Server Access Links -->
<div class="row mb-4">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">Mail Server Access</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4">
                        <div class="text-center">
                            <div class="mb-3">
                                <i class="fa fa-envelope fa-3x text-primary"></i>
                            </div>
                            <h6>Webmail Access</h6>
                            <p class="text-muted small mb-3">Access your email through the web interface</p>
                            <a href="https://<?php echo htmlspecialchars($mail_server_domain); ?>/webmail/" target="_blank" class="btn btn-outline-primary btn-sm">
                                <i class="fa fa-external-link"></i> Open Webmail
                            </a>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="text-center">
                            <div class="mb-3">
                                <i class="fa fa-cog fa-3x text-success"></i>
                            </div>
                            <h6>Advanced Settings</h6>
                            <p class="text-muted small mb-3">Manage email spam and autoresponder settings</p>
                            <a href="https://<?php echo htmlspecialchars($mail_server_domain); ?>/admin/login" target="_blank" class="btn btn-outline-success btn-sm">
                                <i class="fa fa-external-link"></i> Admin Panel
                            </a>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="text-center">
                            <div class="mb-3">
                                <i class="fa fa-book fa-3x text-info"></i>
                            </div>
                            <h6>Setup Instructions</h6>
                            <p class="text-muted small mb-3">View detailed setup and configuration guides</p>
                            <a href="https://<?php echo htmlspecialchars($mail_server_domain); ?>/admin/install/instructions" target="_blank" class="btn btn-outline-info btn-sm">
                                <i class="fa fa-external-link"></i> View Instructions
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Email Usage Statistics -->
<div class="row mb-4">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">Email Usage Statistics</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4">
                        <div class="text-center">
                            <h4 class="text-primary"><?php echo $usage_stats['current_accounts'] ?? 0; ?></h4>
                            <p class="text-muted mb-0">Email Accounts</p>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="text-center">
                            <h4 class="text-success"><?php echo $usage_stats['forwarders'] ?? 0; ?></h4>
                            <p class="text-muted mb-0">Forwarders</p>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="text-center">
                            <h4 class="text-warning"><?php echo $remaining_accounts; ?></h4>
                            <p class="text-muted mb-0">Remaining Email Accounts</p>
                        </div>
                    </div>
                </div>
                <?php if (isset($usage_stats['max_accounts']) && $usage_stats['max_accounts'] > 0): ?>
                <div class="mt-3">
                    <div class="progress">
                        <div class="progress-bar <?php echo ($usage_stats['current_accounts'] / $usage_stats['max_accounts']) > 0.8 ? 'bg-danger' : (($usage_stats['current_accounts'] / $usage_stats['max_accounts']) > 0.6 ? 'bg-warning' : 'bg-success'); ?>" 
                             role="progressbar" style="width: <?php echo min(($usage_stats['current_accounts'] / $usage_stats['max_accounts']) * 100, 100); ?>%" 
                             aria-valuenow="<?php echo $usage_stats['current_accounts']; ?>" aria-valuemin="0" aria-valuemax="<?php echo $usage_stats['max_accounts']; ?>">
                        </div>
                    </div>
                    <small class="text-muted"><?php echo $usage_stats['current_accounts']; ?> of <?php echo $usage_stats['max_accounts']; ?> email accounts used</small>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php if (AUTH_USER === 'root' && $mail_server_status): ?>
<!-- Mail Server Status -->
<div class="row mb-4">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">Mail Server Status</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="d-flex align-items-center">
                            <div class="me-3">
                                <i class="fa fa-<?php echo $mail_server_status['status'] === 'success' ? 'check-circle text-success' : 'times-circle text-danger'; ?> fa-2x"></i>
                            </div>
                            <div>
                                <h6 class="mb-1">Connection Status</h6>
                                <p class="mb-0 text-muted"><?php echo htmlspecialchars($mail_server_status['message']); ?></p>
                                <?php if ($mail_server_status['status'] === 'error' && strpos($mail_server_status['message'], 'configure') !== false): ?>
                                <div class="mt-2">
                                    <a href="?page=server-settings" class="btn btn-sm btn-outline-primary">
                                        <i class="fa fa-cog"></i> Configure Mail Server
                                    </a>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="d-flex align-items-center">
                            <div class="me-3">
                                <i class="fa fa-server fa-2x text-info"></i>
                            </div>
                            <div>
                                <h6 class="mb-1">Mail Server</h6>
                                <p class="mb-0 text-muted">Integrated with external mail server API</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<?php if (AUTH_USER === 'root'): ?>
<!-- Email Import Section -->
<div class="row mb-4">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">Import Email Accounts</h5>
            </div>
            <div class="card-body">
                <p class="text-muted mb-3">Import existing email accounts from the mail server for domains that have been added to this server.</p>
                
                <form method="POST" action="" id="importEmailForm">
                    <input type="hidden" name="action" value="import_email_accounts">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    <div class="row">
                        <div class="col-md-8">
                            <div class="mb-3">
                                <label for="import_domain" class="form-label">Select Domain to Import</label>
                                <select class="form-select" id="import_domain" name="import_domain" required>
                                    <option value="">-- Select a domain --</option>
                                    <?php
                                    // Get domains available for import
                                    $import_domains_result = $EmailMgmt->getDomainsAvailableForImport();
                                    if ($import_domains_result['status'] === '0' && !empty($import_domains_result['domains'])) {
                                        foreach ($import_domains_result['domains'] as $domain_info) {
                                            echo '<option value="' . htmlspecialchars($domain_info['domain_name']) . '">' . 
                                                 htmlspecialchars($domain_info['domain_name']) . ' (' . htmlspecialchars($domain_info['username']) . ')</option>';
                                        }
                                    }
                                    ?>
                                </select>
                                <div class="form-text">Only domains that have been added to this server can be imported.</div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label">&nbsp;</label>
                                <button type="submit" class="btn btn-primary w-100" id="importButton">
                                    <i class="fa fa-download"></i> Import Email Accounts
                                </button>
                            </div>
                        </div>
                    </div>
                </form>
                
                <div class="alert alert-info mt-3">
                    <i class="fa fa-info-circle"></i>
                    <strong>Note:</strong> This will import all email accounts and forwarders for the selected domain from the mail server. 
                    Existing accounts will be skipped. Imported accounts will be assigned temporary passwords that users must reset.
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<?php if ($bichon_configured && $has_archived_mailbox && $bichon_url !== ''): ?>
<!-- Email Archival Access -->
<div class="row mb-4">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">Email Archival</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-12">
                        <div class="text-center">
                            <div class="mb-3">
                                <i class="fa fa-archive fa-3x text-success"></i>
                            </div>
                            <h6>Access Your Archive</h6>
                            <p class="text-muted small mb-3">Sign in with your email address as the username and your archive password.</p>
                            <a href="<?php echo htmlspecialchars($bichon_url); ?>" target="_blank" rel="noopener" class="btn btn-outline-success btn-sm">
                                <i class="fa fa-external-link"></i> Open Archive
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Email Accounts Section -->
<div class="row mb-4">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">Email Accounts</h5>
                <?php if ($can_create && ((!empty($domains)) || (AUTH_USER === 'root' && !empty($whp_domains)))): ?>
                <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#createEmailModal">
                    <i class="fa fa-plus"></i> Create Email Account
                </button>
                <?php endif; ?>
            </div>
            <div class="card-body">
                <?php if ($bichon_configured && AUTH_USER !== 'root'): ?>
                <div class="text-muted small mb-2">
                  <i class="fa fa-archive"></i> Archival: <?php echo $archival_current; ?>
                  of <?php echo $archival_max; ?> mailboxes archived
                  <?php if ($archival_max === 0): ?>(no archival slots in your plan)<?php endif; ?>
                </div>
                <?php endif; ?>
                <?php if (empty($domains) && (AUTH_USER !== 'root' || empty($whp_domains))): ?>
                <div class="alert alert-warning">
                    <i class="fa fa-exclamation-triangle"></i>
                    <strong>No domains available</strong> - You need to add domains in the Domains section before creating email accounts.
                </div>
                <?php elseif (!$can_create): ?>
                <div class="alert alert-warning">
                    <i class="fa fa-exclamation-triangle"></i>
                    <strong>Email account limit reached</strong> - You have reached your maximum allowed email accounts.
                </div>
                <?php endif; ?>
                
                <?php if (empty($accounts)): ?>
                <div class="alert alert-info">
                    <i class="fa fa-info-circle"></i>
                    <strong>No email accounts found</strong> - Create your first email account to get started.
                </div>
                <?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="emailSearchInput" placeholder="Search email accounts...">
                        </div>
                    </div>
                    <?php if (AUTH_USER === 'root'): ?>
                    <div class="col-md-3">
                        <select class="form-select" id="emailUserFilter">
                            <option value="">All Users</option>
                            <?php
                            $email_users = array_unique(array_column($accounts, 'username'));
                            sort($email_users);
                            foreach ($email_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 (AUTH_USER === 'root') ? '3' : '6'; ?> text-end">
                        <small class="text-muted" id="emailTableInfo"></small>
                    </div>
                </div>

                <div class="table-responsive">
                    <table class="table table-striped" id="emailAccountsTable">
                        <thead>
                            <tr>
                                <?php if (AUTH_USER === 'root'): ?>
                                <th>User</th>
                                <?php endif; ?>
                                <th>Email Address</th>
                                <th>Domain</th>
                                <th>Quota</th>
                                <th>Status</th>
                                <th>Archival</th>
                                <th>Created</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($accounts as $account): ?>
                            <tr data-username="<?php echo htmlspecialchars($account['username']); ?>">
                                <?php if (AUTH_USER === 'root'): ?>
                                <td><?php echo htmlspecialchars($account['username']); ?></td>
                                <?php endif; ?>
                                <td>
                                    <strong><?php echo htmlspecialchars($account['email_address']); ?></strong>
                                </td>
                                <td><?php echo htmlspecialchars($account['domain_name']); ?></td>
                                <td><?php echo number_format($account['quota_mb']); ?> MB</td>
                                <td>
                                    <span class="badge <?php echo $account['active'] ? 'bg-success' : 'bg-secondary'; ?>">
                                        <?php echo $account['active'] ? 'Enabled' : 'Disabled'; ?>
                                    </span>
                                </td>
                                <td>
                                    <?php if (!empty($account['archival_enabled'])): ?>
                                        <?php if (!empty($account['archival_paused_at'])): ?>
                                            <span class="badge bg-warning text-dark"
                                                  title="<?php echo htmlspecialchars($account['archival_last_error'] ?? 'Paused'); ?>">
                                                <i class="fa fa-pause"></i> Paused
                                            </span>
                                        <?php else: ?>
                                            <span class="badge bg-success" title="Bichon is syncing this mailbox">
                                                <i class="fa fa-archive"></i> Archiving
                                            </span>
                                        <?php endif; ?>
                                        <?php if (!empty($account['bichon_username'])): ?>
                                            <div class="small text-muted mt-1" title="Log in to the archive with this username and your archive login password">
                                                Archive login: <code><?php echo htmlspecialchars($account['bichon_username']); ?></code>
                                            </div>
                                        <?php endif; ?>
                                    <?php elseif ($bichon_configured && $archival_max > 0): ?>
                                        <span class="badge bg-secondary">Off</span>
                                    <?php else: ?>
                                        <span class="text-muted small">&mdash;</span>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo whp_local_time($account['created_at'], 'M j, Y'); ?></td>
                                <td>
                                    <button type="button" class="btn btn-sm btn-outline-info"
                                            onclick="showEmailStats('<?php echo htmlspecialchars($account['email_address']); ?>')"
                                            title="View Statistics">
                                        <i class="fa fa-archive"></i>
                                    </button>
                                    <?php
                                    $archStateForRow = !empty($account['archival_enabled'])
                                        ? (!empty($account['archival_paused_at']) ? 'paused' : 'archiving')
                                        : 'off';
                                    // Slot check is against the MAILBOX OWNER's plan, not the viewer's
                                    // (root has no plan; falling back to root's globals would always
                                    // disable archival management for everyone). Reuse the seat map
                                    // already computed for the create-email modal when viewing as root.
                                    if (AUTH_USER === 'root') {
                                        $_seats = $archival_seat_map[$account['username']] ?? ['max' => 0, 'remaining' => 0];
                                        $row_max       = (int)$_seats['max'];
                                        $row_remaining = (int)$_seats['remaining'];
                                    } else {
                                        $row_max       = $archival_max;
                                        $row_remaining = $archival_remaining;
                                    }
                                    ?>
                                    <button type="button" class="btn btn-sm btn-outline-primary"
                                            onclick="editEmailAccount(<?php echo (int)$account['id']; ?>, '<?php echo htmlspecialchars($account['email_address'], ENT_QUOTES); ?>', <?php echo (int)$account['quota_mb']; ?>, <?php echo $account['active'] ? 'true' : 'false'; ?>, '<?php echo $archStateForRow; ?>', <?php echo $row_remaining; ?>, <?php echo $row_max; ?>)">
                                        <i class="fa fa-edit"></i>
                                    </button>
                                    <?php if ($bichon_configured && $row_max > 0): ?>
                                        <?php
                                        $archDisabled = !$account['archival_enabled'] && $row_remaining <= 0;
                                        $archAction   = $account['archival_enabled'] ? 'showDisableArchivalModal' : 'showEnableArchivalModal';
                                        $archTitle    = $account['archival_enabled']
                                            ? 'Disable archival'
                                            : ($archDisabled ? 'No archival slots remaining' : 'Enable archival');
                                        $archClass    = $account['archival_enabled'] ? 'btn-outline-warning' : 'btn-outline-success';
                                        ?>
                                        <button type="button"
                                                class="btn btn-sm <?php echo $archClass; ?>"
                                                <?php echo $archDisabled ? 'disabled' : ''; ?>
                                                onclick="<?php echo $archAction; ?>(<?php echo (int)$account['id']; ?>, '<?php echo htmlspecialchars($account['email_address'], ENT_QUOTES); ?>')"
                                                title="<?php echo htmlspecialchars($archTitle, ENT_QUOTES); ?>">
                                            <i class="fa fa-archive"></i>
                                        </button>
                                        <?php if (!empty($account['archival_enabled'])): ?>
                                        <?php $isImapMode = (($account['archival_mode'] ?? 'nosync') === 'imap'); ?>
                                        <button type="button" class="btn btn-sm btn-outline-info"
                                                onclick="showImportArchiveModal(<?php echo (int)$account['id']; ?>, '<?php echo htmlspecialchars($account['email_address'], ENT_QUOTES); ?>', <?php echo $isImapMode ? 'true' : 'false'; ?>, <?php echo (int)$account['quota_mb']; ?>, <?php echo $account['active'] ? 'true' : 'false'; ?>, '<?php echo $archStateForRow; ?>', <?php echo $row_remaining; ?>, <?php echo $row_max; ?>)"
                                                title="<?php echo $isImapMode ? 'Sync existing mail now' : 'Import existing mail into the archive'; ?>">
                                            <i class="fa fa-download"></i>
                                        </button>
                                        <button type="button" class="btn btn-sm btn-outline-secondary"
                                                onclick="showResetArchivePasswordModal(<?php echo (int)$account['id']; ?>, '<?php echo htmlspecialchars($account['email_address'], ENT_QUOTES); ?>')"
                                                title="Reset archive login password">
                                            <i class="fa fa-key"></i>
                                        </button>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                    <button type="button" class="btn btn-sm btn-outline-danger"
                                            onclick="deleteEmailAccount(<?php echo $account['id']; ?>, '<?php echo htmlspecialchars($account['email_address']); ?>')">
                                        <i class="fa fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

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

<!-- Email Forwarding Section -->
<div class="row mb-4">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">Email Forwarding</h5>
                <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#createForwardingModal">
                    <i class="fa fa-plus"></i> Create Email Forwarder
                </button>
            </div>
            <div class="card-body">
                <p class="text-muted mb-3">Set up email forwarding to redirect incoming emails from one address to another. Create email forwarders to automatically forward emails to external addresses, or create aliases to forward to existing email accounts.</p>
                
                <?php 
                // Group forwarders by source email to show multiple destinations together
                $grouped_forwarders = [];
                foreach ($forwarders as $forwarder) {
                    $source = $forwarder['source_email'];
                    if (!isset($grouped_forwarders[$source])) {
                        $grouped_forwarders[$source] = [
                            'source' => $source,
                            'destinations' => [],
                            'ids' => [],
                            'username' => $forwarder['username'],
                            'active' => $forwarder['active'],
                            'created_at' => $forwarder['created_at']
                        ];
                    }
                    $grouped_forwarders[$source]['destinations'][] = $forwarder['destination_email'];
                    $grouped_forwarders[$source]['ids'][] = $forwarder['id'];
                }
                
                // Combine grouped forwarders and aliases into one list for unified display
                $forwarding_rules = [];
                
                // Add grouped forwarders
                foreach ($grouped_forwarders as $forwarder_group) {
                    $forwarding_rules[] = [
                        'ids' => $forwarder_group['ids'],
                        'type' => 'forwarder',
                        'source' => $forwarder_group['source'],
                        'destinations' => $forwarder_group['destinations'],
                        'username' => $forwarder_group['username'],
                        'active' => $forwarder_group['active'],
                        'created_at' => $forwarder_group['created_at']
                    ];
                }
                
                // Add aliases (keep them separate as they work differently)
                foreach ($aliases as $alias) {
                    $forwarding_rules[] = [
                        'ids' => [$alias['id']],
                        'type' => 'alias',
                        'source' => $alias['alias_email'],
                        'destinations' => [$alias['target_email']],
                        'username' => $alias['username'],
                        'active' => $alias['active'],
                        'created_at' => $alias['created_at']
                    ];
                }
                
                // Sort by active status first, then by creation date (newest first)
                usort($forwarding_rules, function($a, $b) {
                    if ($a['active'] !== $b['active']) {
                        return $b['active'] - $a['active']; // Active first
                    }
                    return strtotime($b['created_at']) - strtotime($a['created_at']);
                });
                ?>
                
                <?php if (empty($forwarding_rules)): ?>
                <div class="alert alert-info">
                    <i class="fa fa-info-circle"></i>
                    <strong>No email forwarding rules found</strong> - Create forwarding rules to redirect emails from one address to another.
                </div>
                <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <?php if (AUTH_USER === 'root'): ?>
                                <th>User</th>
                                <?php endif; ?>
                                <th>Source Email</th>
                                <th>Destination</th>
                                <th>Type</th>
                                <th>Status</th>
                                <th>Created</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($forwarding_rules as $rule): ?>
                            <tr>
                                <?php if (AUTH_USER === 'root'): ?>
                                <td><?php echo htmlspecialchars($rule['username']); ?></td>
                                <?php endif; ?>
                                <td><?php echo htmlspecialchars($rule['source']); ?></td>
                                <td>
                                    <?php 
                                    // Display multiple destinations with proper formatting
                                    if (count($rule['destinations']) > 1) {
                                        echo '<div>';
                                        foreach ($rule['destinations'] as $idx => $dest) {
                                            echo htmlspecialchars($dest);
                                            if ($idx < count($rule['destinations']) - 1) {
                                                echo '<br>';
                                            }
                                        }
                                        echo '</div>';
                                    } else {
                                        echo htmlspecialchars($rule['destinations'][0]);
                                    }
                                    ?>
                                </td>
                                <td>
                                    <?php if ($rule['type'] === 'forwarder'): ?>
                                        <span class="badge bg-primary">Forwarder</span>
                                    <?php else: ?>
                                        <span class="badge bg-info">Alias</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="badge <?php echo $rule['active'] ? 'bg-success' : 'bg-secondary'; ?>">
                                        <?php echo $rule['active'] ? 'Enabled' : 'Disabled'; ?>
                                    </span>
                                </td>
                                <td><?php echo whp_local_time($rule['created_at'], 'M j, Y'); ?></td>
                                <td>
                                    <?php if ($rule['type'] === 'forwarder'): ?>
                                        <?php if (count($rule['ids']) > 1): ?>
                                            <!-- Multiple destinations - show dropdown to delete individually -->
                                            <div class="dropdown">
                                                <button class="btn btn-sm btn-outline-danger dropdown-toggle" type="button" 
                                                        id="dropdownMenuButton-<?php echo $rule['ids'][0]; ?>" 
                                                        data-bs-toggle="dropdown" aria-expanded="false">
                                                    <i class="fa fa-trash"></i>
                                                </button>
                                                <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton-<?php echo $rule['ids'][0]; ?>">
                                                    <?php foreach ($rule['destinations'] as $idx => $dest): ?>
                                                    <li>
                                                        <a class="dropdown-item" href="#" 
                                                           onclick="deleteForwarderDestination(<?php echo $rule['ids'][$idx]; ?>, '<?php echo htmlspecialchars($rule['source']); ?>', '<?php echo htmlspecialchars($dest); ?>'); return false;">
                                                            <i class="fa fa-times"></i> Remove <?php echo htmlspecialchars($dest); ?>
                                                        </a>
                                                    </li>
                                                    <?php endforeach; ?>
                                                </ul>
                                            </div>
                                        <?php else: ?>
                                            <!-- Single destination - simple delete button -->
                                            <button type="button" class="btn btn-sm btn-outline-danger" 
                                                    onclick="deleteForwarder(<?php echo $rule['ids'][0]; ?>, '<?php echo htmlspecialchars($rule['source']); ?>')">
                                                <i class="fa fa-trash"></i>
                                            </button>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <button type="button" class="btn btn-sm btn-outline-danger" 
                                                onclick="deleteAlias(<?php echo $rule['ids'][0]; ?>, '<?php echo htmlspecialchars($rule['source']); ?>')">
                                            <i class="fa fa-trash"></i>
                                        </button>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php if (AUTH_USER === 'root'): ?>
<!-- Email Domain Management Section -->
<div class="row mb-4">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">Email Domain Management</h5>
            </div>
            <div class="card-body">
                <p class="text-muted mb-3">Manage email settings for domains configured in WHP. These domains are automatically synchronized to the mail server when added or removed in the Domains section.</p>
                
                <?php if (empty($whp_domains)): ?>
                <div class="alert alert-info">
                    <i class="fa fa-info-circle"></i>
                    <strong>No domains configured</strong> - No domains are currently configured in WHP. 
                    <br><br>
                    <strong>To add domains:</strong>
                    <ol>
                        <li>Go to the <a href="?page=domains">Domains</a> section</li>
                        <li>Add your domains there</li>
                        <li>They will automatically be synchronized to the mail server</li>
                        <li>Return here to manage email-specific domain settings</li>
                    </ol>
                </div>
                <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>Domain Name</th>
                                <th>Owner</th>
                                <th>Status</th>
                                <th>Mail Server Status</th>
                                <th>Created</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($whp_domains as $domain): ?>
                            <tr>
                                <td><strong><?php echo htmlspecialchars($domain['domain_name']); ?></strong></td>
                                <td><?php echo htmlspecialchars($domain['username']); ?></td>
                                <td>
                                    <span class="badge <?php echo $domain['active'] ? 'bg-success' : 'bg-danger'; ?>">
                                        <?php echo $domain['active'] ? 'Active' : 'Inactive'; ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="badge bg-info">Synchronized</span>
                                    <br><small class="text-muted">Auto-synced with mail server</small>
                                </td>
                                <td>
                                    <?php
                                    $created = $domain['created_at'] ?? 'Jan 1, 1970';
                                    echo whp_local_time($created, 'M j, Y');
                                    ?>
                                </td>
                                <td>
                                    <button type="button" class="btn btn-sm btn-outline-info" 
                                            onclick="showDomainDetails(<?php echo htmlspecialchars(json_encode($domain['domain_name'])); ?>)" 
                                            title="View Mail Server Details">
                                        <i class="fa fa-eye"></i>
                                    </button>
                                    <button type="button" class="btn btn-sm btn-outline-primary" 
                                            onclick="editDomain(<?php echo htmlspecialchars(json_encode($domain['domain_name'])); ?>)" 
                                            title="Edit Mail Server Settings">
                                        <i class="fa fa-edit"></i>
                                    </button>
                                    <button type="button" class="btn btn-sm btn-outline-warning" 
                                            onclick="manageDkim(<?php echo htmlspecialchars(json_encode($domain['domain_name'])); ?>)" 
                                            title="Manage DKIM">
                                        <i class="fa fa-key"></i>
                                    </button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- DKIM Management Section -->
<div class="row mb-4">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">DKIM Management</h5>
            </div>
            <div class="card-body">
                <p class="text-muted mb-3">Manage DKIM (DomainKeys Identified Mail) records for your domains to improve email deliverability and security. DNS records are automatically configured when DKIM is created.</p>

                <div class="mb-3">
                    <input type="text" class="form-control" id="dkimSearch" placeholder="Type a domain name to search&hellip;" autocomplete="off">
                </div>

                <div class="table-responsive">
                    <table class="table table-striped" id="dkimTable" style="display:none;">
                        <thead>
                            <tr>
                                <th>Domain</th>
                                <th>DKIM Status</th>
                                <th>DNS Record</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody id="dkimDomainsTable"></tbody>
                    </table>
                    <div id="dkimEmptyState" class="text-muted text-center py-3">
                        Start typing a domain name above to check or manage DKIM records.
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php if ($bichon_configured): ?>
<div class="row">
    <div class="col-md-12">
        <p class="text-muted small text-center mt-3 mb-3">
            Email Archival is powered by
            <a href="https://github.com/rustmailer/bichon" target="_blank" rel="noopener">Bichon</a>.
        </p>
    </div>
</div>
<?php endif; ?>

<!-- Create Email Account Modal -->
<div class="modal fade" id="createEmailModal" tabindex="-1" aria-labelledby="createEmailModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="action" value="create_email_account">
                <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                <div class="modal-header">
                    <h5 class="modal-title" id="createEmailModalLabel">Create Email Account</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <?php if (AUTH_USER === 'root'): ?>
                    <div class="mb-3">
                        <label for="target_user" class="form-label">User Account</label>
                        <select class="form-select" id="target_user" name="target_user" onchange="updateUserDomains()" required>
                            <option value="">Select user...</option>
                            <?php
                            // Get all users with domains for root
                            try {
                                require_once('/docker/whp/web/libs/mysqlmgmt.php');
                                $MySQLMgmt = new mysqlmgmt();
                                $pdo = $MySQLMgmt->getMySQLConnection();
                                if ($pdo) {
                                    $pdo->exec("USE whp");
                                    $stmt = $pdo->prepare("
                                        SELECT DISTINCT username 
                                        FROM whp.domains 
                                        WHERE active = 1 
                                        ORDER BY username
                                    ");
                                    $stmt->execute();
                                    $users_with_domains = $stmt->fetchAll(PDO::FETCH_ASSOC);
                                    
                                    foreach ($users_with_domains as $user): ?>
                                    <option value="<?php echo htmlspecialchars($user['username']); ?>">
                                        <?php echo htmlspecialchars($user['username']); ?>
                                    </option>
                                    <?php endforeach;
                                }
                            } catch (Exception $e) {
                                // Fallback if query fails
                            }
                            ?>
                        </select>
                        <div class="form-text">Select the user account this email will belong to</div>
                    </div>
                    <?php else: ?>
                    <input type="hidden" name="target_user" value="<?php echo htmlspecialchars(AUTH_USER); ?>">
                    <?php endif; ?>
                    
                    <div class="mb-3">
                        <label for="email_local" class="form-label">Email Address</label>
                        <div class="row g-2">
                            <div class="col-md-6">
                                <div class="input-group">
                                    <input type="text" class="form-control" id="email_local" name="email_local" placeholder="username" required pattern="[a-zA-Z0-9._\-]+">
                                    <span class="input-group-text">@</span>
                                </div>
                                <small class="form-text text-muted">Enter the username part</small>
                            </div>
                            <div class="col-md-6">
                                <select class="form-select" id="domain_name" name="domain_name" required>
                                    <option value="">Select Domain</option>
                                    <?php if (AUTH_USER !== 'root'): ?>
                                        <?php foreach ($domains as $domain): ?>
                                        <option value="<?php echo htmlspecialchars($domain['domain_name']); ?>">
                                            <?php echo htmlspecialchars($domain['domain_name']); ?>
                                        </option>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </select>
                                <small class="form-text text-muted">Choose the domain</small>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="password" class="form-label">Password</label>
                        <div class="input-group">
                            <input type="password" class="form-control" id="password" name="password" required minlength="8" placeholder="Enter or generate a password">
                            <button type="button" class="btn btn-outline-secondary" id="toggleEmailPassword" title="Show/Hide Password">
                                <i class="fa fa-eye" id="toggleEmailPasswordIcon"></i>
                            </button>
                            <button type="button" class="btn btn-outline-primary" id="generateEmailPassword" title="Generate Password">
                                <i class="fa fa-magic"></i>
                            </button>
                            <button type="button" class="btn btn-outline-secondary" id="copyEmailPassword" title="Copy to Clipboard" style="display: none;">
                                <i class="fa fa-copy"></i>
                            </button>
                        </div>
                        <div class="form-text">
                            Minimum 8 characters required. 
                            <span id="passwordStrength" class="badge bg-secondary ms-2" style="display: none;"></span>
                        </div>
                        
                        <!-- Password Generator Options -->
                        <div class="mt-2" id="passwordGenerator" style="display: none;">
                            <div class="card card-body bg-dark text-light">
                                <h6 class="mb-3">Password Generator Options</h6>
                                <div class="row g-2">
                                    <div class="col-md-3">
                                        <label for="passwordLength" class="form-label">Length</label>
                                        <input type="range" class="form-range" id="passwordLength" min="8" max="32" value="16">
                                        <small class="text-muted"><span id="passwordLengthValue">16</span> characters</small>
                                    </div>
                                    <div class="col-md-9">
                                        <label class="form-label">Include</label>
                                        <div class="d-flex flex-wrap gap-3">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" id="includeUppercase" checked>
                                                <label class="form-check-label" for="includeUppercase">A-Z</label>
                                            </div>
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" id="includeLowercase" checked>
                                                <label class="form-check-label" for="includeLowercase">a-z</label>
                                            </div>
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" id="includeNumbers" checked>
                                                <label class="form-check-label" for="includeNumbers">0-9</label>
                                            </div>
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" id="includeSymbols" checked>
                                                <label class="form-check-label" for="includeSymbols">!@#$</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="row mt-2">
                                    <div class="col-12">
                                        <div class="d-flex gap-2">
                                            <button type="button" class="btn btn-sm btn-primary" onclick="generateSecurePassword()">
                                                <i class="fa fa-refresh"></i> Generate New
                                            </button>
                                            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="togglePasswordGenerator()">
                                                <i class="fa fa-times"></i> Close
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="quota_mb" class="form-label">Quota (MB)</label>
                        <input type="number" class="form-control" id="quota_mb" name="quota_mb" value="100" min="10" max="20480">
                        <div class="form-text">Storage limit for this email account (10-20,480 MB)</div>
                    </div>

                    <?php if ($bichon_configured): ?>
                    <div class="form-check mb-3" id="createArchivalRow"<?php echo (AUTH_USER === 'root' || $archival_remaining > 0) ? '' : ' style="display:none;"'; ?>>
                        <input class="form-check-input" type="checkbox" id="enable_archival_on_create" name="enable_archival_on_create" value="1"
                               <?php echo (AUTH_USER !== 'root' && $archival_remaining <= 0) ? 'disabled' : ''; ?>>
                        <label class="form-check-label" for="enable_archival_on_create">
                            Enable Email Archival for this mailbox
                        </label>
                        <div class="form-text" id="createArchivalHint">
                            <?php if (AUTH_USER === 'root'): ?>
                                Pick a user above to see their archival seat usage.
                            <?php else: ?>
                                <?php echo $archival_remaining; ?> of <?php echo $archival_max; ?> archival slots remaining in your plan.
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </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">Create Account</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php if ($bichon_configured && AUTH_USER === 'root'): ?>
<script>
// Per-user archival-seat map for the root create-mailbox modal. Updates the
// "Enable archival" checkbox state when the target user dropdown changes.
window.WHP_ARCHIVAL_SEATS = <?php echo json_encode($archival_seat_map, JSON_HEX_TAG | JSON_HEX_AMP); ?>;
(function () {
  const sel = document.getElementById('target_user');
  const cb  = document.getElementById('enable_archival_on_create');
  const row = document.getElementById('createArchivalRow');
  const hint = document.getElementById('createArchivalHint');
  if (!sel || !cb || !row || !hint) return;
  function syncArchivalUI() {
    const u = sel.value;
    const seats = u && window.WHP_ARCHIVAL_SEATS[u] ? window.WHP_ARCHIVAL_SEATS[u] : null;
    if (!u) {
      cb.checked = false; cb.disabled = true;
      hint.textContent = 'Pick a user above to see their archival seat usage.';
      return;
    }
    if (!seats || seats.max === 0) {
      cb.checked = false; cb.disabled = true;
      hint.textContent = u + ' has no archival slots in their plan.';
      return;
    }
    if (seats.remaining <= 0) {
      cb.checked = false; cb.disabled = true;
      hint.textContent = u + ' has used all ' + seats.max + ' archival slots — disable one before enabling another.';
      return;
    }
    cb.disabled = false;
    hint.textContent = seats.remaining + ' of ' + seats.max + ' archival slots remaining for ' + u + '.';
  }
  sel.addEventListener('change', syncArchivalUI);
  syncArchivalUI();
})();
</script>
<?php endif; ?>

<!-- Create Email Forwarder Modal -->
<div class="modal fade" id="createForwardingModal" tabindex="-1" aria-labelledby="createForwardingModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST" id="createForwardingForm">
                <input type="hidden" name="action" value="create_forwarder">
                <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                <div class="modal-header">
                    <h5 class="modal-title" id="createForwardingModalLabel">Create Email Forwarder</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <?php if (AUTH_USER === 'root'): ?>
                    <div class="mb-3">
                        <label for="forwarding_target_user" class="form-label">User Account</label>
                        <select class="form-select" id="forwarding_target_user" name="forwarding_target_user" onchange="updateForwarderUserDomains()" required>
                            <option value="">Select user...</option>
                            <?php
                            // Get all users with domains for root
                            try {
                                require_once('/docker/whp/web/libs/mysqlmgmt.php');
                                $MySQLMgmt = new mysqlmgmt();
                                $pdo = $MySQLMgmt->getMySQLConnection();
                                if ($pdo) {
                                    $pdo->exec("USE whp");
                                    $stmt = $pdo->prepare("
                                        SELECT DISTINCT username 
                                        FROM whp.domains 
                                        WHERE active = 1 
                                        ORDER BY username
                                    ");
                                    $stmt->execute();
                                    $users_with_domains = $stmt->fetchAll(PDO::FETCH_ASSOC);
                                    
                                    foreach ($users_with_domains as $user): ?>
                                    <option value="<?php echo htmlspecialchars($user['username']); ?>">
                                        <?php echo htmlspecialchars($user['username']); ?>
                                    </option>
                                    <?php endforeach;
                                }
                            } catch (Exception $e) {
                                // Fallback if query fails
                            }
                            ?>
                        </select>
                        <div class="form-text">Select the user account this forwarder will belong to</div>
                    </div>
                    <?php else: ?>
                    <input type="hidden" name="forwarding_target_user" value="<?php echo htmlspecialchars(AUTH_USER); ?>">
                    <?php endif; ?>
                    
                    <div class="mb-3">
                        <label for="source_email_local" class="form-label">Source Email Address</label>
                        <div class="row g-2">
                            <div class="col-md-6">
                                <div class="input-group">
                                    <input type="text" class="form-control" id="source_email_local" name="source_email_local" placeholder="username" required pattern="[a-zA-Z0-9._\-]+">
                                    <span class="input-group-text">@</span>
                                </div>
                                <small class="form-text text-muted">Enter the username part</small>
                            </div>
                            <div class="col-md-6">
                                <select class="form-select" id="source_domain_name" name="source_domain_name" required>
                                    <option value="">Select Domain</option>
                                    <?php if (AUTH_USER !== 'root'): ?>
                                        <?php foreach ($domains as $domain): ?>
                                        <option value="<?php echo htmlspecialchars($domain['domain_name']); ?>">
                                            <?php echo htmlspecialchars($domain['domain_name']); ?>
                                        </option>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </select>
                                <small class="form-text text-muted">Choose the domain</small>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="destination_email" class="form-label">Destination Email Address</label>
                        <input type="email" class="form-control" id="destination_email" name="destination_email" required placeholder="user@example.com">
                        <div class="form-text">To forward to multiple addresses, add additional forwarders with the same source email</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">Create Forwarder</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Email Account Modal -->
<div class="modal fade" id="editEmailModal" tabindex="-1" aria-labelledby="editEmailModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="action" value="update_email_account">
                <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                <input type="hidden" name="email_id" id="edit_email_id">
                <div class="modal-header">
                    <h5 class="modal-title" id="editEmailModalLabel">Edit Email Account</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="edit_email_address" class="form-label">Email Address</label>
                        <input type="email" class="form-control" id="edit_email_address" readonly>
                    </div>
                    <div class="mb-3">
                        <label for="edit_password" class="form-label">
                            <span id="edit_password_label_text">New Password (leave blank to keep current)</span>
                            <span id="edit_password_required_marker" class="text-danger d-none" aria-hidden="true">*</span>
                        </label>
                        <div class="input-group">
                            <input type="password" class="form-control" id="edit_password" name="password" minlength="8" placeholder="Enter new password or leave blank">
                            <button type="button" class="btn btn-outline-secondary" id="toggleEditPassword" title="Show/Hide Password">
                                <i class="fa fa-eye" id="toggleEditPasswordIcon"></i>
                            </button>
                            <button type="button" class="btn btn-outline-primary" id="generateEditPassword" title="Generate Password">
                                <i class="fa fa-magic"></i>
                            </button>
                            <button type="button" class="btn btn-outline-secondary" id="copyEditPassword" title="Copy to Clipboard" style="display: none;">
                                <i class="fa fa-copy"></i>
                            </button>
                        </div>
                        <div class="form-text">
                            <span id="edit_password_helper_text">Leave blank to keep current password. Minimum 8 characters if changing.</span>
                            <span id="editPasswordStrength" class="badge bg-secondary ms-2" style="display: none;"></span>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="edit_quota_mb" class="form-label">Quota (MB)</label>
                        <input type="number" class="form-control" id="edit_quota_mb" name="quota_mb" min="10" max="20480">
                    </div>
                    <div class="mb-3">
                        <label for="edit_active" class="form-label">Status</label>
                        <select class="form-select" id="edit_active" name="active">
                            <option value="1">Enabled</option>
                            <option value="0">Disabled</option>
                        </select>
                    </div>

                    <?php if ($bichon_configured): ?>
                    <hr>
                    <div class="mb-2">
                        <label class="form-label mb-1">Email Archival</label>
                        <div id="edit_archival_status" class="mb-2"></div>
                        <div class="btn-group" role="group" aria-label="Archival on/off">
                            <input type="radio" class="btn-check" name="archival_action" id="edit_archival_off" value="off">
                            <label class="btn btn-outline-secondary btn-sm" for="edit_archival_off">Disabled</label>
                            <input type="radio" class="btn-check" name="archival_action" id="edit_archival_on"  value="on">
                            <label class="btn btn-outline-success btn-sm"   for="edit_archival_on">Enabled</label>
                        </div>
                        <div class="form-text mt-2" id="edit_archival_hint"></div>
                    </div>
                    <?php endif; ?>
                </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="edit_email_submit">Update Account</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modals -->
<div class="modal fade" id="deleteEmailModal" tabindex="-1" aria-labelledby="deleteEmailModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="action" value="delete_email_account">
                <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                <input type="hidden" name="email_id" id="delete_email_id">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteEmailModalLabel">Delete Email Account</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to delete the email account <strong id="delete_email_address"></strong>?</p>
                    <p class="text-danger"><small>This action cannot be undone.</small></p>
                </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">Delete Account</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Enable Archival Modal -->
<div class="modal fade" id="enableArchivalModal" tabindex="-1" aria-labelledby="enableArchivalModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="enableArchivalModalLabel">Enable Email Archival</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="enableArchivalEmailId">
                <div class="mb-3">
                    <label class="form-label">Email Address</label>
                    <div class="form-control-plaintext"><strong id="enableArchivalEmailDisplay"></strong></div>
                </div>
                <div class="mb-3" id="enableArchivalBichonPwRow">
                    <label for="enableArchivalBichonPassword" class="form-label">Archive login password <span class="text-muted small">(optional &mdash; used to view your archive)</span></label>
                    <div class="input-group">
                        <input type="password" class="form-control" id="enableArchivalBichonPassword" placeholder="Set archive login password (optional)" autocomplete="new-password">
                        <button type="button" class="btn btn-outline-secondary" id="toggleEnableArchivalBichonPassword" title="Show/Hide Password">
                            <i class="fa fa-eye" id="toggleEnableArchivalBichonPasswordIcon"></i>
                        </button>
                    </div>
                </div>
                <div class="alert alert-info">
                    <i class="fa fa-info-circle"></i>
                    Archived mail is delivered to the archive automatically &mdash; no mailbox password needed. The archive login password is what you use to view your archive at the link below; it's stored only by the archive itself.
                </div>
                <div id="enableArchivalError" class="alert alert-danger d-none"></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-success" id="enableArchivalSubmit">
                    <i class="fa fa-archive"></i> Enable Archival
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Reset Archive Password Modal -->
<div class="modal fade" id="resetArchivePasswordModal" tabindex="-1" aria-labelledby="resetArchivePasswordModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="resetArchivePasswordModalLabel">Reset Archive Login Password</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="resetArchivePwEmailId">
                <div class="mb-3">
                    <label class="form-label">Email Address</label>
                    <div class="form-control-plaintext"><strong id="resetArchivePwEmailDisplay"></strong></div>
                </div>
                <div class="mb-3">
                    <label for="resetArchivePwNew" class="form-label">New archive password</label>
                    <div class="input-group">
                        <input type="password" class="form-control" id="resetArchivePwNew" placeholder="Enter a new archive password" autocomplete="new-password">
                        <button type="button" class="btn btn-outline-secondary" id="toggleResetArchivePwNew" title="Show/Hide Password">
                            <i class="fa fa-eye" id="toggleResetArchivePwNewIcon"></i>
                        </button>
                    </div>
                </div>
                <div class="mb-3">
                    <label for="resetArchivePwConfirm" class="form-label">Confirm new password</label>
                    <input type="password" class="form-control" id="resetArchivePwConfirm" placeholder="Re-enter new archive password" autocomplete="new-password">
                </div>
                <div class="alert alert-info">
                    <i class="fa fa-info-circle"></i>
                    This only changes the password you use to view your archive. It does not change your mailbox / IMAP password.
                </div>
                <div id="resetArchivePwError" class="alert alert-danger d-none"></div>
                <div id="resetArchivePwSuccess" class="alert alert-success d-none"></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" id="resetArchivePwSubmit">
                    <i class="fa fa-key"></i> Update password
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Import Existing Mail Modal -->
<div class="modal fade" id="importArchiveModal" tabindex="-1" aria-labelledby="importArchiveModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="importArchiveModalLabel">Import Existing Mail</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="importArchiveEmailId">
                <div class="mb-3">
                    <label class="form-label">Email Address</label>
                    <div class="form-control-plaintext"><strong id="importArchiveEmailDisplay"></strong></div>
                </div>
                <div class="mb-3">
                    <label for="importArchiveMailboxPassword" class="form-label">Mailbox password</label>
                    <div class="input-group">
                        <input type="password" class="form-control" id="importArchiveMailboxPassword" placeholder="Current mailbox (email) password" autocomplete="off">
                        <button type="button" class="btn btn-outline-secondary" id="toggleImportArchiveMailboxPassword" title="Show/Hide Password">
                            <i class="fa fa-eye" id="toggleImportArchiveMailboxPasswordIcon"></i>
                        </button>
                    </div>
                    <div class="form-text">
                        Forgot it? <a href="#" id="importArchiveResetLink">Reset the mailbox password first</a>.
                    </div>
                </div>
                <div class="alert alert-info">
                    <i class="fa fa-info-circle"></i>
                    This imports your existing mail (including the Sent folder) into the archive and
                    switches this mailbox to the full-archive tier. New mail continues to be archived
                    automatically. Your mailbox password is sent only to the archive server and is never stored by the panel.
                </div>
                <div id="importArchiveError" class="alert alert-danger d-none"></div>
                <div id="importArchiveSuccess" class="alert alert-success d-none"></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-info" id="importArchiveSubmit">
                    <i class="fa fa-download"></i> <span id="importArchiveSubmitLabel">Import existing mail</span>
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Disable Archival Modal -->
<div class="modal fade" id="disableArchivalModal" tabindex="-1" aria-labelledby="disableArchivalModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="disableArchivalModalLabel">Disable Email Archival</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="disableArchivalEmailId">
                <div class="mb-3">
                    <label class="form-label">Email Address</label>
                    <div class="form-control-plaintext"><strong id="disableArchivalEmailDisplay"></strong></div>
                </div>
                <p>Are you sure you want to disable archival for <strong id="disableArchivalEmailConfirm"></strong>?</p>
                <?php if (AUTH_USER === 'root'): ?>
                <div class="form-check mb-2">
                    <input class="form-check-input" type="checkbox" id="disableArchivalPurgeRemote" checked>
                    <label class="form-check-label" for="disableArchivalPurgeRemote">
                        Also delete all archived data from Bichon (cannot be undone)
                    </label>
                </div>
                <?php else: ?>
                <input type="hidden" id="disableArchivalPurgeRemote" value="on">
                <?php endif; ?>
                <div id="disableArchivalError" class="alert alert-danger d-none"></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-danger" id="disableArchivalSubmit">
                    <i class="fa fa-times"></i> Disable Archival
                </button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="deleteForwarderModal" tabindex="-1" aria-labelledby="deleteForwarderModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="action" value="delete_forwarder">
                <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                <input type="hidden" name="forwarder_id" id="delete_forwarder_id">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteForwarderModalLabel">Delete Email Forwarder</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to delete the email forwarder destination <strong id="delete_forwarder_email"></strong>?</p>
                    <p class="text-muted small">Note: If this is the only destination for the forwarder, the entire forwarder will be deleted.</p>
                </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">Delete Forwarder</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="deleteAliasModal" tabindex="-1" aria-labelledby="deleteAliasModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="action" value="delete_alias">
                <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                <input type="hidden" name="alias_id" id="delete_alias_id">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteAliasModalLabel">Delete Email Alias</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to delete the email alias <strong id="delete_alias_email"></strong>?</p>
                </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">Delete Alias</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Email Statistics Modal -->
<div class="modal fade" id="emailStatsModal" tabindex="-1" aria-labelledby="emailStatsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="emailStatsModalLabel">Email Statistics</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="statsLoading" class="text-center">
                    <div class="spinner-border" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-2">Loading email statistics...</p>
                </div>
                
                <div id="statsContent" style="display: none;">
                    <div class="row mb-4">
                        <div class="col-md-3">
                            <div class="card text-center">
                                <div class="card-body">
                                    <h4 class="text-primary" id="totalIn">0</h4>
                                    <p class="text-muted mb-0">Incoming Emails</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card text-center">
                                <div class="card-body">
                                    <h4 class="text-success" id="totalOut">0</h4>
                                    <p class="text-muted mb-0">Outgoing Emails</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card text-center">
                                <div class="card-body">
                                    <h4 class="text-info" id="totalEmails">0</h4>
                                    <p class="text-muted mb-0">Total Emails</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card text-center">
                                <div class="card-body">
                                    <h4 class="text-warning" id="activeDays">0</h4>
                                    <p class="text-muted mb-0">Active Days</p>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-header">
                                    <h6 class="mb-0">Daily Averages</h6>
                                </div>
                                <div class="card-body">
                                    <p><strong>Incoming:</strong> <span id="avgIn">0</span> emails/day</p>
                                    <p><strong>Outgoing:</strong> <span id="avgOut">0</span> emails/day</p>
                                    <p><strong>Last Activity:</strong> <span id="lastActivity">Never</span></p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-header">
                                    <h6 class="mb-0">Recent Activity</h6>
                                </div>
                                <div class="card-body">
                                    <div id="recentActivity">
                                        <p class="text-muted">No recent activity</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-header">
                            <h6 class="mb-0">Daily Statistics (Last 30 Days)</h6>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-sm">
                                    <thead>
                                        <tr>
                                            <th>Date</th>
                                            <th>Incoming</th>
                                            <th>Outgoing</th>
                                            <th>Total</th>
                                        </tr>
                                    </thead>
                                    <tbody id="dailyStatsTable">
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div id="statsError" style="display: none;">
                    <div class="alert alert-danger">
                        <i class="fa fa-exclamation-triangle"></i>
                        <strong>Error loading statistics</strong>
                        <p id="statsErrorMessage" class="mb-0"></p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- DKIM Management Modal -->
<div class="modal fade" id="dkimModal" tabindex="-1" aria-labelledby="dkimModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="dkimModalLabel">DKIM Management</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="dkimLoading" class="text-center">
                    <div class="spinner-border" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-2">Loading DKIM information...</p>
                </div>
                
                <div id="dkimContent" style="display: none;">
                    <div class="alert alert-info">
                        <i class="fa fa-info-circle"></i>
                        <strong>DKIM Records</strong> - These records have been automatically added to your domain's DNS configuration.
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <h6>DKIM Information</h6>
                            <table class="table table-sm">
                                <tr>
                                    <td><strong>Domain:</strong></td>
                                    <td id="dkim_domain"></td>
                                </tr>
                                <tr>
                                    <td><strong>Selector:</strong></td>
                                    <td id="dkim_selector"></td>
                                </tr>
                                <tr>
                                    <td><strong>Status:</strong></td>
                                    <td id="dkim_status"></td>
                                </tr>
                            </table>
                            <div class="mt-3">
                                <button type="button" class="btn btn-warning" onclick="rotateDkimRecords()">
                                    <i class="fa fa-refresh"></i> Rotate DKIM Keys
                                </button>
                                <small class="d-block mt-2 text-muted">Best practice: Rotate DKIM keys twice a year</small>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <h6>DNS Record</h6>
                            <div class="form-group">
                                <label for="dkim_dns_record" class="form-label">TXT Record</label>
                                <textarea class="form-control" id="dkim_dns_record" rows="4" readonly></textarea>
                                <small class="form-text text-muted">This record has been automatically added to your domain's DNS configuration.</small>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row mt-3">
                        <div class="col-md-12">
                            <h6>Benefits</h6>
                            <ul>
                                <li><strong>Email Authentication:</strong> DKIM helps verify that emails are genuinely from your domain</li>
                                <li><strong>Improved Deliverability:</strong> Reduces the chance of emails being marked as spam</li>
                                <li><strong>Security:</strong> Protects against email spoofing and phishing attacks</li>
                                <li><strong>Automatic Setup:</strong> DNS records are automatically configured for you</li>
                            </ul>
                        </div>
                    </div>
                </div>
                
                <div id="dkimError" style="display: none;">
                    <div class="alert alert-danger">
                        <i class="fa fa-exclamation-triangle"></i>
                        <strong>Error loading DKIM information</strong>
                        <p id="dkimErrorMessage" class="mb-0"></p>
                    </div>
                </div>
                
                <div id="dkimNoRecords" style="display: none;">
                    <div class="alert alert-warning">
                        <i class="fa fa-exclamation-triangle"></i>
                        <strong>No DKIM records found</strong>
                        <p class="mb-3">DKIM records have not been created for this domain yet. This may happen if the domain was created before the timing fix was implemented.</p>
                        <div class="btn-group" role="group">
                            <button type="button" class="btn btn-primary" onclick="createDkimRecords()">
                                <i class="fa fa-plus"></i> Create DKIM Records
                            </button>
                            <button type="button" class="btn btn-warning" onclick="retryDkimCreation()">
                                <i class="fa fa-refresh"></i> Retry DKIM Creation
                            </button>
                        </div>
                        <small class="form-text text-muted mt-2">Use "Retry DKIM Creation" if the domain was created recently and DKIM creation failed due to timing issues.</small>
                    </div>
                </div>
            </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="createDkimBtn" style="display: none;" onclick="createDkimRecords()">
                    <i class="fa fa-plus"></i> Create DKIM Records
                </button>
            </div>
        </div>
    </div>
</div>

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

// Render-time flag: is the viewer the root admin? Used to gate copy that
// reveals admin-only implementation details (e.g. archive retention window).
const WHP_IS_ROOT = <?php echo AUTH_USER === 'root' ? 'true' : 'false'; ?>;

// JavaScript functions for modal interactions

// Email import form handling
<?php if (AUTH_USER === 'root'): ?>
document.addEventListener('DOMContentLoaded', function() {
    const importForm = document.getElementById('importEmailForm');
    const importButton = document.getElementById('importButton');
    
    if (importForm) {
        importForm.addEventListener('submit', function(e) {
            const domain = document.getElementById('import_domain').value;
            if (!domain) {
                e.preventDefault();
                alert('Please select a domain to import');
                return;
            }
            
            // Update button to show loading state
            importButton.disabled = true;
            importButton.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Importing...';
        });
    }
});
<?php endif; ?>

function editEmailAccount(id, email, quota, active, archivalState, archivalRemaining, archivalMax) {
    document.getElementById('edit_email_id').value = id;
    document.getElementById('edit_email_address').value = email;
    document.getElementById('edit_quota_mb').value = quota;
    document.getElementById('edit_active').value = active ? '1' : '0';
    populateEditArchivalSection(id, email, archivalState || 'off', archivalRemaining || 0, archivalMax || 0);

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

// Drives the Email Archival block inside the edit modal. The radio reflects
// the desired final state (Disabled or Enabled). When the user moves it from
// Disabled -> Enabled (or while a paused row is being saved with a new
// password), the hint reminds them that the password field below is required
// and serves as both the new mailbox password and the archive login. Slot
// counts come from the *mailbox owner's* plan (passed in by the per-row
// foreach), not the viewing user's — so root managing customer mailboxes
// sees the customer's seat numbers.
function populateEditArchivalSection(id, email, state, archivalRemaining, archivalMax) {
    const statusEl = document.getElementById('edit_archival_status');
    const hintEl   = document.getElementById('edit_archival_hint');
    const offRadio = document.getElementById('edit_archival_off');
    const onRadio  = document.getElementById('edit_archival_on');
    const offLabel = document.querySelector('label[for="edit_archival_off"]');
    const onLabel  = document.querySelector('label[for="edit_archival_on"]');
    const passInput = document.getElementById('edit_password');
    if (!statusEl || !offRadio || !onRadio) return; // Bichon isn't configured

    function badge(cls, iconClass, text) {
        statusEl.textContent = '';
        const span = document.createElement('span');
        span.className = 'badge ' + cls;
        if (iconClass) {
            const icon = document.createElement('i');
            icon.className = 'fa ' + iconClass;
            span.appendChild(icon);
            span.appendChild(document.createTextNode(' '));
        }
        span.appendChild(document.createTextNode(text));
        statusEl.appendChild(span);
    }

    // Initial state: radio reflects current archival state. Enable disabled
    // when the user has no remaining seats (and isn't already on).
    const startedEnabled = (state === 'archiving' || state === 'paused');
    offRadio.checked = !startedEnabled;
    onRadio.checked  = startedEnabled;
    onRadio.disabled = false;

    if (state === 'archiving') {
        badge('bg-success', 'fa-archive', 'Archiving');
    } else if (state === 'paused') {
        badge('bg-warning text-dark', 'fa-pause', 'Paused');
    } else {
        badge('bg-secondary', '', 'Off');
        if (archivalMax === 0) {
            onRadio.disabled = true;
        } else if (archivalRemaining <= 0) {
            onRadio.disabled = true;
        }
    }

    // Refs for the password-required UI swap.
    const labelTextEl  = document.getElementById('edit_password_label_text');
    const requiredMark = document.getElementById('edit_password_required_marker');
    const helperEl     = document.getElementById('edit_password_helper_text');
    const submitBtn    = document.getElementById('edit_email_submit');

    function refreshHint() {
        const wantOn  = onRadio.checked;
        const wantOff = offRadio.checked;
        // passwordRequired = the chosen action requires a non-empty new password.
        // Push/journaling model: enabling archival from Off needs NO password
        // (ingest-only NoSync account). Only resuming a paused IMAP-era account
        // still needs a fresh IMAP credential.
        let passwordRequired = false;

        if (state === 'paused' && wantOn) {
            hintEl.textContent = 'Archival is currently paused. Set a new password below to re-supply the IMAP credential and resume.';
            passwordRequired = true;
        } else if (state === 'off' && wantOn) {
            if (archivalMax === 0) {
                hintEl.textContent = 'This user has no archival slots in their plan.';
            } else if (archivalRemaining <= 0) {
                hintEl.textContent = 'All ' + archivalMax + ' archival slots are in use — disable one before enabling another.';
            } else {
                hintEl.textContent = 'Archived mail is delivered automatically — no mailbox password needed. ' + archivalRemaining + ' of ' + archivalMax + ' slots remaining.';
            }
        } else if (state === 'archiving' && wantOff) {
            // 14-day retention is an admin-only implementation detail.
            hintEl.textContent = WHP_IS_ROOT
                ? 'Archive will be retained for 14 days in case this is undone.'
                : '';
        } else if (state === 'paused' && wantOff) {
            hintEl.textContent = WHP_IS_ROOT
                ? 'Archive will be retained for 14 days. The slot is released immediately.'
                : '';
        } else if (state === 'archiving' && wantOn) {
            hintEl.textContent = 'Use the key icon on the row to change the archive login password independently of the mailbox password.';
        } else {
            hintEl.textContent = '';
        }

        // Apply the required state to the password field + asterisk + helper.
        if (passInput) {
            if (passwordRequired) {
                passInput.required = true;
                passInput.placeholder = 'Required to resume archival';
                if (labelTextEl)  labelTextEl.textContent = 'New Password';
                if (requiredMark) requiredMark.classList.remove('d-none');
                if (helperEl) {
                    helperEl.textContent = 'Required — at least 8 characters. Re-supplies the IMAP credential to resume archival.';
                }
            } else {
                passInput.required = false;
                passInput.placeholder = 'Enter new password or leave blank';
                if (labelTextEl)  labelTextEl.textContent = 'New Password (leave blank to keep current)';
                if (requiredMark) requiredMark.classList.add('d-none');
                if (helperEl) {
                    helperEl.textContent = 'Leave blank to keep current password. Minimum 8 characters if changing.';
                }
            }
        }
        refreshSubmitState();
    }

    function refreshSubmitState() {
        if (!submitBtn || !passInput) return;
        // Disable submit only when the password is required (because of the
        // archival transition) but missing/too-short. In all other cases let
        // the form submit through; the existing minlength="8" attribute also
        // blocks too-short non-empty passwords on its own.
        const required = passInput.required;
        const len = (passInput.value || '').length;
        if (required && len < 8) {
            submitBtn.disabled = true;
            submitBtn.title = 'Set a new password (8+ chars) to enable or resume archival';
        } else {
            submitBtn.disabled = false;
            submitBtn.removeAttribute('title');
        }
    }

    if (passInput) {
        passInput.addEventListener('input', refreshSubmitState);
    }
    offRadio.onchange = refreshHint;
    onRadio.onchange  = refreshHint;
    refreshHint();
}

function deleteEmailAccount(id, email) {
    document.getElementById('delete_email_id').value = id;
    document.getElementById('delete_email_address').textContent = email;
    
    new bootstrap.Modal(document.getElementById('deleteEmailModal')).show();
}

function deleteForwarder(id, email) {
    document.getElementById('delete_forwarder_id').value = id;
    document.getElementById('delete_forwarder_email').textContent = email;
    
    new bootstrap.Modal(document.getElementById('deleteForwarderModal')).show();
}

function deleteForwarderDestination(id, source, destination) {
    document.getElementById('delete_forwarder_id').value = id;
    document.getElementById('delete_forwarder_email').textContent = source + ' → ' + destination;
    
    new bootstrap.Modal(document.getElementById('deleteForwarderModal')).show();
}

function deleteAlias(id, email) {
    document.getElementById('delete_alias_id').value = id;
    document.getElementById('delete_alias_email').textContent = email;
    
    new bootstrap.Modal(document.getElementById('deleteAliasModal')).show();
}

function showEmailStats(email) {
    // Show modal and loading state
    const modal = new bootstrap.Modal(document.getElementById('emailStatsModal'));
    modal.show();
    
    document.getElementById('statsLoading').style.display = 'block';
    document.getElementById('statsContent').style.display = 'none';
    document.getElementById('statsError').style.display = 'none';
    
    // Update modal title
    document.getElementById('emailStatsModalLabel').textContent = 'Email Statistics - ' + email;
    
    // Fetch statistics
    fetch('api/email-management.php?action=get_email_stats&email=' + encodeURIComponent(email))
        .then(response => response.json())
        .then(data => {
            document.getElementById('statsLoading').style.display = 'none';
            
            if (data.status === '0') {
                // Display statistics
                const summary = data.summary;
                const dailyStats = data.daily_stats;
                
                // Update summary cards
                document.getElementById('totalIn').textContent = summary.total_in;
                document.getElementById('totalOut').textContent = summary.total_out;
                document.getElementById('totalEmails').textContent = summary.total_emails;
                document.getElementById('activeDays').textContent = summary.days_with_activity;
                
                // Update averages
                document.getElementById('avgIn').textContent = summary.avg_in_per_day;
                document.getElementById('avgOut').textContent = summary.avg_out_per_day;
                document.getElementById('lastActivity').textContent = summary.last_activity || 'Never';
                
                // Update recent activity
                const recentActivityDiv = document.getElementById('recentActivity');
                if (summary.last_activity) {
                    recentActivityDiv.innerHTML = `
                        <p><strong>Last Activity:</strong> ${summary.last_activity}</p>
                        <p><strong>Active Days:</strong> ${summary.days_with_activity} out of ${Object.keys(dailyStats).length}</p>
                    `;
                } else {
                    recentActivityDiv.innerHTML = '<p class="text-muted">No recent activity</p>';
                }
                
                // Update daily stats table
                const tableBody = document.getElementById('dailyStatsTable');
                tableBody.innerHTML = '';
                
                // Sort dates in descending order
                const sortedDates = Object.keys(dailyStats).sort().reverse();
                
                sortedDates.forEach(date => {
                    const dayStats = dailyStats[date];
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${formatDate(date)}</td>
                        <td>${dayStats.in || 0}</td>
                        <td>${dayStats.out || 0}</td>
                        <td>${(dayStats.in || 0) + (dayStats.out || 0)}</td>
                    `;
                    tableBody.appendChild(row);
                });
                
                document.getElementById('statsContent').style.display = 'block';
            } else {
                // Show error
                document.getElementById('statsErrorMessage').textContent = data.msg || 'Failed to load statistics';
                document.getElementById('statsError').style.display = 'block';
            }
        })
        .catch(error => {
            document.getElementById('statsLoading').style.display = 'none';
            document.getElementById('statsErrorMessage').textContent = 'Network error: ' + error.message;
            document.getElementById('statsError').style.display = 'block';
        });
}

function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('en-US', { 
        weekday: 'short', 
        year: 'numeric', 
        month: 'short', 
        day: 'numeric' 
    });
}

// Auto-generate email address when domain is selected
document.getElementById('domain_name').addEventListener('change', function() {
    const localPart = document.getElementById('email_local').value;
    const domain = this.value;
    if (localPart && domain) {
        // Update the form to use the full email address
        const fullEmail = localPart + '@' + domain;
        // We'll handle this in the form submission
    }
});

// Handle form submission for email creation
document.querySelector('#createEmailModal form').addEventListener('submit', function(e) {
    const localPart = document.getElementById('email_local').value;
    const domain = document.getElementById('domain_name').value;
    
    if (localPart && domain) {
        // Create a hidden input for the full email address
        const emailInput = document.createElement('input');
        emailInput.type = 'hidden';
        emailInput.name = 'email_address';
        emailInput.value = localPart + '@' + domain;
        this.appendChild(emailInput);
    }
    
    <?php if (AUTH_USER === 'root'): ?>
    // Ensure target_user is set for root users
    const targetUser = document.getElementById('target_user').value;
    if (!targetUser) {
        e.preventDefault();
        alert('Please select a user account for this email.');
        return false;
    }
    
    // Update the username field for form processing
    const usernameInput = document.createElement('input');
    usernameInput.type = 'hidden';
    usernameInput.name = 'username';
    usernameInput.value = targetUser;
    this.appendChild(usernameInput);
    <?php endif; ?>
});

// DKIM Management Functions
let currentDkimDomain = '';

// Realtime DKIM domain search. The full domain list is rendered server-side
// into an array; the input filters it client-side. Status checks only fire
// when the user clicks "Check" on a row — auto-checking every domain on
// load fanned out one upstream Poste.io call per domain and saturated PHP-FPM
// workers for root accounts with hundreds of domains.
document.addEventListener('DOMContentLoaded', initDkimSearch);

const DKIM_DOMAINS = <?php echo json_encode(AUTH_USER === 'root' ? $whp_domains : $domains, JSON_HEX_TAG | JSON_HEX_AMP); ?>;
const DKIM_MAX_RESULTS = 25;

function initDkimSearch() {
    const input      = document.getElementById('dkimSearch');
    const table      = document.getElementById('dkimTable');
    const tableBody  = document.getElementById('dkimDomainsTable');
    const emptyState = document.getElementById('dkimEmptyState');
    if (!input || !table || !tableBody || !emptyState) return;

    if (!DKIM_DOMAINS.length) {
        emptyState.textContent = 'No domains available — add domains in the Domains section to manage DKIM records.';
        input.disabled = true;
        return;
    }

    input.addEventListener('input', () => {
        const q = input.value.trim().toLowerCase();
        if (!q) {
            table.style.display = 'none';
            emptyState.style.display = '';
            emptyState.textContent = 'Start typing a domain name above to check or manage DKIM records.';
            tableBody.replaceChildren();
            return;
        }
        const matches = DKIM_DOMAINS
            .filter(d => d.domain_name.toLowerCase().includes(q))
            .slice(0, DKIM_MAX_RESULTS);

        if (!matches.length) {
            table.style.display = 'none';
            emptyState.style.display = '';
            emptyState.textContent = 'No domains match "' + q + '".';
            tableBody.replaceChildren();
            return;
        }

        emptyState.style.display = 'none';
        table.style.display = '';
        renderDkimRows(matches, tableBody);
    });
}

function makeIconButton(iconClass, label, btnClass, domain, onClick) {
    const btn = document.createElement('button');
    btn.type = 'button';
    btn.className = 'btn btn-sm ' + btnClass;
    btn.title = label;
    btn.dataset.domain = domain;
    const icon = document.createElement('i');
    icon.className = iconClass;
    btn.append(icon, ' ' + label);
    btn.addEventListener('click', onClick);
    return btn;
}

function renderDkimRows(domains, tableBody) {
    tableBody.replaceChildren();
    domains.forEach(domain => {
        const name = String(domain.domain_name);
        const row = document.createElement('tr');

        const nameCell = document.createElement('td');
        const strong = document.createElement('strong');
        strong.textContent = name;
        nameCell.append(strong);

        const statusCell = document.createElement('td');
        const statusBadge = document.createElement('span');
        statusBadge.className = 'badge bg-secondary';
        statusBadge.textContent = 'Not checked';
        statusCell.append(statusBadge);

        const dnsCell = document.createElement('td');
        const dnsSpan = document.createElement('span');
        dnsSpan.className = 'text-muted';
        dnsSpan.textContent = '—';
        dnsCell.append(dnsSpan);

        const actionsCell = document.createElement('td');
        const checkBtn = makeIconButton('fa fa-search', 'Check', 'btn-outline-primary', name, function() {
            this.disabled = true;
            const checkingBadge = document.createElement('span');
            checkingBadge.className = 'badge bg-secondary';
            checkingBadge.textContent = 'Checking…';
            statusCell.replaceChildren(checkingBadge);
            checkDkimStatus(name, row);
        });
        const manageBtn = makeIconButton('fa fa-key', 'Manage', 'btn-outline-warning', name, function() {
            manageDkim(name);
        });
        actionsCell.append(checkBtn, ' ', manageBtn);

        row.append(nameCell, statusCell, dnsCell, actionsCell);
        tableBody.append(row);
    });
}

function checkDkimStatus(domainName, row) {
    fetch('api/email-management.php?action=get_dkim&domain=' + encodeURIComponent(domainName))
        .then(response => response.json())
        .then(data => {
            const statusCell = row.cells[1];
            const dnsCell = row.cells[2];
            
            if (data.status === '0') {
                // DKIM exists
                statusCell.innerHTML = '<span class="badge bg-success">Active</span>';
                dnsCell.innerHTML = `
                    <small class="text-success">
                        <i class="fa fa-check"></i> DNS record configured
                    </small>
                `;
            } else if (data.status === '1' && data.msg.includes('not found')) {
                // No DKIM records
                statusCell.innerHTML = '<span class="badge bg-warning">Not Configured</span>';
                dnsCell.innerHTML = `
                    <small class="text-muted">
                        <i class="fa fa-times"></i> No DNS record
                    </small>
                `;
            } else {
                // Error
                statusCell.innerHTML = '<span class="badge bg-danger">Error</span>';
                dnsCell.innerHTML = `
                    <small class="text-danger">
                        <i class="fa fa-exclamation-triangle"></i> ${data.msg || 'Unknown error'}
                    </small>
                `;
            }
        })
        .catch(error => {
            const statusCell = row.cells[1];
            const dnsCell = row.cells[2];
            statusCell.innerHTML = '<span class="badge bg-danger">Error</span>';
            dnsCell.innerHTML = `
                <small class="text-danger">
                    <i class="fa fa-exclamation-triangle"></i> Network error
                </small>
            `;
        });
}

function manageDkim(domainName) {
    currentDkimDomain = domainName;
    
    // Show modal and loading state
    const modal = new bootstrap.Modal(document.getElementById('dkimModal'));
    modal.show();
    
    document.getElementById('dkimModalLabel').textContent = 'DKIM Management - ' + domainName;
    document.getElementById('dkimLoading').style.display = 'block';
    document.getElementById('dkimContent').style.display = 'none';
    document.getElementById('dkimError').style.display = 'none';
    document.getElementById('dkimNoRecords').style.display = 'none';
    document.getElementById('createDkimBtn').style.display = 'none';
    
    // Fetch DKIM records
    fetch('api/email-management.php?action=get_dkim&domain=' + encodeURIComponent(domainName))
        .then(response => response.json())
        .then(data => {
            document.getElementById('dkimLoading').style.display = 'none';
            
            if (data.status === '0') {
                const dkim = data.dkim;
                
                // Populate DKIM information
                document.getElementById('dkim_domain').textContent = domainName;
                document.getElementById('dkim_selector').textContent = dkim.selector;
                document.getElementById('dkim_status').innerHTML = '<span class="badge bg-success">Active</span>';
                
                // Create DNS record using cleaned public key
                const dnsRecord = `${dkim.selector}._domainkey.${domainName} IN TXT ${dkim.dns_record}`;
                document.getElementById('dkim_dns_record').value = dnsRecord;
                
                document.getElementById('dkimContent').style.display = 'block';
            } else if (data.status === '1' && data.msg.includes('not found')) {
                // No DKIM records found
                document.getElementById('dkimNoRecords').style.display = 'block';
                document.getElementById('createDkimBtn').style.display = 'block';
            } else {
                // Error
                document.getElementById('dkimErrorMessage').textContent = data.msg || 'Failed to load DKIM information';
                document.getElementById('dkimError').style.display = 'block';
            }
        })
        .catch(error => {
            document.getElementById('dkimLoading').style.display = 'none';
            document.getElementById('dkimErrorMessage').textContent = 'Network error: ' + error.message;
            document.getElementById('dkimError').style.display = 'block';
        });
}

function createDkimRecords() {
    if (!currentDkimDomain) return;
    
    // Show loading state
    document.getElementById('dkimLoading').style.display = 'block';
    document.getElementById('dkimContent').style.display = 'none';
    document.getElementById('dkimError').style.display = 'none';
    document.getElementById('dkimNoRecords').style.display = 'none';
    document.getElementById('createDkimBtn').style.display = 'none';
    
    // Create DKIM records
    fetch('api/email-management.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-Token': nonce
        },
        body: JSON.stringify({
            action: 'create_dkim',
            domain_name: currentDkimDomain
        })
    })
    .then(response => response.json())
    .then(data => {
        document.getElementById('dkimLoading').style.display = 'none';
        
        if (data.status === '0') {
            // Success - reload DKIM information
            manageDkim(currentDkimDomain);
        } else {
            // Error
            document.getElementById('dkimErrorMessage').textContent = data.msg || 'Failed to create DKIM records';
            document.getElementById('dkimError').style.display = 'block';
        }
    })
    .catch(error => {
        document.getElementById('dkimLoading').style.display = 'none';
        document.getElementById('dkimErrorMessage').textContent = 'Network error: ' + error.message;
        document.getElementById('dkimError').style.display = 'block';
    });
}

function retryDkimCreation() {
    if (!currentDkimDomain) return;
    
    // Show loading state
    document.getElementById('dkimLoading').style.display = 'block';
    document.getElementById('dkimContent').style.display = 'none';
    document.getElementById('dkimError').style.display = 'none';
    document.getElementById('dkimNoRecords').style.display = 'none';
    document.getElementById('createDkimBtn').style.display = 'none';
    
    // Retry DKIM creation with extended retry logic
    fetch('api/email-management.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-Token': nonce
        },
        body: JSON.stringify({
            action: 'retry_dkim',
            domain_name: currentDkimDomain,
            max_retries: 5,
            delay_seconds: 3
        })
    })
    .then(response => response.json())
    .then(data => {
        document.getElementById('dkimLoading').style.display = 'none';
        
        if (data.status === '0') {
            // Success - reload DKIM information
            manageDkim(currentDkimDomain);
        } else {
            // Error
            document.getElementById('dkimErrorMessage').textContent = data.msg || 'Failed to create DKIM records after retries';
            document.getElementById('dkimError').style.display = 'block';
        }
    })
    .catch(error => {
        document.getElementById('dkimLoading').style.display = 'none';
        document.getElementById('dkimErrorMessage').textContent = 'Network error: ' + error.message;
        document.getElementById('dkimError').style.display = 'block';
    });
}

function rotateDkimRecords() {
    if (!currentDkimDomain) {
        alert('No domain selected');
        return;
    }
    
    if (!confirm(`Are you sure you want to rotate the DKIM keys for ${currentDkimDomain}?\n\nThis will:\n1. Delete the existing DKIM records\n2. Generate new DKIM keys\n3. Update the DNS records automatically\n\nNote: Email delivery may be temporarily affected during rotation.`)) {
        return;
    }
    
    // Show loading state
    document.getElementById('dkimLoading').style.display = 'block';
    document.getElementById('dkimContent').style.display = 'none';
    document.getElementById('dkimError').style.display = 'none';
    document.getElementById('dkimNoRecords').style.display = 'none';
    document.getElementById('createDkimBtn').style.display = 'none';
    
    // Update loading message
    const loadingText = document.querySelector('#dkimLoading p');
    if (loadingText) {
        loadingText.textContent = 'Rotating DKIM keys... This may take a moment.';
    }
    
    // Rotate DKIM records
    fetch('api/email-management.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest',
            'X-CSRF-Token': nonce
        },
        body: JSON.stringify({
            action: 'rotate_dkim',
            domain_name: currentDkimDomain,
            csrf_token: nonce
        })
    })
    .then(response => response.json())
    .then(data => {
        document.getElementById('dkimLoading').style.display = 'none';
        
        if (data.status === '0' || data.status === 0) {
            // Success - show success message then reload DKIM information
            const successAlert = document.createElement('div');
            successAlert.className = 'alert alert-success alert-dismissible fade show';
            successAlert.innerHTML = `
                <i class="fa fa-check-circle"></i>
                <strong>Success!</strong> ${data.msg || 'DKIM keys have been rotated successfully.'}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            `;
            
            // Insert the alert at the top of the modal body
            const modalBody = document.querySelector('#dkimModal .modal-body');
            modalBody.insertBefore(successAlert, modalBody.firstChild);
            
            // Reload DKIM information after a short delay
            setTimeout(() => {
                manageDkim(currentDkimDomain);
            }, 1500);
        } else {
            // Error
            document.getElementById('dkimErrorMessage').textContent = data.msg || data.message || 'Failed to rotate DKIM keys';
            document.getElementById('dkimError').style.display = 'block';
        }
    })
    .catch(error => {
        document.getElementById('dkimLoading').style.display = 'none';
        document.getElementById('dkimErrorMessage').textContent = 'Network error: ' + error.message;
        document.getElementById('dkimError').style.display = 'block';
    });
}

// Domain Management Functions
function showDomainDetails(domainName) {
    // Show modal and loading state
    const modal = new bootstrap.Modal(document.getElementById('domainDetailsModal'));
    modal.show();
    
    document.getElementById('domainDetailsModalLabel').textContent = 'Domain Details - ' + domainName;
    document.getElementById('domainDetailsLoading').style.display = 'block';
    document.getElementById('domainDetailsContent').style.display = 'none';
    document.getElementById('domainDetailsError').style.display = 'none';
    
    // Fetch domain details
    fetch('api/email-management.php?action=get_domain&domain=' + encodeURIComponent(domainName))
        .then(response => response.json())
        .then(data => {
            document.getElementById('domainDetailsLoading').style.display = 'none';
            
            if (data.status === '0') {
                const domain = data.domain;
                
                // Populate details
                document.getElementById('detail_name').textContent = domain.name;
                document.getElementById('detail_status').innerHTML = domain.disabled ? 
                    '<span class="badge bg-danger">Disabled</span>' : 
                    '<span class="badge bg-success">Active</span>';
                document.getElementById('detail_created').textContent = formatDate(domain.created);
                document.getElementById('detail_updated').textContent = formatDate(domain.updated);
                document.getElementById('detail_reference_id').textContent = domain.reference_id || 'N/A';
                
                document.getElementById('detail_forwarding').innerHTML = domain.forward ? 
                    'Enabled' + (domain.forward_domain ? ' → ' + domain.forward_domain : '') : 'Disabled';
                document.getElementById('detail_domain_bin').innerHTML = domain.domain_bin ? 
                    'Enabled' + (domain.domain_bin_address ? ' → ' + domain.domain_bin_address : '') : 'Disabled';
                document.getElementById('detail_force_route').innerHTML = domain.force_route ? 
                    'Enabled' + (domain.force_route_host ? ' → ' + domain.force_route_host : '') : 'Disabled';
                document.getElementById('detail_custom_outbound').innerHTML = domain.custom_outbound ? 
                    'Enabled' + (domain.outbound_ip ? ' (IP: ' + domain.outbound_ip + ')' : '') : 'Disabled';
                
                document.getElementById('domainDetailsContent').style.display = 'block';
            } else {
                document.getElementById('domainDetailsErrorMessage').textContent = data.msg || 'Failed to load domain details';
                document.getElementById('domainDetailsError').style.display = 'block';
            }
        })
        .catch(error => {
            document.getElementById('domainDetailsLoading').style.display = 'none';
            document.getElementById('domainDetailsErrorMessage').textContent = 'Network error: ' + error.message;
            document.getElementById('domainDetailsError').style.display = 'block';
        });
}

function editDomain(domainName) {
    // Load domain details and populate form
    fetch('api/email-management.php?action=get_domain&domain=' + encodeURIComponent(domainName))
        .then(response => response.json())
        .then(data => {
            if (data.status === '0') {
                const domain = data.domain;
                
                // Populate form fields
                document.getElementById('edit_domain_name').value = domain.name;
                document.getElementById('edit_name').value = domain.name;
                document.getElementById('edit_reference_id').value = domain.reference_id || '';
                document.getElementById('edit_disabled').checked = domain.disabled;
                document.getElementById('edit_forward').checked = domain.forward;
                document.getElementById('edit_forward_domain').value = domain.forward_domain || '';
                document.getElementById('edit_domain_bin').checked = domain.domain_bin;
                document.getElementById('edit_domain_bin_address').value = domain.domain_bin_address || '';
                document.getElementById('edit_force_route').checked = domain.force_route;
                document.getElementById('edit_force_route_host').value = domain.force_route_host || '';
                document.getElementById('edit_custom_outbound').checked = domain.custom_outbound;
                document.getElementById('edit_outbound_ip').value = domain.outbound_ip || '';
                document.getElementById('edit_outbound_ehlo').value = domain.outbound_ehlo || '';
                
                // Show modal
                const modal = new bootstrap.Modal(document.getElementById('editDomainModal'));
                modal.show();
            } else {
                alert('Failed to load domain details: ' + data.msg);
            }
        })
        .catch(error => {
            alert('Network error: ' + error.message);
        });
}

// Handle domain edit form submission to properly set disabled field
document.addEventListener('DOMContentLoaded', function() {
    const editDomainForm = document.querySelector('#editDomainModal form');
    if (editDomainForm) {
        editDomainForm.addEventListener('submit', function(e) {
            const disabledCheckbox = document.getElementById('edit_disabled');
            const disabledHidden = editDomainForm.querySelector('input[name="disabled"][type="hidden"]');
            
            // Update hidden field value based on checkbox state
            if (disabledCheckbox.checked) {
                disabledHidden.value = '1';
            } else {
                disabledHidden.value = '0';
            }
        });
    }
});

// Handle forwarder form submission
document.querySelector('#createForwardingForm').addEventListener('submit', function(e) {
    const localPart = document.getElementById('source_email_local').value;
    const domain = document.getElementById('source_domain_name').value;
    
    if (localPart && domain) {
        // Create a hidden input for the full source email address
        const sourceEmailInput = document.createElement('input');
        sourceEmailInput.type = 'hidden';
        sourceEmailInput.name = 'source_email';
        sourceEmailInput.value = localPart + '@' + domain;
        this.appendChild(sourceEmailInput);
    }
    
    <?php if (AUTH_USER === 'root'): ?>
    // Ensure target_user is set for root users
    const targetUser = document.getElementById('forwarding_target_user').value;
    if (!targetUser) {
        e.preventDefault();
        alert('Please select a user account for this forwarder.');
        return false;
    }
    <?php endif; ?>
});

<?php if (AUTH_USER === 'root'): ?>
// Update domain dropdown when user is selected (for forwarders)
function updateForwarderUserDomains() {
    const selectedUser = document.getElementById('forwarding_target_user').value;
    const domainSelect = document.getElementById('source_domain_name');
    
    if (!selectedUser) {
        // Clear domain options
        domainSelect.innerHTML = '<option value="">Select Domain</option>';
        return;
    }
    
    // Fetch domains for selected user
    fetch('api/email-management.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-Token': nonce
        },
        body: JSON.stringify({
            action: 'get_user_domains',
            username: selectedUser
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === '0' && data.domains) {
            let options = '<option value="">Select Domain</option>';
            data.domains.forEach(domain => {
                const disabled = !domain.active ? ' disabled' : '';
                options += `<option value="${domain.domain_name}"${disabled}>${domain.domain_name}</option>`;
            });
            domainSelect.innerHTML = options;
        } else {
            domainSelect.innerHTML = '<option value="">No domains available</option>';
            console.error('Failed to load domains:', data.msg);
        }
    })
    .catch(error => {
        console.error('Error fetching domains:', error);
        domainSelect.innerHTML = '<option value="">Error loading domains</option>';
    });
}
<?php endif; ?>



// Domain management for root users
let domainChoices = null;
let targetUserChoices = null;

// Initialize choices.js when modal opens
document.getElementById('createEmailModal').addEventListener('shown.bs.modal', function() {
    // Initialize domain dropdown with choices.js
    if (!domainChoices) {
        domainChoices = new Choices('#domain_name', {
            searchEnabled: true,
            placeholderValue: 'Select a domain...',
            searchPlaceholderValue: 'Type to search domains...',
            noResultsText: 'No domains found',
            noChoicesText: 'No domains available',
            itemSelectText: 'Press to select',
            allowHTML: false
        });
    }
    
    <?php if (AUTH_USER === 'root'): ?>
    // Initialize user dropdown for root users
    if (!targetUserChoices) {
        targetUserChoices = new Choices('#target_user', {
            searchEnabled: true,
            placeholderValue: 'Select a user...',
            searchPlaceholderValue: 'Type to search users...',
            noResultsText: 'No users found',
            noChoicesText: 'No users available',
            itemSelectText: 'Press to select',
            allowHTML: false
        });
    }
    <?php endif; ?>
});

// Clean up choices.js when modal closes
document.getElementById('createEmailModal').addEventListener('hidden.bs.modal', function() {
    if (domainChoices) {
        domainChoices.destroy();
        domainChoices = null;
    }
    if (targetUserChoices) {
        targetUserChoices.destroy();
        targetUserChoices = null;
    }
});

<?php if (AUTH_USER === 'root'): ?>
// Update domain dropdown when user is selected (for root)
function updateUserDomains() {
    const selectedUser = document.getElementById('target_user').value;
    const domainSelect = document.getElementById('domain_name');
    
    if (!selectedUser) {
        // Clear domain options
        if (domainChoices) {
            domainChoices.clearStore();
            domainChoices.setChoices([]);
        }
        return;
    }
    
    // Fetch domains for selected user
    fetch('api/email-management.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-Token': nonce
        },
        body: JSON.stringify({
            action: 'get_user_domains',
            username: selectedUser
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === '0' && data.domains) {
            const domainOptions = data.domains.map(domain => ({
                value: domain.domain_name,
                label: domain.domain_name,
                disabled: !domain.active
            }));
            
            if (domainChoices) {
                domainChoices.clearStore();
                domainChoices.setChoices(domainOptions, 'value', 'label', true);
            }
        } else {
            if (domainChoices) {
                domainChoices.clearStore();
                domainChoices.setChoices([]);
            }
            console.error('Failed to load domains:', data.msg);
        }
    })
    .catch(error => {
        console.error('Error fetching domains:', error);
        if (domainChoices) {
            domainChoices.clearStore();
            domainChoices.setChoices([]);
        }
    });
}
<?php endif; ?>

// Enhanced Password Management Functions
document.addEventListener('DOMContentLoaded', function() {
    // Initialize password functionality
    initializePasswordField('password', 'toggleEmailPassword', 'toggleEmailPasswordIcon', 'generateEmailPassword', 'copyEmailPassword', 'passwordStrength');
    initializePasswordField('edit_password', 'toggleEditPassword', 'toggleEditPasswordIcon', 'generateEditPassword', 'copyEditPassword', 'editPasswordStrength');
    
    // Initialize password length slider
    const lengthSlider = document.getElementById('passwordLength');
    const lengthValue = document.getElementById('passwordLengthValue');
    
    if (lengthSlider && lengthValue) {
        lengthSlider.addEventListener('input', function() {
            lengthValue.textContent = this.value;
        });
    }
});

function initializePasswordField(fieldId, toggleId, iconId, generateId, copyId, strengthId) {
    const passwordField = document.getElementById(fieldId);
    const toggleBtn = document.getElementById(toggleId);
    const toggleIcon = document.getElementById(iconId);
    const generateBtn = document.getElementById(generateId);
    const copyBtn = document.getElementById(copyId);
    const strengthIndicator = document.getElementById(strengthId);
    
    if (!passwordField) return;
    
    // Toggle password visibility
    if (toggleBtn && toggleIcon) {
        toggleBtn.addEventListener('click', function() {
            const isPassword = passwordField.type === 'password';
            passwordField.type = isPassword ? 'text' : 'password';
            toggleIcon.className = isPassword ? 'fa fa-eye-slash' : 'fa fa-eye';
        });
    }
    
    // Generate password
    if (generateBtn) {
        generateBtn.addEventListener('click', function() {
            if (fieldId === 'password') {
                togglePasswordGenerator();
            } else {
                // For edit modal, generate directly
                const password = generateSecurePassword(false);
                passwordField.value = password;
                updatePasswordStrength(password, strengthIndicator);
                showCopyButton(copyBtn);
            }
        });
    }
    
    // Copy to clipboard
    if (copyBtn) {
        copyBtn.addEventListener('click', function() {
            copyToClipboard(passwordField.value, copyBtn);
        });
    }
    
    // Password strength checking
    if (strengthIndicator) {
        passwordField.addEventListener('input', function() {
            const password = this.value;
            if (password.length > 0) {
                updatePasswordStrength(password, strengthIndicator);
                showCopyButton(copyBtn);
            } else {
                strengthIndicator.style.display = 'none';
                if (copyBtn) copyBtn.style.display = 'none';
            }
        });
    }
}

function togglePasswordGenerator() {
    const generator = document.getElementById('passwordGenerator');
    if (generator.style.display === 'none') {
        generator.style.display = 'block';
        generateSecurePassword(); // Generate initial password
    } else {
        generator.style.display = 'none';
    }
}

function generateSecurePassword(updateField = true) {
    const length = document.getElementById('passwordLength')?.value || 16;
    const includeUppercase = document.getElementById('includeUppercase')?.checked ?? true;
    const includeLowercase = document.getElementById('includeLowercase')?.checked ?? true;
    const includeNumbers = document.getElementById('includeNumbers')?.checked ?? true;
    const includeSymbols = document.getElementById('includeSymbols')?.checked ?? true;
    
    let charset = '';
    if (includeUppercase) charset += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    if (includeLowercase) charset += 'abcdefghijklmnopqrstuvwxyz';
    if (includeNumbers) charset += '0123456789';
    if (includeSymbols) charset += '!@#$%^&*()_+-=[]{}|;:,.<>?';
    
    if (charset === '') {
        alert('Please select at least one character type for password generation.');
        return '';
    }
    
    let password = '';
    for (let i = 0; i < length; i++) {
        password += charset.charAt(Math.floor(Math.random() * charset.length));
    }
    
    if (updateField) {
        const passwordField = document.getElementById('password');
        if (passwordField) {
            passwordField.value = password;
            updatePasswordStrength(password, document.getElementById('passwordStrength'));
            showCopyButton(document.getElementById('copyPassword'));
        }
    }
    
    return password;
}

function updatePasswordStrength(password, strengthIndicator) {
    if (!strengthIndicator) return;
    
    let score = 0;
    let feedback = '';
    
    // Length check
    if (password.length >= 8) score += 1;
    if (password.length >= 12) score += 1;
    if (password.length >= 16) score += 1;
    
    // Character variety
    if (/[a-z]/.test(password)) score += 1;
    if (/[A-Z]/.test(password)) score += 1;
    if (/[0-9]/.test(password)) score += 1;
    if (/[^A-Za-z0-9]/.test(password)) score += 1;
    
    // Determine strength
    if (score < 3) {
        strengthIndicator.className = 'badge bg-danger ms-2';
        feedback = 'Weak';
    } else if (score < 5) {
        strengthIndicator.className = 'badge bg-warning ms-2';
        feedback = 'Medium';
    } else if (score < 7) {
        strengthIndicator.className = 'badge bg-success ms-2';
        feedback = 'Strong';
    } else {
        strengthIndicator.className = 'badge bg-primary ms-2';
        feedback = 'Very Strong';
    }
    
    strengthIndicator.textContent = feedback;
    strengthIndicator.style.display = 'inline';
}

function showCopyButton(copyBtn) {
    if (copyBtn) {
        copyBtn.style.display = 'inline-block';
    }
}

function copyToClipboard(text, button) {
    if (!text) return;
    
    navigator.clipboard.writeText(text).then(function() {
        // Visual feedback
        const originalIcon = button.querySelector('i').className;
        const originalTitle = button.title;
        
        button.querySelector('i').className = 'fa fa-check';
        button.title = 'Copied!';
        button.classList.add('btn-success');
        button.classList.remove('btn-outline-secondary');
        
        // Reset after 2 seconds
        setTimeout(function() {
            button.querySelector('i').className = originalIcon;
            button.title = originalTitle;
            button.classList.remove('btn-success');
            button.classList.add('btn-outline-secondary');
        }, 2000);
    }).catch(function(err) {
        // Fallback for older browsers
        const textarea = document.createElement('textarea');
        textarea.value = text;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
        
        // Show success message
        alert('Password copied to clipboard!');
    });
}

// Initialize email accounts pagination
document.addEventListener('DOMContentLoaded', function() {
    const emailTable = document.getElementById('emailAccountsTable');
    if (emailTable) {
        <?php if (AUTH_USER === 'root'): ?>
        new TablePagination({
            tableId: 'emailAccountsTable',
            searchId: 'emailSearchInput',
            paginationId: 'emailPagination',
            infoId: 'emailTableInfo',
            filterSelectId: 'emailUserFilter',
            filterAttribute: 'username',
            itemsPerPage: 25
        });
        <?php else: ?>
        new TablePagination({
            tableId: 'emailAccountsTable',
            searchId: 'emailSearchInput',
            paginationId: 'emailPagination',
            infoId: 'emailTableInfo',
            itemsPerPage: 25
        });
        <?php endif; ?>
    }
});

// ============================================================
// Bichon Email Archival
// ============================================================
function showEnableArchivalModal(id, email) {
    document.getElementById('enableArchivalEmailId').value = id;
    document.getElementById('enableArchivalEmailDisplay').textContent = email;
    var bichonPwField = document.getElementById('enableArchivalBichonPassword');
    if (bichonPwField) bichonPwField.value = '';
    document.getElementById('enableArchivalError').classList.add('d-none');
    bootstrap.Modal.getOrCreateInstance(document.getElementById('enableArchivalModal')).show();
}

function showResetArchivePasswordModal(id, email) {
    document.getElementById('resetArchivePwEmailId').value = id;
    document.getElementById('resetArchivePwEmailDisplay').textContent = email;
    document.getElementById('resetArchivePwNew').value = '';
    document.getElementById('resetArchivePwConfirm').value = '';
    document.getElementById('resetArchivePwError').classList.add('d-none');
    document.getElementById('resetArchivePwSuccess').classList.add('d-none');
    bootstrap.Modal.getOrCreateInstance(document.getElementById('resetArchivePasswordModal')).show();
}

function showDisableArchivalModal(id, email) {
    document.getElementById('disableArchivalEmailId').value = id;
    document.getElementById('disableArchivalEmailDisplay').textContent = email;
    var confirmEl = document.getElementById('disableArchivalEmailConfirm');
    if (confirmEl) confirmEl.textContent = email;
    var purgeEl = document.getElementById('disableArchivalPurgeRemote');
    if (purgeEl && typeof purgeEl.checked === 'boolean') purgeEl.checked = true;
    document.getElementById('disableArchivalError').classList.add('d-none');
    bootstrap.Modal.getOrCreateInstance(document.getElementById('disableArchivalModal')).show();
}

// Cache the edit-modal args so the "Reset the mailbox password first" affordance
// can hand off to the existing Edit Email modal without losing quota/active.
var importArchiveEditArgs = null;

function showImportArchiveModal(id, email, isImap, quota, active, archivalState, archivalRemaining, archivalMax) {
    document.getElementById('importArchiveEmailId').value = id;
    document.getElementById('importArchiveEmailDisplay').textContent = email;
    var pwField = document.getElementById('importArchiveMailboxPassword');
    if (pwField) pwField.value = '';
    document.getElementById('importArchiveError').classList.add('d-none');
    document.getElementById('importArchiveSuccess').classList.add('d-none');

    // Re-run vs first import labeling.
    var title = document.getElementById('importArchiveModalLabel');
    var btnLbl = document.getElementById('importArchiveSubmitLabel');
    if (isImap) {
        if (title)  title.textContent  = 'Sync Existing Mail';
        if (btnLbl) btnLbl.textContent = 'Sync now';
    } else {
        if (title)  title.textContent  = 'Import Existing Mail';
        if (btnLbl) btnLbl.textContent = 'Import existing mail';
    }

    importArchiveEditArgs = { id: id, email: email, quota: quota, active: active,
                              state: archivalState, remaining: archivalRemaining, max: archivalMax };

    bootstrap.Modal.getOrCreateInstance(document.getElementById('importArchiveModal')).show();
}

(function () {
    var enableBtn = document.getElementById('enableArchivalSubmit');
    if (enableBtn) {
        enableBtn.addEventListener('click', async () => {
            const id   = document.getElementById('enableArchivalEmailId').value;
            const bichonField = document.getElementById('enableArchivalBichonPassword');
            // Archive login (Bichon WebUI) password is optional. No mailbox /
            // IMAP password is sent — archival is an ingest-only push target.
            const bichonPw = bichonField ? bichonField.value : '';
            const err  = document.getElementById('enableArchivalError');
            err.classList.add('d-none');
            const fd = new FormData();
            fd.append('email_id', id);
            if (bichonPw) {
                fd.append('bichon_password', bichonPw);
            }
            fd.append('csrf_token', '<?php echo get_csrf_token(); ?>');
            try {
                const r = await fetch('api/email-archival.php?action=enable', { method: 'POST', body: fd });
                const j = await r.json();
                if (j.status === 'success') {
                    location.reload();
                } else {
                    err.textContent = j.message || 'Unknown error';
                    err.classList.remove('d-none');
                }
            } catch (e) {
                err.textContent = 'Request failed: ' + e.message;
                err.classList.remove('d-none');
            }
        });
    }

    var resetBtn = document.getElementById('resetArchivePwSubmit');
    if (resetBtn) {
        resetBtn.addEventListener('click', async () => {
            const id   = document.getElementById('resetArchivePwEmailId').value;
            const pw1  = document.getElementById('resetArchivePwNew').value;
            const pw2  = document.getElementById('resetArchivePwConfirm').value;
            const err  = document.getElementById('resetArchivePwError');
            const ok   = document.getElementById('resetArchivePwSuccess');
            err.classList.add('d-none');
            ok.classList.add('d-none');
            if (!pw1) { err.textContent = 'New password required.'; err.classList.remove('d-none'); return; }
            if (pw1 !== pw2) { err.textContent = 'Passwords do not match.'; err.classList.remove('d-none'); return; }
            const fd = new FormData();
            fd.append('email_id', id);
            fd.append('new_password', pw1);
            fd.append('csrf_token', '<?php echo get_csrf_token(); ?>');
            try {
                const r = await fetch('api/email-archival.php?action=reset_password', { method: 'POST', body: fd });
                const j = await r.json();
                if (j.status === 'success') {
                    ok.textContent = j.message || 'Archive password updated';
                    ok.classList.remove('d-none');
                    document.getElementById('resetArchivePwNew').value = '';
                    document.getElementById('resetArchivePwConfirm').value = '';
                    setTimeout(function () {
                        var modalEl = document.getElementById('resetArchivePasswordModal');
                        var inst = bootstrap.Modal.getInstance(modalEl);
                        if (inst) inst.hide();
                    }, 1200);
                } else {
                    err.textContent = j.message || 'Unknown error';
                    err.classList.remove('d-none');
                }
            } catch (e) {
                err.textContent = 'Request failed: ' + e.message;
                err.classList.remove('d-none');
            }
        });
    }

    // Show/hide for the new Bichon-WebUI password field in enable modal
    var togglePwBtn2 = document.getElementById('toggleEnableArchivalBichonPassword');
    if (togglePwBtn2) {
        togglePwBtn2.addEventListener('click', function () {
            var pw   = document.getElementById('enableArchivalBichonPassword');
            var icon = document.getElementById('toggleEnableArchivalBichonPasswordIcon');
            if (pw.type === 'password') {
                pw.type = 'text';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            } else {
                pw.type = 'password';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        });
    }

    // Show/hide for the new-password field in reset modal
    var togglePwBtn3 = document.getElementById('toggleResetArchivePwNew');
    if (togglePwBtn3) {
        togglePwBtn3.addEventListener('click', function () {
            var pw   = document.getElementById('resetArchivePwNew');
            var icon = document.getElementById('toggleResetArchivePwNewIcon');
            if (pw.type === 'password') {
                pw.type = 'text';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            } else {
                pw.type = 'password';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        });
    }

    var disableBtn = document.getElementById('disableArchivalSubmit');
    if (disableBtn) {
        disableBtn.addEventListener('click', async () => {
            const id    = document.getElementById('disableArchivalEmailId').value;
            // Customer view renders the purge flag as a hidden input (no .checked);
            // root sees a real checkbox. Read whichever shape is present and
            // default to true if neither (current disableArchival is always a
            // soft-delete regardless, so the value is non-load-bearing for
            // behavior — only the audit-log details differ).
            const purgeEl = document.getElementById('disableArchivalPurgeRemote');
            const purge   = purgeEl ? (typeof purgeEl.checked === 'boolean' ? purgeEl.checked : true) : true;
            const err   = document.getElementById('disableArchivalError');
            err.classList.add('d-none');
            const fd = new FormData();
            fd.append('email_id', id);
            fd.append('purge_remote', purge ? 'true' : 'false');
            fd.append('csrf_token', '<?php echo get_csrf_token(); ?>');
            try {
                const r = await fetch('api/email-archival.php?action=disable', { method: 'POST', body: fd });
                const j = await r.json();
                if (j.status === 'success') {
                    location.reload();
                } else {
                    err.textContent = j.message || 'Unknown error';
                    err.classList.remove('d-none');
                }
            } catch (e) {
                err.textContent = 'Request failed: ' + e.message;
                err.classList.remove('d-none');
            }
        });
    }

    // Show/hide for the mailbox-password field in the import modal.
    var togglePwBtnImport = document.getElementById('toggleImportArchiveMailboxPassword');
    if (togglePwBtnImport) {
        togglePwBtnImport.addEventListener('click', function () {
            var pw   = document.getElementById('importArchiveMailboxPassword');
            var icon = document.getElementById('toggleImportArchiveMailboxPasswordIcon');
            if (pw.type === 'password') {
                pw.type = 'text';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            } else {
                pw.type = 'password';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        });
    }

    // "Forgot it? Reset the mailbox password first" — hand off to the existing
    // Edit Email modal (which sets a new mailbox password) without losing the
    // row's quota/active/archival context.
    var importResetLink = document.getElementById('importArchiveResetLink');
    if (importResetLink) {
        importResetLink.addEventListener('click', function (ev) {
            ev.preventDefault();
            var a = importArchiveEditArgs;
            var inst = bootstrap.Modal.getInstance(document.getElementById('importArchiveModal'));
            if (inst) inst.hide();
            if (a && typeof editEmailAccount === 'function') {
                editEmailAccount(a.id, a.email, a.quota, a.active, a.state, a.remaining, a.max);
            }
        });
    }

    var importBtn = document.getElementById('importArchiveSubmit');
    if (importBtn) {
        importBtn.addEventListener('click', async () => {
            const id  = document.getElementById('importArchiveEmailId').value;
            const pwField = document.getElementById('importArchiveMailboxPassword');
            const pw  = pwField ? pwField.value : '';
            const err = document.getElementById('importArchiveError');
            const ok  = document.getElementById('importArchiveSuccess');
            err.classList.add('d-none');
            ok.classList.add('d-none');
            if (!pw) { err.textContent = 'Mailbox password is required.'; err.classList.remove('d-none'); return; }
            // Mailbox password goes through $_POST['password'] only — never logged server-side.
            const fd = new FormData();
            fd.append('email_id', id);
            fd.append('password', pw);
            fd.append('csrf_token', '<?php echo get_csrf_token(); ?>');
            try {
                const r = await fetch('api/email-archival.php?action=import_existing', { method: 'POST', body: fd });
                const j = await r.json();
                if (j.status === 'success') {
                    if (pwField) pwField.value = '';
                    ok.textContent = 'Import started — existing mail will appear in the archive shortly.';
                    ok.classList.remove('d-none');
                    setTimeout(function () {
                        var modalEl = document.getElementById('importArchiveModal');
                        var inst = bootstrap.Modal.getInstance(modalEl);
                        if (inst) inst.hide();
                        location.reload();
                    }, 1800);
                } else {
                    err.textContent = j.message || 'Unknown error';
                    err.classList.remove('d-none');
                }
            } catch (e) {
                err.textContent = 'Request failed: ' + e.message;
                err.classList.remove('d-none');
            }
        });
    }

})();
</script>

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

<!-- Choices.js CSS/JS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/choices.js/public/assets/styles/choices.min.css">
<script src="https://cdn.jsdelivr.net/npm/choices.js/public/assets/scripts/choices.min.js"></script>

<style>
/* Choices.js styling for domain dropdown */
.choices__inner {
    background-color: var(--bs-body-bg) !important;
    border: 1px solid var(--bs-border-color) !important;
    color: #212529 !important; /* Use .text-dark for light backgrounds */
    min-width: 200px;
}

.choices__list--dropdown {
    background-color: var(--bs-body-bg) !important;
    border: 1px solid var(--bs-border-color) !important;
    color: #212529 !important; /* Use .text-dark for light backgrounds */
}

.choices__item--choice {
    color: #212529 !important; /* Use .text-dark for light backgrounds */
    background-color: var(--bs-body-bg) !important;
}

.choices__item--choice:hover {
    background-color: var(--bs-tertiary-bg) !important;
    color: #212529 !important;
}

.choices__item--choice.is-highlighted {
    background-color: var(--bs-primary) !important;
    color: white !important;
}

.choices__placeholder {
    color: var(--bs-secondary-color) !important;
}

.choices__input {
    background-color: transparent !important;
    color: #212529 !important;
}

/* Fix dropdown z-index in modals */
.modal .choices__list--dropdown {
    z-index: 1060;
}

/* Improve form text readability */
.form-text {
    color: #f8f9fa !important; /* Use .text-light for dark backgrounds */
}

.form-text.text-muted {
    color: #adb5bd !important;
}

/* Dark mode password generator text */
.bg-dark .text-muted {
    color: #adb5bd !important;
}

.bg-dark .form-check-label {
    color: #f8f9fa !important;
}
</style>

<!-- Domain Details Modal -->
<div class="modal fade" id="domainDetailsModal" tabindex="-1" aria-labelledby="domainDetailsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="domainDetailsModalLabel">Domain Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="domainDetailsLoading" class="text-center">
                    <div class="spinner-border" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-2">Loading domain information...</p>
                </div>
                
                <div id="domainDetailsContent" style="display: none;">
                    <div class="row">
                        <div class="col-md-6">
                            <h6>Basic Information</h6>
                            <table class="table table-sm">
                                <tr>
                                    <td><strong>Domain:</strong></td>
                                    <td id="detail_name"></td>
                                </tr>
                                <tr>
                                    <td><strong>Status:</strong></td>
                                    <td id="detail_status"></td>
                                </tr>
                                <tr>
                                    <td><strong>Created:</strong></td>
                                    <td id="detail_created"></td>
                                </tr>
                                <tr>
                                    <td><strong>Updated:</strong></td>
                                    <td id="detail_updated"></td>
                                </tr>
                                <tr>
                                    <td><strong>Reference ID:</strong></td>
                                    <td id="detail_reference_id"></td>
                                </tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <h6>Configuration</h6>
                            <table class="table table-sm">
                                <tr>
                                    <td><strong>Forwarding:</strong></td>
                                    <td id="detail_forwarding"></td>
                                </tr>
                                <tr>
                                    <td><strong>Domain Bin:</strong></td>
                                    <td id="detail_domain_bin"></td>
                                </tr>
                                <tr>
                                    <td><strong>Force Route:</strong></td>
                                    <td id="detail_force_route"></td>
                                </tr>
                                <tr>
                                    <td><strong>Custom Outbound:</strong></td>
                                    <td id="detail_custom_outbound"></td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </div>
                
                <div id="domainDetailsError" style="display: none;">
                    <div class="alert alert-danger">
                        <i class="fa fa-exclamation-triangle"></i>
                        <strong>Error loading domain details</strong>
                        <p id="domainDetailsErrorMessage" class="mb-0"></p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- Edit Domain Modal -->
<div class="modal fade" id="editDomainModal" tabindex="-1" aria-labelledby="editDomainModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="action" value="update_domain">
                <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                <input type="hidden" id="edit_domain_name" name="domain_name">
                <div class="modal-header">
                    <h5 class="modal-title" id="editDomainModalLabel">Edit Domain</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <h6>Basic Settings</h6>
                            <div class="mb-3">
                                <label for="edit_name" class="form-label">Domain Name</label>
                                <input type="text" class="form-control" id="edit_name" name="name" readonly>
                            </div>
                            <div class="mb-3">
                                <label for="edit_reference_id" class="form-label">Reference ID</label>
                                <input type="text" class="form-control" id="edit_reference_id" name="reference_id" placeholder="Optional reference ID">
                            </div>
                            <div class="mb-3">
                                <div class="form-check">
                                    <input type="hidden" name="disabled" value="0">
                                    <input class="form-check-input" type="checkbox" id="edit_disabled" name="disabled" value="1">
                                    <label class="form-check-label" for="edit_disabled">
                                        Disable domain
                                    </label>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <h6>Forwarding Settings</h6>
                            <div class="mb-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="edit_forward" name="forward" value="1">
                                    <label class="form-check-label" for="edit_forward">
                                        Enable forwarding
                                    </label>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label for="edit_forward_domain" class="form-label">Forward to domain</label>
                                <input type="text" class="form-control" id="edit_forward_domain" name="forward_domain" placeholder="example.com">
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <h6>Domain Bin Settings</h6>
                            <div class="mb-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="edit_domain_bin" name="domain_bin" value="1">
                                    <label class="form-check-label" for="edit_domain_bin">
                                        Enable domain bin
                                    </label>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label for="edit_domain_bin_address" class="form-label">Domain bin address</label>
                                <input type="email" class="form-control" id="edit_domain_bin_address" name="domain_bin_address" placeholder="bin@example.com">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <h6>Force Route Settings</h6>
                            <div class="mb-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="edit_force_route" name="force_route" value="1">
                                    <label class="form-check-label" for="edit_force_route">
                                        Enable force route
                                    </label>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label for="edit_force_route_host" class="form-label">Force route host</label>
                                <input type="text" class="form-control" id="edit_force_route_host" name="force_route_host" placeholder="mail.example.com">
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <h6>Custom Outbound Settings</h6>
                            <div class="mb-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="edit_custom_outbound" name="custom_outbound" value="1">
                                    <label class="form-check-label" for="edit_custom_outbound">
                                        Enable custom outbound
                                    </label>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label for="edit_outbound_ip" class="form-label">Outbound IP</label>
                                <input type="text" class="form-control" id="edit_outbound_ip" name="outbound_ip" placeholder="192.168.1.100">
                            </div>
                            <div class="mb-3">
                                <label for="edit_outbound_ehlo" class="form-label">Outbound EHLO</label>
                                <input type="text" class="form-control" id="edit_outbound_ehlo" name="outbound_ehlo" placeholder="mail.example.com">
                            </div>
                        </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">Save Changes</button>
                </div>
            </form>
        </div>
    </div>
</div> 