<?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';
                    } else {
                        $message = $result['msg'];
                        $message_type = 'danger';
                    }
                }
                break;
                
            case 'update_email_account':
                if (!empty($_POST['email_id'])) {
                    $updates = [];
                    if (!empty($_POST['password'])) {
                        $updates['password'] = $_POST['password'];
                    }
                    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(
                            intval($_POST['email_id']),
                            AUTH_USER,
                            $updates['password'] ?? null,
                            $updates['quota_mb'] ?? null,
                            $updates['active'] ?? null
                        );
                        
                        if ($result['status'] === '0') {
                            $message = $result['msg'];
                            $message_type = 'success';
                        } else {
                            $message = $result['msg'];
                            $message_type = 'danger';
                        }
                    }
                }
                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'];
}

// 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; ?>

<!-- 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 (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>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 echo date('M j, Y', strtotime($account['created_at'])); ?></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>
                                    <button type="button" class="btn btn-sm btn-outline-primary" 
                                            onclick="editEmailAccount(<?php echo $account['id']; ?>, '<?php echo htmlspecialchars($account['email_address']); ?>', <?php echo $account['quota_mb']; ?>, <?php echo $account['active'] ? 'true' : 'false'; ?>)">
                                        <i class="fa fa-edit"></i>
                                    </button>
                                    <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 date('M j, Y', strtotime($rule['created_at'])); ?></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 date('M j, Y', strtotime($created));
                                    ?>
                                </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="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>Domain</th>
                                <th>DKIM Status</th>
                                <th>DNS Record</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody id="dkimDomainsTable">
                            <tr>
                                <td colspan="4" class="text-center">
                                    <div class="spinner-border spinner-border-sm" role="status">
                                        <span class="visually-hidden">Loading...</span>
                                    </div>
                                    Loading domains...
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 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>
                </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>

<!-- 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">New Password (leave blank to keep current)</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">
                            Leave blank to keep current password. Minimum 8 characters if changing.
                            <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>
                </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">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>

<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(); ?>';

// 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) {
    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';
    
    new bootstrap.Modal(document.getElementById('editEmailModal')).show();
}

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 = '';

// Load DKIM domains on page load
document.addEventListener('DOMContentLoaded', function() {
    loadDkimDomains();
});

function loadDkimDomains() {
    const tableBody = document.getElementById('dkimDomainsTable');
    
    // Get user's domains from the PHP variables (for root, use all WHP domains)
    <?php if (AUTH_USER === 'root'): ?>
    const domains = <?php echo json_encode($whp_domains); ?>;
    <?php else: ?>
    const domains = <?php echo json_encode($domains); ?>;
    <?php endif; ?>
    
    if (domains.length === 0) {
        tableBody.innerHTML = `
            <tr>
                <td colspan="4" class="text-center">
                    <div class="alert alert-info mb-0">
                        <i class="fa fa-info-circle"></i>
                        <strong>No domains available</strong> - Add domains in the Domains section to manage DKIM records.
                    </div>
                </td>
            </tr>
        `;
        return;
    }
    
    tableBody.innerHTML = '';
    
    domains.forEach(domain => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td><strong>${domain.domain_name}</strong></td>
            <td>
                <span class="badge bg-secondary">Checking...</span>
            </td>
            <td>
                <span class="text-muted">Loading...</span>
            </td>
            <td>
                <button type="button" class="btn btn-sm btn-outline-warning dkim-manage-btn" 
                        data-domain="${domain.domain_name}" 
                        title="Manage DKIM">
                    <i class="fa fa-key"></i> Manage DKIM
                </button>
            </td>
        `;
        tableBody.appendChild(row);
        
        // Add event listener for DKIM manage button
        const dkimBtn = row.querySelector('.dkim-manage-btn');
        dkimBtn.addEventListener('click', function() {
            manageDkim(this.getAttribute('data-domain'));
        });
        
        // Check DKIM status for this domain
        checkDkimStatus(domain.domain_name, 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);
            // Refresh the domains table
            loadDkimDomains();
        } 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);
            // Refresh the domains table
            loadDkimDomains();
        } 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);
                // Refresh the domains table
                loadDkimDomains();
            }, 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; ?>
    }
});
</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> 