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



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

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'update_hostname':
                if (!empty($_POST['hostname'])) {
                    $hostname = trim($_POST['hostname']);
                    
                    // Validate hostname format
                    if (!filter_var($hostname, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME)) {
                        $message = 'Invalid hostname format';
                        $message_type = 'danger';
                        break;
                    }
                    
                    // Update system hostname
                    $result = shell_exec("hostnamectl set-hostname " . escapeshellarg($hostname) . " 2>&1");
                    
                    // Update /etc/hosts
                    $hosts_content = file_get_contents('/etc/hosts');
                    $hosts_lines = explode("\n", $hosts_content);
                    $updated = false;
                    
                    foreach ($hosts_lines as $i => $line) {
                        if (strpos($line, '127.0.1.1') === 0) {
                            $hosts_lines[$i] = "127.0.1.1\t" . $hostname;
                            $updated = true;
                            break;
                        }
                    }
                    
                    if (!$updated) {
                        $hosts_lines[] = "127.0.1.1\t" . $hostname;
                    }
                    
                    file_put_contents('/etc/hosts', implode("\n", $hosts_lines));
                    
                    // Save to configuration file
                    $config = [
                        'hostname' => $hostname,
                        'updated_at' => date('Y-m-d H:i:s')
                    ];
                    
                    if (file_exists('/docker/whp/settings.json')) {
                        $existing_config = json_decode(file_get_contents('/docker/whp/settings.json'), true);
                        $config = array_merge($existing_config, $config);
                    }
                    
                    file_put_contents('/docker/whp/settings.json', json_encode($config, JSON_PRETTY_PRINT));
                    chmod('/docker/whp/settings.json', 0600);
                    
                    $message = 'Hostname updated successfully: ' . $hostname;
                    $message_type = 'success';
                } else {
                    $message = 'Hostname is required';
                    $message_type = 'danger';
                }
                break;
                
            case 'update_nameservers':
                if (!empty($_POST['nameserver1'])) {
                    $nameservers = [
                        trim($_POST['nameserver1']),
                        !empty($_POST['nameserver2']) ? trim($_POST['nameserver2']) : null
                    ];
                    
                    // Filter out empty nameservers
                    $nameservers = array_filter($nameservers);
                    
                    // Validate nameserver IPs
                    $valid_nameservers = [];
                    foreach ($nameservers as $ns) {
                        if (filter_var($ns, FILTER_VALIDATE_IP)) {
                            $valid_nameservers[] = $ns;
                        } else {
                            $message = 'Invalid nameserver IP address: ' . $ns;
                            $message_type = 'danger';
                            break 2;
                        }
                    }
                    
                    if (empty($valid_nameservers)) {
                        $message = 'At least one valid nameserver is required';
                        $message_type = 'danger';
                        break;
                    }
                    
                    // Update resolv.conf
                    $resolv_content = "# Generated by WHP Server Settings\n";
                    foreach ($valid_nameservers as $ns) {
                        $resolv_content .= "nameserver $ns\n";
                    }
                    
                    file_put_contents('/etc/resolv.conf', $resolv_content);
                    
                    // Save to configuration file
                    $config = [
                        'nameservers' => $valid_nameservers,
                        'updated_at' => date('Y-m-d H:i:s')
                    ];
                    
                    if (file_exists('/docker/whp/settings.json')) {
                        $existing_config = json_decode(file_get_contents('/docker/whp/settings.json'), true);
                        $config = array_merge($existing_config, $config);
                    }
                    
                    file_put_contents('/docker/whp/settings.json', json_encode($config, JSON_PRETTY_PRINT));
                    chmod('/docker/whp/settings.json', 0600);
                    
                    $message = 'Nameservers updated successfully';
                    $message_type = 'success';
                } else {
                    $message = 'At least one nameserver is required';
                    $message_type = 'danger';
                }
                break;
                
            case 'update_timezone':
                if (!empty($_POST['timezone'])) {
                    $timezone = trim($_POST['timezone']);
                    
                    // Validate timezone
                    if (!in_array($timezone, timezone_identifiers_list())) {
                        $message = 'Invalid timezone';
                        $message_type = 'danger';
                        break;
                    }
                    
                    // Update system timezone
                    shell_exec("timedatectl set-timezone " . escapeshellarg($timezone));
                    
                    // Save to configuration file
                    $config = [
                        'timezone' => $timezone,
                        'updated_at' => date('Y-m-d H:i:s')
                    ];
                    
                    if (file_exists('/docker/whp/settings.json')) {
                        $existing_config = json_decode(file_get_contents('/docker/whp/settings.json'), true);
                        $config = array_merge($existing_config, $config);
                    }
                    
                    file_put_contents('/docker/whp/settings.json', json_encode($config, JSON_PRETTY_PRINT));
                    chmod('/docker/whp/settings.json', 0600);
                    
                    $message = 'Timezone updated successfully: ' . $timezone;
                    $message_type = 'success';
                } else {
                    $message = 'Timezone is required';
                    $message_type = 'danger';
                }
                break;
                
            case 'restart_services':
                if (!empty($_POST['services'])) {
                    $services = $_POST['services'];
                    $allowed_services = ['httpd', 'php-fpm', 'docker', 'network', 'proftpd', 'whp-backup-upload'];
                    $restarted_services = [];
                    $failed_services = [];
                    
                    foreach ($services as $service) {
                        if (in_array($service, $allowed_services)) {
                            if ($service === 'network') {
                                $result = shell_exec("systemctl restart NetworkManager 2>&1");
                            } else {
                                $result = shell_exec("systemctl restart $service 2>&1");
                            }
                            
                            // Check if service restarted successfully
                            $status = shell_exec("systemctl is-active $service 2>/dev/null");
                            if (trim($status) === 'active') {
                                $restarted_services[] = $service;
                            } else {
                                $failed_services[] = $service;
                            }
                        }
                    }
                    
                    if (!empty($restarted_services)) {
                        $message = 'Services restarted: ' . implode(', ', $restarted_services);
                        $message_type = 'success';
                        
                        if (!empty($failed_services)) {
                            $message .= '. Failed: ' . implode(', ', $failed_services);
                        }
                    } else {
                        $message = 'No services were restarted';
                        $message_type = 'danger';
                    }
                }
                break;
                
            case 'update_whp_nameservers':
                if (!empty($_POST['whp_ns1']) && !empty($_POST['whp_ns2'])) {
                    $whp_ns1 = trim($_POST['whp_ns1']);
                    $whp_ns2 = trim($_POST['whp_ns2']);
                    $whp_ns1_ip = trim($_POST['whp_ns1_ip']);
                    $whp_ns2_ip = trim($_POST['whp_ns2_ip']);
                    
                    // Validate nameserver hostnames
                    if (!filter_var($whp_ns1, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) ||
                        !filter_var($whp_ns2, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME)) {
                        $message = 'Invalid nameserver hostname format';
                        $message_type = 'danger';
                        break;
                    }
                    
                    // Validate IP addresses
                    if (!filter_var($whp_ns1_ip, FILTER_VALIDATE_IP) ||
                        !filter_var($whp_ns2_ip, FILTER_VALIDATE_IP)) {
                        $message = 'Invalid nameserver IP address format';
                        $message_type = 'danger';
                        break;
                    }
                    
                    // Save to configuration file
                    $config = [
                        'whp_nameservers' => [
                            'ns1' => $whp_ns1,
                            'ns1_ip' => $whp_ns1_ip,
                            'ns2' => $whp_ns2,
                            'ns2_ip' => $whp_ns2_ip
                        ],
                        'updated_at' => date('Y-m-d H:i:s')
                    ];
                    
                    if (file_exists('/docker/whp/settings.json')) {
                        $existing_config = json_decode(file_get_contents('/docker/whp/settings.json'), true);
                        $config = array_merge($existing_config, $config);
                    }
                    
                    file_put_contents('/docker/whp/settings.json', json_encode($config, JSON_PRETTY_PRINT));
                    chmod('/docker/whp/settings.json', 0600);
                    
                    $message = 'WHP nameserver configuration updated successfully';
                    $message_type = 'success';
                } else {
                    $message = 'Both primary and secondary nameserver hostnames and IPs are required';
                    $message_type = 'danger';
                }
                break;

            case 'update_backup_settings':
                if (!empty($_POST['max_concurrent_backups'])) {
                    $max_concurrent = intval($_POST['max_concurrent_backups']);

                    // Validate the value (1-10 concurrent backups)
                    if ($max_concurrent < 1 || $max_concurrent > 10) {
                        $message = 'Maximum concurrent backups must be between 1 and 10';
                        $message_type = 'danger';
                        break;
                    }

                    // Load existing config and merge
                    $config = [];
                    if (file_exists('/docker/whp/settings.json')) {
                        $existing_config = json_decode(file_get_contents('/docker/whp/settings.json'), true);
                        if ($existing_config) {
                            $config = $existing_config;
                        }
                    }

                    $config['backup_max_concurrent'] = $max_concurrent;
                    $config['updated_at'] = date('Y-m-d H:i:s');

                    // Handle backup local storage limit if provided
                    if (isset($_POST['backup_upload_space_gb']) && $_POST['backup_upload_space_gb'] !== '') {
                        $space_gb = intval($_POST['backup_upload_space_gb']);
                        if ($space_gb < 10 || $space_gb > 10000) {
                            $message = 'Backup local storage limit must be between 10 and 10,000 GB';
                            $message_type = 'danger';
                            break;
                        }

                        // Update backup_local_storage table
                        try {
                            require_once('/docker/whp/web/libs/mysqlmgmt.php');
                            $mysql = new \mysqlmgmt();
                            $dbConn = $mysql->getMySQLConnection();
                            $dbConn->exec("USE whp");
                            $stmt = $dbConn->prepare("UPDATE backup_local_storage SET max_size_gb = ? WHERE id = 1");
                            $stmt->execute([$space_gb]);

                            $config['backup_upload_space_gb'] = $space_gb;
                        } catch (Exception $e) {
                            $message = 'Failed to update backup storage limit: ' . $e->getMessage();
                            $message_type = 'danger';
                            break;
                        }
                    }

                    // Save settings
                    $settings_json = json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
                    if (file_put_contents('/docker/whp/settings.json', $settings_json) === false) {
                        $message = 'Failed to save backup settings';
                        $message_type = 'danger';
                        break;
                    }

                    // Set proper permissions
                    chmod('/docker/whp/settings.json', 0600);

                    $message = "Backup settings updated successfully. Maximum concurrent backups set to $max_concurrent.";
                    $message_type = 'success';
                } else {
                    $message = 'Maximum concurrent backups value is required';
                    $message_type = 'danger';
                }
                break;

            case 'manage_docker_container':
                if (!empty($_POST['container']) && !empty($_POST['operation'])) {
                    $container = trim($_POST['container']);
                    $operation = trim($_POST['operation']);
                    $allowed_containers = ['mysql', 'haproxy-manager', 'memcache', 'postgresql'];
                    $allowed_operations = ['start', 'stop', 'restart', 'pull_recreate'];
                    
                    if (!in_array($container, $allowed_containers) || !in_array($operation, $allowed_operations)) {
                        $message = 'Invalid container or operation';
                        $message_type = 'danger';
                        break;
                    }
                    
                    $result = '';
                    switch ($operation) {
                        case 'start':
                            $result = shell_exec("/root/whp/scripts/container-manager.sh start $container 2>&1");
                            $message = "Container $container started";
                            break;
                        case 'stop':
                            $result = shell_exec("/root/whp/scripts/container-manager.sh stop $container 2>&1");
                            $message = "Container $container stopped";
                            break;
                        case 'restart':
                            $result = shell_exec("/root/whp/scripts/container-manager.sh restart $container 2>&1");
                            $message = "Container $container restarted";
                            break;
                        case 'pull_recreate':
                            $result = shell_exec("/root/whp/scripts/container-manager.sh recreate $container 2>&1");
                            $message = "Container $container recreated with latest image";
                            break;
                    }
                    
                    $message_type = 'success';
                }
                break;
                
            case 'manage_shared_httpd':
                if (!empty($_POST['operation'])) {
                    $operation = trim($_POST['operation']);
                    $allowed_operations = ['scale', 'restart_all', 'pull_recreate_all', 'stop_all', 'start_all'];

                    if (!in_array($operation, $allowed_operations)) {
                        $message = 'Invalid shared httpd operation';
                        $message_type = 'danger';
                        break;
                    }

                    $result = '';
                    switch ($operation) {
                        case 'scale':
                            $count = max(0, intval($_POST['instance_count'] ?? 1));
                            $result = shell_exec("/root/whp/scripts/container-manager.sh scale shared-httpd $count 2>&1");
                            $message = "Shared httpd scaled to $count instance(s)";
                            break;
                        case 'restart_all':
                            $instances = trim(shell_exec("docker ps --filter 'name=shared-httpd-' --filter 'status=running' --format '{{.Names}}' 2>/dev/null"));
                            if (!empty($instances)) {
                                foreach (explode("\n", $instances) as $name) {
                                    shell_exec("docker restart " . escapeshellarg(trim($name)) . " 2>&1");
                                }
                                $message = "All shared httpd instances restarted";
                            } else {
                                $message = "No running shared httpd instances to restart";
                                $message_type = 'warning';
                                break 2;
                            }
                            break;
                        case 'pull_recreate_all':
                            $instances = trim(shell_exec("docker ps -a --filter 'name=shared-httpd-' --format '{{.Names}}' 2>/dev/null"));
                            if (!empty($instances)) {
                                foreach (explode("\n", $instances) as $name) {
                                    $instance_num = str_replace('shared-httpd-', '', trim($name));
                                    shell_exec("/root/whp/scripts/container-manager.sh recreate shared-httpd $instance_num 2>&1");
                                }
                                $message = "All shared httpd instances pulled and recreated";
                            } else {
                                $message = "No shared httpd instances found";
                                $message_type = 'warning';
                                break 2;
                            }
                            break;
                        case 'stop_all':
                            $instances = trim(shell_exec("docker ps --filter 'name=shared-httpd-' --filter 'status=running' --format '{{.Names}}' 2>/dev/null"));
                            if (!empty($instances)) {
                                foreach (explode("\n", $instances) as $name) {
                                    shell_exec("docker stop " . escapeshellarg(trim($name)) . " 2>&1");
                                }
                                $message = "All shared httpd instances stopped";
                            } else {
                                $message = "No running shared httpd instances to stop";
                                $message_type = 'warning';
                                break 2;
                            }
                            break;
                        case 'start_all':
                            $instances = trim(shell_exec("docker ps -a --filter 'name=shared-httpd-' --filter 'status=exited' --format '{{.Names}}' 2>/dev/null"));
                            if (!empty($instances)) {
                                foreach (explode("\n", $instances) as $name) {
                                    shell_exec("docker start " . escapeshellarg(trim($name)) . " 2>&1");
                                }
                                $message = "All shared httpd instances started";
                            } else {
                                $message = "No stopped shared httpd instances to start";
                                $message_type = 'warning';
                                break 2;
                            }
                            break;
                    }
                    $message_type = $message_type ?: 'success';
                }
                break;

            case 'update_shared_httpd_settings':
                $default_mode = ($_POST['default_mode'] ?? 'standalone') === 'shared_httpd' ? 'shared_httpd' : 'standalone';

                $config = [];
                if (file_exists('/docker/whp/settings.json')) {
                    $config = json_decode(file_get_contents('/docker/whp/settings.json'), true) ?: [];
                }
                $config['shared_httpd'] = [
                    'default_mode' => $default_mode,
                ];
                $config['updated_at'] = date('Y-m-d H:i:s');

                file_put_contents('/docker/whp/settings.json', json_encode($config, JSON_PRETTY_PRINT));
                chmod('/docker/whp/settings.json', 0600);

                $message = 'Shared httpd settings updated successfully';
                $message_type = 'success';
                break;

            case 'update_haproxy_api_key':
                if (!empty($_POST['haproxy_api_key'])) {
                    $api_key = trim($_POST['haproxy_api_key']);
                    
                    // Validate API key format (basic validation)
                    if (strlen($api_key) < 16) {
                        $message = 'API key must be at least 16 characters long';
                        $message_type = 'danger';
                        break;
                    }
                    
                    // Save to configuration file
                    $config = [
                        'haproxy_api_key' => $api_key,
                        'updated_at' => date('Y-m-d H:i:s')
                    ];
                    
                    if (file_exists('/docker/whp/settings.json')) {
                        $existing_config = json_decode(file_get_contents('/docker/whp/settings.json'), true);
                        $config = array_merge($existing_config, $config);
                    }
                    
                    file_put_contents('/docker/whp/settings.json', json_encode($config, JSON_PRETTY_PRINT));
                    chmod('/docker/whp/settings.json', 0600);
                    
                    $message = 'HAProxy API key updated successfully. Restart the HAProxy container to apply changes.';
                    $message_type = 'success';
                } else {
                    $message = 'API key is required';
                    $message_type = 'danger';
                }
                break;
                
            case 'haproxy_regenerate_config':
                try {
                    require_once('/docker/whp/web/libs/haproxy_manager.php');
                    require_once('/docker/whp/web/libs/mysqlmgmt.php');
                    
                    $haproxy_manager = new haproxy_manager();
                    $MySQLMgmt = new mysqlmgmt();
                    $db = $MySQLMgmt->getMySQLConnection();
                    
                    if (!$db) {
                        throw new Exception('Failed to connect to database');
                    }
                    
                    // First, clear all existing HAProxy configurations
                    $stmt = $db->query("SELECT domain_name FROM whp.haproxy_domains");
                    $existing_domains = $stmt->fetchAll();
                    
                    foreach ($existing_domains as $domain) {
                        $haproxy_manager->removeDomain($domain['domain_name']);
                    }
                    
                    // Get all active sites and reconfigure HAProxy
                    $stmt = $db->query("SELECT id FROM whp.sites WHERE active = 1");
                    $sites = $stmt->fetchAll();
                    
                    $regenerate_errors = [];
                    foreach ($sites as $site) {
                        $result = $haproxy_manager->configureSite($site['id'], []);
                        if (!$result['success']) {
                            $regenerate_errors[] = "Site {$site['id']}: " . $result['error'];
                        }
                    }
                    
                    // Call HAProxy regenerate to rebuild configuration
                    $regenerate_result = $haproxy_manager->regenerateConfiguration();
                    if (!$regenerate_result['success']) {
                        $regenerate_errors[] = "HAProxy regenerate failed: " . $regenerate_result['error'];
                    }
                    
                    if (empty($regenerate_errors)) {
                        $message = 'HAProxy configuration regenerated successfully for all sites';
                        $message_type = 'success';
                    } else {
                        $message = 'HAProxy configuration regenerated with some errors: ' . implode(', ', $regenerate_errors);
                        $message_type = 'warning';
                    }
                } catch (Exception $e) {
                    $message = 'Error regenerating HAProxy configuration: ' . $e->getMessage();
                    $message_type = 'danger';
                }
                break;
                
            case 'haproxy_reload_config':
                try {
                    require_once('/docker/whp/web/libs/haproxy_manager.php');
                    $haproxy_manager = new haproxy_manager();
                    
                    $result = $haproxy_manager->reloadConfiguration();
                    
                    if ($result['success']) {
                        $message = 'HAProxy configuration reloaded successfully';
                        $message_type = 'success';
                    } else {
                        $message = 'Failed to reload HAProxy configuration: ' . $result['error'];
                        $message_type = 'danger';
                    }
                } catch (Exception $e) {
                    $message = 'Error reloading HAProxy configuration: ' . $e->getMessage();
                    $message_type = 'danger';
                }
                break;
                
            case 'haproxy_health_check':
                try {
                    require_once('/docker/whp/web/libs/haproxy_manager.php');
                    $haproxy_manager = new haproxy_manager();
                    
                    $result = $haproxy_manager->getHealthStatus();
                    
                    if ($result['success']) {
                        $health_data = $result['data'];
                        $message = 'HAProxy health check completed. Status: ' . ($health_data['haproxy_status'] ?? 'Unknown');
                        $message_type = 'success';
                    } else {
                        $message = 'HAProxy health check failed: ' . $result['error'];
                        $message_type = 'danger';
                    }
                } catch (Exception $e) {
                    $message = 'Error checking HAProxy health: ' . $e->getMessage();
                    $message_type = 'danger';
                }
                break;
                
            case 'enable_system_service_ssl':
                if (!empty($_POST['service_name']) && !empty($_POST['domain_name'])) {
                    $service_name = trim($_POST['service_name']);
                    $domain_name = trim($_POST['domain_name']);
                    
                    // Validate service name
                    $allowed_services = ['httpd', 'proftpd'];
                    if (!in_array($service_name, $allowed_services)) {
                        $message = 'Invalid service name';
                        $message_type = 'danger';
                        break;
                    }
                    
                    // Validate domain format
                    if (!filter_var('http://' . $domain_name, FILTER_VALIDATE_URL)) {
                        $message = 'Invalid domain format';
                        $message_type = 'danger';
                        break;
                    }
                    
                    try {
                        require_once('/docker/whp/web/libs/ssl_manager.php');
                        $ssl_manager = new ssl_manager();
                        $result = $ssl_manager->enable_system_service_ssl($service_name, $domain_name);
                        
                        if ($result['success']) {
                            $message = $result['message'];
                            $message_type = 'success';
                        } else {
                            $message = 'Failed to enable SSL for ' . $service_name . ': ' . $result['error'];
                            $message_type = 'danger';
                        }
                    } catch (Exception $e) {
                        $message = 'Error enabling SSL: ' . $e->getMessage();
                        $message_type = 'danger';
                    }
                } else {
                    $message = 'Service name and domain name are required';
                    $message_type = 'danger';
                }
                break;
                
            case 'update_dns_settings':
                try {
                    // Validate and collect DNS settings
                    $dns_settings = [];
                    
                    // Mail server configuration
                    $mail_server = trim($_POST['mail_server'] ?? '');
                    if (!empty($mail_server)) {
                        if (filter_var('http://' . $mail_server, FILTER_VALIDATE_URL)) {
                            $dns_settings['mail_server'] = $mail_server;
                        } else {
                            throw new Exception('Invalid mail server format');
                        }
                    }
                    
                    // Mail server API configuration
                    $mail_api_url = trim($_POST['mail_api_url'] ?? '');
                    if (!empty($mail_api_url)) {
                        if (filter_var($mail_api_url, FILTER_VALIDATE_URL)) {
                            $dns_settings['mail_api_url'] = $mail_api_url;
                        } else {
                            throw new Exception('Invalid mail API URL format');
                        }
                    }
                    
                    $mail_api_username = trim($_POST['mail_api_username'] ?? '');
                    if (!empty($mail_api_username)) {
                        $dns_settings['mail_api_username'] = $mail_api_username;
                    }
                    
                    $mail_api_password = trim($_POST['mail_api_password'] ?? '');
                    if (!empty($mail_api_password)) {
                        $dns_settings['mail_api_password'] = $mail_api_password;
                    }
                    
                    // Default TTL
                    $default_ttl = intval($_POST['default_ttl'] ?? 3600);
                    if ($default_ttl < 60 || $default_ttl > 86400) {
                        $default_ttl = 3600;
                    }
                    $dns_settings['default_ttl'] = $default_ttl;
                    
                    // Server information
                    $dns_settings['server_name'] = trim($_POST['server_name'] ?? 'WHP Server');
                    $dns_settings['server_description'] = trim($_POST['server_description'] ?? 'Web Hosting Panel Server');
                    
                    // Load existing config and merge
                    $config = [];
                    if (file_exists('/docker/whp/settings.json')) {
                        $existing_config = json_decode(file_get_contents('/docker/whp/settings.json'), true);
                        $config = array_merge($existing_config, $dns_settings);
                    } else {
                        $config = $dns_settings;
                    }
                    
                    $config['updated_at'] = date('Y-m-d H:i:s');
                    
                    // Save settings
                    $settings_json = json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
                    if (file_put_contents('/docker/whp/settings.json', $settings_json) === false) {
                        throw new Exception('Failed to save settings file');
                    }
                    
                    // Set proper permissions
                    chmod('/docker/whp/settings.json', 0600);
                    
                    $message = 'DNS settings updated successfully';
                    $message_type = 'success';
                    
                    // Update NS records for all domains if PowerDNS integration is available
                    if (file_exists('/docker/whp/web/libs/pdns-integration.php') && 
                        file_exists('/docker/whp/web/libs/mysqlmgmt.php')) {
                        try {
                            require_once('/docker/whp/web/libs/pdns-integration.php');
                            require_once('/docker/whp/web/libs/mysqlmgmt.php');
                            $MySQLMgmt = new mysqlmgmt();
                            $db = $MySQLMgmt->getMySQLConnection();
                            if ($db) {
                                $pdns = new PowerDNSIntegration($db);
                                $pdns->updateAllDomainNSRecords();
                            }
                        } catch (Exception $e) {
                            // Don't fail the whole operation if PowerDNS update fails
                            $message .= ' (Note: PowerDNS update failed: ' . $e->getMessage() . ')';
                        }
                    }
                    
                    $mailserver_debug_log = !empty($_POST['mailserver_debug_log']) ? true : false;
                    $config = [
                        'mailserver_debug_log' => $mailserver_debug_log,
                        'updated_at' => date('Y-m-d H:i:s')
                    ];
                    if (file_exists('/docker/whp/settings.json')) {
                        $existing_config = json_decode(file_get_contents('/docker/whp/settings.json'), true);
                        $config = array_merge($existing_config, $config);
                    }
                    file_put_contents('/docker/whp/settings.json', json_encode($config, JSON_PRETTY_PRINT));
                    chmod('/docker/whp/settings.json', 0600);
                    
                } catch (Exception $e) {
                    $message = 'Error updating DNS settings: ' . $e->getMessage();
                    $message_type = 'danger';
                }
                break;
                
            case 'create_api_key':
                // Only root users can manage API keys
                if (AUTH_USER !== 'root') {
                    $message = 'Access denied. Only root users can manage API keys.';
                    $message_type = 'danger';
                    break;
                }
                
                if (!empty($_POST['key_name'])) {
                    $keyName = trim($_POST['key_name']);
                    $permissions = [];
                    
                    // Collect permissions
                    $availablePermissions = ['user_management', 'resource_management', 'sso_access', 'system_stats', 'ai_monitor_management'];
                    foreach ($availablePermissions as $perm) {
                        if (!empty($_POST['permissions'][$perm])) {
                            $permissions[$perm] = true;
                        }
                    }
                    
                    if (empty($permissions)) {
                        $message = 'At least one permission must be selected';
                        $message_type = 'danger';
                        break;
                    }
                    
                    try {
                        require_once('/docker/whp/web/libs/ApiKeyManager.php');
                        $apiKeyManager = new ApiKeyManager();
                        
                        $options = [
                            'rate_limit_per_hour' => intval($_POST['rate_limit'] ?? 1000),
                            'ip_whitelist' => !empty($_POST['ip_whitelist']) ? trim($_POST['ip_whitelist']) : null,
                            'notes' => !empty($_POST['notes']) ? trim($_POST['notes']) : null
                        ];
                        
                        $result = $apiKeyManager->generateApiKey($keyName, AUTH_USER, $permissions, $options);
                        
                        if ($result['success']) {
                            // Store the secret temporarily in the session for display
                            $_SESSION['new_api_secret'] = $result['api_secret'];
                            $_SESSION['new_api_key'] = $result['api_key'];
                            
                            $message = 'API key created successfully. Please copy the secret now - it will not be shown again.';
                            $message_type = 'success';
                        } else {
                            $message = 'Failed to create API key: ' . $result['error'];
                            $message_type = 'danger';
                        }
                    } catch (Exception $e) {
                        $message = 'Error creating API key: ' . $e->getMessage();
                        $message_type = 'danger';
                    }
                } else {
                    $message = 'API key name is required';
                    $message_type = 'danger';
                }
                break;
                
            case 'deactivate_api_key':
                // Only root users can manage API keys
                if (AUTH_USER !== 'root') {
                    $message = 'Access denied. Only root users can manage API keys.';
                    $message_type = 'danger';
                    break;
                }
                
                if (!empty($_POST['key_id'])) {
                    try {
                        require_once('/docker/whp/web/libs/ApiKeyManager.php');
                        $apiKeyManager = new ApiKeyManager();
                        
                        $result = $apiKeyManager->deactivateApiKey($_POST['key_id'], AUTH_USER);
                        
                        if ($result['success']) {
                            $message = 'API key deactivated successfully';
                            $message_type = 'success';
                        } else {
                            $message = 'Failed to deactivate API key: ' . $result['error'];
                            $message_type = 'danger';
                        }
                    } catch (Exception $e) {
                        $message = 'Error deactivating API key: ' . $e->getMessage();
                        $message_type = 'danger';
                    }
                } else {
                    $message = 'API key ID is required';
                    $message_type = 'danger';
                }
                break;
                
            case 'cleanup_sso_tokens':
                // Only root users can manage API keys
                if (AUTH_USER !== 'root') {
                    $message = 'Access denied. Only root users can manage API keys.';
                    $message_type = 'danger';
                    break;
                }
                
                try {
                    require_once('/docker/whp/web/libs/ApiKeyManager.php');
                    $apiKeyManager = new ApiKeyManager();
                    
                    $result = $apiKeyManager->cleanupExpiredTokens();
                    
                    if ($result['success']) {
                        $deletedCount = $result['deleted_count'];
                        $message = "Cleaned up $deletedCount expired SSO tokens";
                        $message_type = 'success';
                    } else {
                        $message = 'Failed to cleanup SSO tokens: ' . $result['error'];
                        $message_type = 'danger';
                    }
                } catch (Exception $e) {
                    $message = 'Error cleaning up SSO tokens: ' . $e->getMessage();
                    $message_type = 'danger';
                }
                break;

            case 'update_smtp_settings':
                $smtp_host = trim($_POST['smtp_host'] ?? '');
                $smtp_port = intval($_POST['smtp_port'] ?? 587);
                $smtp_encryption = $_POST['smtp_encryption'] ?? 'tls';
                $smtp_username = trim($_POST['smtp_username'] ?? '');
                $smtp_password = $_POST['smtp_password'] ?? '';
                $smtp_from_email = trim($_POST['smtp_from_email'] ?? '');
                $smtp_from_name = trim($_POST['smtp_from_name'] ?? 'WHP AI Monitor');
                $smtp_enabled = !empty($_POST['smtp_enabled']);

                // Validate required fields when enabling
                if ($smtp_enabled) {
                    if (empty($smtp_host)) {
                        $message = 'SMTP host is required';
                        $message_type = 'danger';
                        break;
                    }
                    if ($smtp_port < 1 || $smtp_port > 65535) {
                        $message = 'SMTP port must be between 1 and 65535';
                        $message_type = 'danger';
                        break;
                    }
                    if (!in_array($smtp_encryption, ['none', 'tls', 'ssl'])) {
                        $message = 'Invalid encryption type';
                        $message_type = 'danger';
                        break;
                    }
                    if (empty($smtp_from_email) || !filter_var($smtp_from_email, FILTER_VALIDATE_EMAIL)) {
                        $message = 'A valid From email address is required';
                        $message_type = 'danger';
                        break;
                    }
                }

                // Load existing config
                $config = [];
                if (file_exists('/docker/whp/settings.json')) {
                    $config = json_decode(file_get_contents('/docker/whp/settings.json'), true) ?: [];
                }

                // Encrypt password if provided, otherwise keep existing
                require_once('/docker/whp/web/libs/smtp_mailer.php');
                $encrypted_password = '';
                if (!empty($smtp_password) && $smtp_password !== '********') {
                    $encrypted_password = SmtpMailer::encryptPassword($smtp_password);
                } elseif (isset($config['smtp']['password'])) {
                    $encrypted_password = $config['smtp']['password'];
                }

                $config['smtp'] = [
                    'host' => $smtp_host,
                    'port' => $smtp_port,
                    'encryption' => $smtp_encryption,
                    'username' => $smtp_username,
                    'password' => $encrypted_password,
                    'from_email' => $smtp_from_email,
                    'from_name' => $smtp_from_name,
                    'enabled' => $smtp_enabled
                ];
                $config['updated_at'] = date('Y-m-d H:i:s');

                file_put_contents('/docker/whp/settings.json', json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
                chmod('/docker/whp/settings.json', 0600);

                $message = 'SMTP settings updated successfully';
                $message_type = 'success';
                break;

            case 'send_test_email':
                $test_email = trim($_POST['test_email'] ?? '');
                if (empty($test_email) || !filter_var($test_email, FILTER_VALIDATE_EMAIL)) {
                    $message = 'A valid test email address is required';
                    $message_type = 'danger';
                    break;
                }

                require_once('/docker/whp/web/libs/smtp_mailer.php');
                $result = SmtpMailer::sendTestEmail($test_email);
                if ($result['success']) {
                    $message = 'Test email sent successfully to ' . htmlspecialchars($test_email);
                    $message_type = 'success';
                } else {
                    $message = 'Failed to send test email: ' . htmlspecialchars($result['error']);
                    $message_type = 'danger';
                }
                break;
        }
    }
}

// Load current configuration
$current_config = [];
if (file_exists('/docker/whp/settings.json')) {
    $current_config = json_decode(file_get_contents('/docker/whp/settings.json'), true) ?: [];
}

// Load backup local storage config with actual disk usage
$backup_storage_config = ['max_size_gb' => 100, 'current_size_bytes' => 0];
try {
    require_once('/docker/whp/web/libs/BackupLocalStorage.php');
    $localStorage = new \WHPBackup\BackupLocalStorage();
    $spaceInfo = $localStorage->getSpaceInfo();
    $backup_storage_config = [
        'max_size_gb' => $spaceInfo['max_size_gb'],
        'current_size_bytes' => $spaceInfo['current_size_bytes']
    ];
} catch (Exception $e) {
    error_log("Error loading backup storage config: " . $e->getMessage());
    // Fallback to database value if BackupLocalStorage fails
    try {
        require_once('/docker/whp/web/libs/mysqlmgmt.php');
        $mysql = new \mysqlmgmt();
        $dbConn = $mysql->getMySQLConnection();
        $dbConn->exec("USE whp");
        $stmt = $dbConn->query("SELECT max_size_gb, current_size_bytes FROM backup_local_storage WHERE id = 1");
        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
        if ($row) {
            $backup_storage_config = $row;
        }
    } catch (Exception $e2) {
        error_log("Error loading backup storage fallback: " . $e2->getMessage());
    }
}

// Load API keys (root only)
$apiKeys = [];
if (defined('AUTH_USER') && AUTH_USER === 'root') {
    try {
        require_once('/docker/whp/web/libs/ApiKeyManager.php');
        $apiKeyManager = new ApiKeyManager();
        $apiKeysResult = $apiKeyManager->getApiKeys();
        if ($apiKeysResult['success']) {
            $apiKeys = $apiKeysResult['keys'];
        }
    } catch (Exception $e) {
        error_log("Error loading API keys: " . $e->getMessage());
    }
}

// Get current system information
$current_hostname = trim(shell_exec('hostname'));
$current_timezone = trim(shell_exec('timedatectl show --property=Timezone --value'));

// Get current nameservers
$current_nameservers = [];
if (file_exists('/etc/resolv.conf')) {
    $resolv_content = file_get_contents('/etc/resolv.conf');
    preg_match_all('/nameserver\s+([^\s]+)/', $resolv_content, $matches);
    $current_nameservers = $matches[1];
}

// Get system status
$service_status = [];
$services = ['httpd', 'php-fpm', 'docker', 'proftpd', 'whp-backup-upload'];
foreach ($services as $service) {
    $status = trim(shell_exec("systemctl is-active $service 2>/dev/null"));
    $service_status[$service] = $status;
}

//Get Server IP Address
require_once('/docker/whp/web/libs/dns_validator.php');
$dns_validator = new dns_validator();
$server_ip = $dns_validator->getServerIPAddress();

// Get Docker container status
$container_status = [];
$containers = ['mysql', 'haproxy-manager', 'memcache', 'postgresql'];
foreach ($containers as $container) {
    $status = trim(shell_exec("docker ps --filter name=$container --format '{{.Status}}' 2>/dev/null"));
    if (!empty($status)) {
        $container_status[$container] = 'running';
    } else {
        // Check if container exists but is stopped
        $exists = trim(shell_exec("docker ps -a --filter name=$container --format '{{.Names}}' 2>/dev/null"));
        $container_status[$container] = !empty($exists) ? 'stopped' : 'not_found';
    }
}

// Get shared-httpd instance status
$shared_httpd_instances = [];
$shared_httpd_output = trim(shell_exec("docker ps -a --filter 'name=shared-httpd-' --format '{{.Names}}|{{.Status}}' 2>/dev/null"));
if (!empty($shared_httpd_output)) {
    foreach (explode("\n", $shared_httpd_output) as $line) {
        $parts = explode('|', $line, 2);
        if (count($parts) === 2) {
            $shared_httpd_instances[trim($parts[0])] = strpos($parts[1], 'Up') !== false ? 'running' : 'stopped';
        }
    }
}
ksort($shared_httpd_instances);

// Load shared httpd settings from config
$shared_httpd_settings = $current_config['shared_httpd'] ?? [
    'default_mode' => 'standalone',
];

// Get system information
$system_info = [
    'uptime' => trim(shell_exec('uptime -p')),
    'load_avg' => trim(shell_exec('uptime | grep -oP "load average: \K[^;]+$"')),
    'disk_usage' => trim(shell_exec("df -h / | awk 'NR==2 {print $5}'")),
    'memory_usage' => trim(shell_exec("free | grep Mem | awk '{printf \"%.1f\", $3/$2 * 100.0}'")),
    'kernel' => trim(shell_exec('uname -r')),
    'os' => trim(shell_exec('cat /etc/redhat-release 2>/dev/null || cat /etc/os-release | grep PRETTY_NAME | cut -d"=" -f2 | tr -d \'"\''))
];



// Get available timezones (common ones)
$common_timezones = [
    'America/New_York',
    'America/Chicago',
    'America/Denver',
    'America/Los_Angeles',
    'America/Phoenix',
    'America/Anchorage',
    'Pacific/Honolulu',
    'Europe/London',
    'Europe/Paris',
    'Europe/Berlin',
    'Europe/Rome',
    'Asia/Tokyo',
    'Asia/Shanghai',
    'Asia/Kolkata',
    'Australia/Sydney',
    'UTC'
];

// Get DNS settings with defaults
$mail_server = $current_config['mail_server'] ?? 'mail.example.com';
        $mail_api_url = $current_config['mail_api_url'] ?? 'https://your-mail-server.com/admin/api/v1/';
$mail_api_username = $current_config['mail_api_username'] ?? 'your-api-username';
$mail_api_password = $current_config['mail_api_password'] ?? 'your-api-password';
$server_name = $current_config['server_name'] ?? 'WHP Server';
$server_description = $current_config['server_description'] ?? 'Web Hosting Panel Server';
$default_ttl = $current_config['default_ttl'] ?? 3600;
?>

<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 htmlspecialchars($message); ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- System Information -->
<div class="row">
    <div class="col-md-12">
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">System Information</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <table class="table table-sm">
                            <tr>
                                <td><strong>Hostname:</strong></td>
                                <td><?php echo htmlspecialchars($current_hostname); ?></td>
                            </tr>
                            <tr>
                                <td><strong>Operating System:</strong></td>
                                <td><?php echo htmlspecialchars($system_info['os']); ?></td>
                            </tr>
                            <tr>
                                <td><strong>Kernel:</strong></td>
                                <td><?php echo htmlspecialchars($system_info['kernel']); ?></td>
                            </tr>
                            <tr>
                                <td><strong>Timezone:</strong></td>
                                <td><?php echo htmlspecialchars($current_timezone); ?></td>
                            </tr>
                        </table>
                    </div>
                    <div class="col-md-6">
                        <table class="table table-sm">
                            <tr>
                                <td><strong>Uptime:</strong></td>
                                <td><?php echo htmlspecialchars($system_info['uptime']); ?></td>
                            </tr>
                            <tr>
                                <td><strong>Load Average:</strong></td>
                                <td><?php echo htmlspecialchars($system_info['load_avg']); ?></td>
                            </tr>
                            <tr>
                                <td><strong>Disk Usage:</strong></td>
                                <td><?php echo htmlspecialchars($system_info['disk_usage']); ?></td>
                            </tr>
                            <tr>
                                <td><strong>Memory Usage:</strong></td>
                                <td><?php echo htmlspecialchars($system_info['memory_usage']); ?>%</td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Service Status -->
<div class="row">
    <div class="col-md-12">
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">Service Status</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <?php
                    $service_display_names = [
                        'httpd' => 'Apache',
                        'php-fpm' => 'PHP-FPM',
                        'docker' => 'Docker',
                        'proftpd' => 'ProFTPD',
                        'whp-backup-upload' => 'Backup Upload',
                    ];
                    ?>
                    <?php foreach ($service_status as $service => $status): ?>
                    <div class="col-md-3 mb-3" data-service="<?php echo $service; ?>">
                        <div class="text-center">
                            <h6><?php echo $service_display_names[$service] ?? ucfirst($service); ?></h6>
                            <span class="badge <?php echo $status === 'active' ? 'bg-success' : 'bg-danger'; ?> fs-6">
                                <?php echo ucfirst($status ?: 'inactive'); ?>
                            </span>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                
                <hr>
                
                <form id="serviceRestartForm">
                    <input type="hidden" name="action" value="restart_services">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    <div class="mb-3">
                        <label class="form-label text-center d-block">Restart Services</label>
                        <div class="row justify-content-center">
                            <div class="col-auto">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="services[]" value="httpd" id="service-httpd">
                                    <label class="form-check-label" for="service-httpd">Apache (httpd)</label>
                                </div>
                            </div>
                            <div class="col-auto">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="services[]" value="php-fpm" id="service-php">
                                    <label class="form-check-label" for="service-php">PHP-FPM</label>
                                </div>
                            </div>
                            <div class="col-auto">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="services[]" value="docker" id="service-docker">
                                    <label class="form-check-label" for="service-docker">Docker</label>
                                </div>
                            </div>
                            <div class="col-auto">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="services[]" value="network" id="service-network">
                                    <label class="form-check-label" for="service-network">Network</label>
                                </div>
                            </div>
                            <div class="col-auto">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="services[]" value="proftpd" id="service-proftpd">
                                    <label class="form-check-label" for="service-proftpd">FTP (ProFTPD)</label>
                                </div>
                            </div>
                            <div class="col-auto">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="services[]" value="whp-backup-upload" id="service-whp-backup-upload">
                                    <label class="form-check-label" for="service-whp-backup-upload">Backup Upload</label>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="text-center">
                        <button type="submit" class="btn btn-warning" id="restartServicesBtn">
                            <i class="fa fa-refresh"></i> Restart Selected Services
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Docker Container Management -->
<div class="row">
    <div class="col-md-12">
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">Docker Container Management</h5>
            </div>
            <div class="card-body">
                <div class="row mb-3">
                    <?php foreach ($container_status as $container => $status): ?>
                    <div class="col-md-4 mb-3" data-container="<?php echo $container; ?>">
                        <div class="text-center">
                            <h6><?php echo ucfirst(str_replace('-', ' ', $container)); ?></h6>
                            <?php
                            $status_class = 'bg-success';
                            $status_text = 'Running';
                            if ($status === 'stopped') {
                                $status_class = 'bg-warning';
                                $status_text = 'Stopped';
                            } elseif ($status === 'not_found') {
                                $status_class = 'bg-danger';
                                $status_text = 'Not Found';
                            }
                            ?>
                            <span class="badge <?php echo $status_class; ?> fs-6">
                                <?php echo $status_text; ?>
                            </span>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                
                <hr>
                
                <form id="dockerContainerForm">
                    <input type="hidden" name="action" value="manage_docker_container">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    <div class="row">
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="container" class="form-label">Container</label>
                                <select class="form-control" id="container" name="container" required>
                                    <option value="">Select Container</option>
                                    <option value="mysql">MariaDB (mysql)</option>
                                    <option value="postgresql">PostgreSQL</option>
                                    <option value="haproxy-manager">HAProxy Manager</option>
                                    <option value="memcache">Memcache</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="operation" class="form-label">Operation</label>
                                <select class="form-control" id="operation" name="operation" required>
                                    <option value="">Select Operation</option>
                                    <option value="start">Start</option>
                                    <option value="stop">Stop</option>
                                    <option value="restart">Restart</option>
                                    <option value="pull_recreate">Pull Latest & Recreate</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label">&nbsp;</label>
                                <div>
                                    <button type="submit" class="btn btn-primary" id="executeDockerBtn">
                                        <i class="fa fa-cogs"></i> Execute Operation
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
                
                <div class="alert alert-info">
                    <i class="fa fa-info-circle"></i>
                    <strong>Note:</strong> 
                    <ul class="mb-0 mt-2">
                        <li><strong>Start/Stop/Restart:</strong> Controls the container state</li>
                        <li><strong>Pull Latest & Recreate:</strong> Downloads the latest image and recreates the container with current settings</li>
                        <li>All containers are configured to restart automatically unless stopped</li>
                        <li>MariaDB data is preserved in volumes during container operations</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Shared Apache Pool Management -->
<div class="row">
    <div class="col-md-12">
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">Shared Apache Pool</h5>
            </div>
            <div class="card-body">
                <!-- Instance Status -->
                <h6 class="mb-3">Running Instances</h6>
                <div class="row mb-3">
                    <?php if (empty($shared_httpd_instances)): ?>
                    <div class="col-12">
                        <span class="text-muted">No shared httpd instances running. Use Scale to start instances.</span>
                    </div>
                    <?php else: ?>
                    <?php foreach ($shared_httpd_instances as $name => $status): ?>
                    <div class="col-md-3 mb-2">
                        <div class="text-center">
                            <h6><?php echo htmlspecialchars($name); ?></h6>
                            <?php
                            $status_class = $status === 'running' ? 'bg-success' : 'bg-warning';
                            $status_text = $status === 'running' ? 'Running' : 'Stopped';
                            ?>
                            <span class="badge <?php echo $status_class; ?> fs-6"><?php echo $status_text; ?></span>
                        </div>
                    </div>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </div>

                <hr>

                <!-- Pool Operations -->
                <h6 class="mb-3">Pool Operations</h6>
                <form id="sharedHttpdForm">
                    <input type="hidden" name="action" value="manage_shared_httpd">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    <div class="row align-items-end">
                        <div class="col-md-3">
                            <div class="mb-3">
                                <label for="shared_httpd_scale_count" class="form-label">Instance Count</label>
                                <input type="number" class="form-control" id="shared_httpd_scale_count" name="instance_count"
                                       value="<?php echo count($shared_httpd_instances) ?: 1; ?>"
                                       min="0" max="10">
                            </div>
                        </div>
                        <div class="col-md-9">
                            <div class="mb-3 d-flex gap-2 flex-wrap">
                                <button type="submit" name="operation" value="scale" class="btn btn-primary shared-httpd-btn">
                                    <i class="fa fa-arrows-v"></i> Scale
                                </button>
                                <button type="submit" name="operation" value="restart_all" class="btn btn-warning shared-httpd-btn">
                                    <i class="fa fa-refresh"></i> Restart All
                                </button>
                                <button type="submit" name="operation" value="pull_recreate_all" class="btn btn-info shared-httpd-btn">
                                    <i class="fa fa-download"></i> Pull & Recreate All
                                </button>
                                <button type="submit" name="operation" value="stop_all" class="btn btn-danger shared-httpd-btn">
                                    <i class="fa fa-stop"></i> Stop All
                                </button>
                                <button type="submit" name="operation" value="start_all" class="btn btn-success shared-httpd-btn">
                                    <i class="fa fa-play"></i> Start All
                                </button>
                            </div>
                        </div>
                    </div>
                </form>

                <hr>

                <!-- Default Settings -->
                <h6 class="mb-3">Default Settings</h6>
                <form id="sharedHttpdSettingsForm">
                    <input type="hidden" name="action" value="update_shared_httpd_settings">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    <div class="row align-items-end">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="shared_httpd_default_mode" class="form-label">Default Mode for New PHP Sites</label>
                                <select class="form-control" id="shared_httpd_default_mode" name="default_mode">
                                    <option value="standalone" <?php echo ($shared_httpd_settings['default_mode'] === 'standalone') ? 'selected' : ''; ?>>Standalone (Apache+PHP per container)</option>
                                    <option value="shared_httpd" <?php echo ($shared_httpd_settings['default_mode'] === 'shared_httpd') ? 'selected' : ''; ?>>Shared Apache (PHP-FPM)</option>
                                </select>
                                <div class="form-text text-muted">Sets the default container mode when creating new PHP sites</div>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="mb-3">
                                <button type="submit" class="btn btn-primary" id="saveSharedHttpdSettingsBtn">
                                    <i class="fa fa-save"></i> Save
                                </button>
                            </div>
                        </div>
                    </div>
                </form>

                <div class="alert alert-info mt-2">
                    <i class="fa fa-info-circle"></i>
                    <strong>Note:</strong>
                    <ul class="mb-0 mt-2">
                        <li><strong>Scale:</strong> Adjusts the number of shared httpd instances (creates or removes as needed)</li>
                        <li><strong>Pull & Recreate All:</strong> Pulls the latest shared-httpd image and recreates all instances</li>
                        <li><strong>Default Mode:</strong> Controls whether new PHP sites default to shared Apache or standalone containers</li>
                        <li>All shared httpd instances share the same vhost configuration volume</li>
                        <li>HAProxy load-balances across all running instances automatically</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Configuration Settings -->
<div class="row">
    <div class="col-md-6">
        <!-- Hostname Settings -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">Hostname Settings</h5>
            </div>
            <div class="card-body">
                <form method="post">
                    <input type="hidden" name="action" value="update_hostname">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    
                    <div class="mb-3">
                        <label for="hostname" class="form-label">Server Hostname</label>
                        <input type="text" class="form-control" id="hostname" name="hostname" 
                               value="<?php echo htmlspecialchars($current_hostname); ?>" 
                               placeholder="server.example.com" required>
                        <div class="form-text text-muted">The server's hostname (FQDN recommended)</div>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">
                        <i class="fa fa-save"></i> Update Hostname
                    </button>
                </form>
            </div>
        </div>
        
        <!-- Timezone Settings -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">Timezone Settings</h5>
            </div>
            <div class="card-body">
                <form method="post">
                    <input type="hidden" name="action" value="update_timezone">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    
                    <div class="mb-3">
                        <label for="timezone" class="form-label">System Timezone</label>
                        <select class="form-control" id="timezone" name="timezone" required>
                            <?php foreach ($common_timezones as $tz): ?>
                            <option value="<?php echo $tz; ?>" <?php echo $tz === $current_timezone ? 'selected' : ''; ?>>
                                <?php echo $tz; ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                        <div class="form-text text-muted">Current timezone: <?php echo htmlspecialchars($current_timezone); ?></div>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">
                        <i class="fa fa-save"></i> Update Timezone
                    </button>
                </form>
            </div>
        </div>

        <!-- Backup Settings -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">Backup Settings</h5>
            </div>
            <div class="card-body">
                <p class="text-muted small">Configure backup system performance settings to prevent server overload.</p>

                <form method="post">
                    <input type="hidden" name="action" value="update_backup_settings">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">

                    <div class="mb-3">
                        <label for="max_concurrent_backups" class="form-label">Maximum Concurrent Backups</label>
                        <input type="number" class="form-control" id="max_concurrent_backups" name="max_concurrent_backups"
                               value="<?php echo intval($current_config['backup_max_concurrent'] ?? 2); ?>"
                               min="1" max="10" required>
                        <div class="form-text text-muted">Number of backup jobs that can run simultaneously (1-10). Default: 2</div>
                    </div>

                    <div class="mb-3">
                        <label for="backup_upload_space_gb" class="form-label">Backup Local Storage Limit (GB)</label>
                        <input type="number" class="form-control" id="backup_upload_space_gb" name="backup_upload_space_gb"
                               value="<?php echo intval($backup_storage_config['max_size_gb']); ?>"
                               min="10" max="10000" required>
                        <div class="form-text text-muted">Maximum disk space for local backup staging (10-10,000 GB). Default: 100</div>
                        <?php
                            $current_bytes = intval($backup_storage_config['current_size_bytes']);
                            $max_bytes = intval($backup_storage_config['max_size_gb']) * 1073741824;
                            $usage_pct = $max_bytes > 0 ? round(($current_bytes / $max_bytes) * 100, 1) : 0;
                            $current_gb = round($current_bytes / 1073741824, 2);
                        ?>
                        <div class="form-text text-muted">
                            Current usage: <?php echo $current_gb; ?> GB / <?php echo intval($backup_storage_config['max_size_gb']); ?> GB (<?php echo $usage_pct; ?>%)
                        </div>
                    </div>

                    <button type="submit" class="btn btn-primary">
                        <i class="fa fa-save"></i> Update Backup Settings
                    </button>
                </form>

                <hr>

                <div class="small text-muted">
                    <strong>Note:</strong> Lowering the concurrent backups number reduces server load but increases backup queue time.
                    The local storage limit controls how much disk space is reserved for backup files awaiting upload to remote storage.
                </div>
            </div>
        </div>

        <!-- Outbound Email (SMTP) Settings -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">Outbound Email (SMTP)</h5>
            </div>
            <div class="card-body">
                <p class="text-muted small">Configure SMTP for customer AI monitoring email notifications and system alerts.</p>

                <?php
                $smtp_config = $current_config['smtp'] ?? [];
                $smtp_enabled = !empty($smtp_config['enabled']);
                $smtp_host = $smtp_config['host'] ?? '';
                $smtp_port = $smtp_config['port'] ?? 587;
                $smtp_encryption = $smtp_config['encryption'] ?? 'tls';
                $smtp_username = $smtp_config['username'] ?? '';
                $smtp_has_password = !empty($smtp_config['password']);
                $smtp_from_email = $smtp_config['from_email'] ?? '';
                $smtp_from_name = $smtp_config['from_name'] ?? 'WHP AI Monitor';
                ?>

                <form method="post">
                    <input type="hidden" name="action" value="update_smtp_settings">
                    <?php if (isset($_SESSION['csrf_token'])): ?>
                    <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                    <?php endif; ?>

                    <div class="form-check form-switch mb-3">
                        <input class="form-check-input" type="checkbox" id="smtp_enabled" name="smtp_enabled" value="1" <?php echo $smtp_enabled ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="smtp_enabled">Enable Outbound Email</label>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="smtp_host" class="form-label">SMTP Host</label>
                            <input type="text" class="form-control" id="smtp_host" name="smtp_host" value="<?php echo htmlspecialchars($smtp_host); ?>" placeholder="smtp.example.com">
                        </div>
                        <div class="col-md-3">
                            <label for="smtp_port" class="form-label">Port</label>
                            <input type="number" class="form-control" id="smtp_port" name="smtp_port" value="<?php echo intval($smtp_port); ?>" min="1" max="65535">
                        </div>
                        <div class="col-md-3">
                            <label for="smtp_encryption" class="form-label">Encryption</label>
                            <select class="form-select" id="smtp_encryption" name="smtp_encryption">
                                <option value="tls" <?php echo $smtp_encryption === 'tls' ? 'selected' : ''; ?>>TLS (STARTTLS)</option>
                                <option value="ssl" <?php echo $smtp_encryption === 'ssl' ? 'selected' : ''; ?>>SSL</option>
                                <option value="none" <?php echo $smtp_encryption === 'none' ? 'selected' : ''; ?>>None</option>
                            </select>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="smtp_username" class="form-label">Username</label>
                            <input type="text" class="form-control" id="smtp_username" name="smtp_username" value="<?php echo htmlspecialchars($smtp_username); ?>" placeholder="user@example.com">
                        </div>
                        <div class="col-md-6">
                            <label for="smtp_password" class="form-label">Password</label>
                            <input type="password" class="form-control" id="smtp_password" name="smtp_password" value="<?php echo $smtp_has_password ? '********' : ''; ?>" placeholder="<?php echo $smtp_has_password ? 'Password saved (leave blank to keep)' : 'Enter password'; ?>">
                            <?php if ($smtp_has_password): ?>
                            <div class="form-text text-muted">Leave blank to keep existing password</div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="smtp_from_email" class="form-label">From Email</label>
                            <input type="email" class="form-control" id="smtp_from_email" name="smtp_from_email" value="<?php echo htmlspecialchars($smtp_from_email); ?>" placeholder="noreply@example.com">
                        </div>
                        <div class="col-md-6">
                            <label for="smtp_from_name" class="form-label">From Name</label>
                            <input type="text" class="form-control" id="smtp_from_name" name="smtp_from_name" value="<?php echo htmlspecialchars($smtp_from_name); ?>" placeholder="WHP AI Monitor">
                        </div>
                    </div>

                    <button type="submit" class="btn btn-primary">
                        <i class="fa fa-save"></i> Save SMTP Settings
                    </button>
                </form>

                <?php if ($smtp_enabled && !empty($smtp_host)): ?>
                <hr>
                <form method="post" class="d-inline-flex align-items-end gap-2">
                    <input type="hidden" name="action" value="send_test_email">
                    <?php if (isset($_SESSION['csrf_token'])): ?>
                    <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                    <?php endif; ?>
                    <div>
                        <label for="test_email" class="form-label">Send Test Email</label>
                        <input type="email" class="form-control" id="test_email" name="test_email" placeholder="test@example.com" required>
                    </div>
                    <button type="submit" class="btn btn-outline-secondary">
                        <i class="fa fa-paper-plane"></i> Send Test
                    </button>
                </form>
                <?php endif; ?>
            </div>
        </div>

        <!-- HAProxy API Key Settings -->
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">HAProxy API Key</h5>
            </div>
            <div class="card-body">
                <p class="text-muted small">Configure the API key for HAProxy Manager authentication. This key will be used as a bearer token.</p>
                
                <form method="post">
                    <input type="hidden" name="action" value="update_haproxy_api_key">
                    
                    <div class="mb-3">
                        <label for="haproxy_api_key" class="form-label">API Key</label>
                        <input type="text" class="form-control" id="haproxy_api_key" name="haproxy_api_key" 
                               value="<?php echo htmlspecialchars($current_config['haproxy_api_key'] ?? ''); ?>" 
                               placeholder="your-secure-api-key-here" minlength="16" required>
                        <div class="form-text text-muted">Minimum 16 characters. Used as bearer token for HAProxy Manager API access.</div>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">
                        <i class="fa fa-save"></i> Update API Key
                    </button>
                </form>
                
                <hr>
                
                <div class="small text-muted">
                    <strong>Note:</strong> After updating the API key, restart the HAProxy container to apply the changes.
                </div>
            </div>
        </div>
    </div>
    
    <!-- HAProxy Configuration Management -->
    <div class="col-md-6">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">HAProxy Configuration Management</h5>
            </div>
            <div class="card-body">
                <p class="text-muted small">Manage HAProxy configuration and monitor health status.</p>
                
                <div class="d-grid gap-2">
                    <form method="post" class="d-inline">
                        <input type="hidden" name="action" value="haproxy_regenerate_config">
                        <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fa fa-cog"></i> Regenerate Configuration
                        </button>
                    </form>
                    
                    <form method="post" class="d-inline">
                        <input type="hidden" name="action" value="haproxy_reload_config">
                        <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                        <button type="submit" class="btn btn-warning w-100">
                            <i class="fa fa-refresh"></i> Reload Configuration
                        </button>
                    </form>
                    
                    <form method="post" class="d-inline">
                        <input type="hidden" name="action" value="haproxy_health_check">
                        <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                        <button type="submit" class="btn btn-info w-100">
                            <i class="fa fa-heart"></i> Health Check
                        </button>
                    </form>
                </div>
                
                <hr>
                
                <div class="small text-muted">
                    <strong>Functions:</strong><br>
                    <strong>Regenerate:</strong> Rebuild HAProxy configuration for all active sites<br>
                    <strong>Reload:</strong> Reload HAProxy configuration without restarting<br>
                    <strong>Health Check:</strong> Check HAProxy service health status
                </div>
            </div>
        </div>
    </div>
    
    <!-- System Service SSL Management -->
    <div class="col-md-6">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">System Service SSL Certificates</h5>
            </div>
            <div class="card-body">
                <p class="text-muted small">Enable SSL certificates for system services like HTTP and FTP.</p>
                
                <form method="post">
                    <input type="hidden" name="action" value="enable_system_service_ssl">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    
                    <div class="mb-3">
                        <label for="service_name" class="form-label">Service</label>
                        <select class="form-control" id="service_name" name="service_name" required>
                            <option value="">Select Service</option>
                            <option value="httpd">Apache HTTP Server</option>
                            <option value="proftpd">ProFTPD Server</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label for="domain_name" class="form-label">Domain Name</label>
                        <input type="text" class="form-control" id="domain_name" name="domain_name" 
                               placeholder="example.com" required>
                        <div class="form-text text-muted">Domain name for the SSL certificate</div>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">
                        <i class="fa fa-lock"></i> Enable SSL
                    </button>
                </form>
                
                <hr>
                
                <?php
                // Display current system service SSL certificates
                try {
                    require_once('/docker/whp/web/libs/ssl_manager.php');
                    $ssl_manager = new ssl_manager();
                    $system_certs = $ssl_manager->getSystemServiceSSLCertificates();
                    
                    if (!empty($system_certs)) {
                        echo '<div class="small">';
                        echo '<strong>Current SSL Certificates:</strong><br>';
                        foreach ($system_certs as $cert) {
                            $status_class = $cert['ssl_enabled'] ? 'text-success' : 'text-muted';
                            $status_text = $cert['ssl_enabled'] ? 'Enabled' : 'Disabled';
                            echo '<div class="' . $status_class . '">';
                            echo '<i class="fa fa-' . ($cert['ssl_enabled'] ? 'lock' : 'unlock') . '"></i> ';
                            echo htmlspecialchars($cert['service_name']) . ' - ' . htmlspecialchars($cert['domain_name']) . ' (' . $status_text . ')';
                            echo '</div>';
                        }
                        echo '</div>';
                    } else {
                        echo '<div class="small text-muted">No system service SSL certificates configured</div>';
                    }
                } catch (Exception $e) {
                    echo '<div class="small text-danger">Error loading SSL certificates: ' . htmlspecialchars($e->getMessage()) . '</div>';
                }
                ?>
            </div>
        </div>
    </div>
    
    <div class="col-md-6">
        <!-- WHP Nameserver Settings -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">WHP Nameserver Configuration</h5>
            </div>
            <div class="card-body">
                <p class="text-muted small">Configure the nameserver hostnames and IP addresses that WHP will use for customer domain configurations.</p>
                
                <form method="post">
                    <input type="hidden" name="action" value="update_whp_nameservers">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="whp_ns1" class="form-label">Primary Nameserver Hostname</label>
                                <input type="text" class="form-control" id="whp_ns1" name="whp_ns1" 
                                       value="<?php echo htmlspecialchars($current_config['whp_nameservers']['ns1'] ?? 'ns1.example.com'); ?>" 
                                       placeholder="ns1.yourdomain.com" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="whp_ns1_ip" class="form-label">Primary Nameserver IP</label>
                                <input type="text" class="form-control" id="whp_ns1_ip" name="whp_ns1_ip" 
                                       value="<?php echo htmlspecialchars($current_config['whp_nameservers']['ns1_ip'] ?? $server_ip); ?>" 
                                       placeholder="<?php echo $server_ip; ?>" required>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="whp_ns2" class="form-label">Secondary Nameserver Hostname</label>
                                <input type="text" class="form-control" id="whp_ns2" name="whp_ns2" 
                                       value="<?php echo htmlspecialchars($current_config['whp_nameservers']['ns2'] ?? 'ns2.example.com'); ?>" 
                                       placeholder="ns2.yourdomain.com" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="whp_ns2_ip" class="form-label">Secondary Nameserver IP</label>
                                <input type="text" class="form-control" id="whp_ns2_ip" name="whp_ns2_ip" 
                                       value="<?php echo htmlspecialchars($current_config['whp_nameservers']['ns2_ip'] ?? $server_ip); ?>" 
                                       placeholder="<?php echo $server_ip; ?>" required>
                            </div>
                        </div>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">
                        <i class="fa fa-save"></i> Update WHP Nameservers
                    </button>
                </form>
                
                <hr>
                
                <div class="small text-muted">
                    <strong>Note:</strong> These hostnames and IP addresses will be used when configuring DNS zones for customer domains. Make sure these hostnames point to the specified IP addresses.
                </div>
            </div>
        </div>
        
        <!-- DNS Settings -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">Network DNS Settings</h5>
            </div>
            <div class="card-body">
                <form method="post">
                    <input type="hidden" name="action" value="update_nameservers">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    
                    <div class="mb-3">
                        <label for="nameserver1" class="form-label">Primary Nameserver</label>
                        <input type="text" class="form-control" id="nameserver1" name="nameserver1" 
                               value="<?php echo htmlspecialchars($current_nameservers[0] ?? '8.8.8.8'); ?>" 
                               placeholder="8.8.8.8" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="nameserver2" class="form-label">Secondary Nameserver</label>
                        <input type="text" class="form-control" id="nameserver2" name="nameserver2" 
                               value="<?php echo htmlspecialchars($current_nameservers[1] ?? '8.8.4.4'); ?>" 
                               placeholder="8.8.4.4">
                    </div>
                    
                    <button type="submit" class="btn btn-primary">
                        <i class="fa fa-save"></i> Update Nameservers
                    </button>
                </form>
                
                <hr>
                
                <div class="small text-muted">
                    <strong>Common DNS Providers:</strong><br>
                    <strong>Google:</strong> 8.8.8.8, 8.8.4.4<br>
                    <strong>Cloudflare:</strong> 1.1.1.1, 1.0.0.1<br>
                    <strong>Quad9:</strong> 9.9.9.9, 149.112.112.112<br>
                    <strong>OpenDNS:</strong> 208.67.222.222, 208.67.220.220
                </div>
            </div>
        </div>
        
        <!-- DNS Configuration Settings -->
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">DNS Configuration Settings</h5>
            </div>
            <div class="card-body">
                <p class="text-muted small">Configure DNS settings that affect customer domains and email services.</p>
                
                <form method="post">
                    <input type="hidden" name="action" value="update_dns_settings">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    
                    <div class="mb-3">
                        <label for="mail_server" class="form-label">Mail Server Hostname</label>
                                                <input type="text" class="form-control" id="mail_server" name="mail_server"
                               value="<?php echo ($mail_server !== 'mail.example.com') ? htmlspecialchars($mail_server) : ''; ?>"
                               placeholder="mail.example.com" required>
                        <div class="form-text text-muted">This will be used for MX records on new domains</div>
                    </div>
                    
                    <hr>
                    
                    <h6 class="mb-3">Mail Server API Configuration</h6>
                    
                    <div class="mb-3">
                        <label for="mail_api_url" class="form-label">Mail API URL</label>
                        <input type="url" class="form-control" id="mail_api_url" name="mail_api_url" 
                               value="<?php echo ($mail_api_url !== 'https://your-mail-server.com/admin/api/v1/') ? htmlspecialchars($mail_api_url) : ''; ?>" 
                               placeholder="https://your-mail-server.com/admin/api/v1/" required>
                        <div class="form-text text-muted">API endpoint for mail server management</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="mail_api_username" class="form-label">Mail API Username</label>
                        <input type="text" class="form-control" id="mail_api_username" name="mail_api_username" 
                               value="<?php echo ($mail_api_username !== 'your-api-username') ? htmlspecialchars($mail_api_username) : ''; ?>" 
                               placeholder="your-api-username" required>
                        <div class="form-text text-muted">Username for mail server API authentication</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="mail_api_password" class="form-label">Mail API Password</label>
                        <input type="password" class="form-control" id="mail_api_password" name="mail_api_password" 
                               value="<?php echo ($mail_api_password !== 'your-api-password') ? htmlspecialchars($mail_api_password) : ''; ?>" 
                               placeholder="Enter mail server API password" required>
                        <div class="form-text text-muted">Password for mail server API authentication</div>
                    </div>
                    
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" id="mailserver_debug_log" name="mailserver_debug_log" value="1" <?php if (!empty($current_config['mailserver_debug_log'])) echo 'checked'; ?>>
                        <label class="form-check-label" for="mailserver_debug_log">
                            Enable Mailserver API Debug Logging
                        </label>
                        <div class="form-text text-muted">Log all mailserver API requests and responses to the PHP error log for troubleshooting.</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="default_ttl" class="form-label">Default TTL (seconds)</label>
                        <input type="number" class="form-control" id="default_ttl" name="default_ttl" 
                               value="<?php echo $default_ttl; ?>" min="60" max="86400" required>
                        <div class="form-text text-muted">Default TTL for new DNS records (60-86400 seconds)</div>
                    </div>
                    
                    <hr>
                    
                    <h6 class="mb-3">Server Information</h6>
                    
                    <div class="mb-3">
                        <label for="server_name" class="form-label">Server Name</label>
                        <input type="text" class="form-control" id="server_name" name="server_name" 
                               value="<?php echo htmlspecialchars($server_name); ?>" 
                               placeholder="WHP Server" required>
                        <div class="form-text text-muted">Display name for this server</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="server_description" class="form-label">Server Description</label>
                        <textarea class="form-control" id="server_description" name="server_description" rows="3"><?php echo htmlspecialchars($server_description); ?></textarea>
                        <div class="form-text text-muted">Description of this server</div>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">
                        <i class="fa fa-save"></i> Update DNS Settings
                    </button>
                </form>
                
                <hr>
                
                <div class="small text-muted">
                    <strong>Note:</strong> These settings affect all new domains. Mail server hostname is used for MX records, and TTL is the default time-to-live for DNS records.
                </div>
            </div>
        </div>
    </div>
</div>

<?php if (defined('AUTH_USER') && AUTH_USER === 'root'): ?>
<!-- API Key Management (Root Only) -->
<div class="row">
    <div class="col-md-12">
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">API Key Management</h5>
                <p class="text-muted small mb-0">Manage API keys for external integrations like WHMCS</p>
            </div>
            <div class="card-body">
                
                <!-- Display new API key if just created -->
                <?php if (isset($_SESSION['new_api_key']) && isset($_SESSION['new_api_secret'])): ?>
                <div class="alert alert-success alert-dismissible">
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    <h5><i class="fa fa-check-circle"></i> API Key Created Successfully</h5>
                    <p><strong>API Key:</strong> <code><?php echo htmlspecialchars($_SESSION['new_api_key']); ?></code></p>
                    <p><strong>API Secret:</strong> <code id="api-secret-display"><?php echo htmlspecialchars($_SESSION['new_api_secret']); ?></code>
                    <button type="button" class="btn btn-sm btn-outline-secondary ms-2" onclick="copyToClipboard('api-secret-display')">
                        <i class="fa fa-copy"></i> Copy
                    </button></p>
                    <p class="text-danger"><strong>Important:</strong> Please copy the API secret now. It will not be shown again for security reasons.</p>
                </div>
                <?php 
                // Clear the session variables after displaying
                unset($_SESSION['new_api_key'], $_SESSION['new_api_secret']);
                endif; 
                ?>
                
                <!-- Create New API Key Form -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h6 class="card-title mb-0">Create New API Key</h6>
                    </div>
                    <div class="card-body">
                        <form method="post">
                            <input type="hidden" name="action" value="create_api_key">
                            <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="key_name" class="form-label">Key Name</label>
                                        <input type="text" class="form-control" id="key_name" name="key_name" 
                                               placeholder="WHMCS Integration Key" required>
                                        <div class="form-text text-muted">Descriptive name for this API key</div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="rate_limit" class="form-label">Rate Limit (per hour)</label>
                                        <input type="number" class="form-control" id="rate_limit" name="rate_limit" 
                                               value="1000" min="1" max="10000">
                                        <div class="form-text text-muted">Maximum API requests per hour</div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Permissions</label>
                                <div class="row">
                                    <div class="col-md-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="permissions[user_management]" value="1" id="perm-user">
                                            <label class="form-check-label" for="perm-user">User Management</label>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="permissions[resource_management]" value="1" id="perm-resources">
                                            <label class="form-check-label" for="perm-resources">Resource Management</label>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="permissions[sso_access]" value="1" id="perm-sso">
                                            <label class="form-check-label" for="perm-sso">SSO Access</label>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="permissions[system_stats]" value="1" id="perm-stats">
                                            <label class="form-check-label" for="perm-stats">System Statistics</label>
                                        </div>
                                    </div>
                                </div>
                                <div class="row mt-2">
                                    <div class="col-md-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="permissions[ai_monitor_management]" value="1" id="perm-ai-monitor">
                                            <label class="form-check-label" for="perm-ai-monitor">AI Monitor Management</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="ip_whitelist" class="form-label">IP Whitelist (optional)</label>
                                <input type="text" class="form-control" id="ip_whitelist" name="ip_whitelist" 
                                       placeholder="192.168.1.100, 10.0.0.50">
                                <div class="form-text text-muted">Comma-separated list of allowed IP addresses (leave empty for no restrictions)</div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="notes" class="form-label">Notes (optional)</label>
                                <textarea class="form-control" id="notes" name="notes" rows="2" 
                                          placeholder="Additional notes about this API key"></textarea>
                            </div>
                            
                            <button type="submit" class="btn btn-primary">
                                <i class="fa fa-plus"></i> Create API Key
                            </button>
                        </form>
                    </div>
                </div>
                
                <!-- Existing API Keys -->
                <div class="card">
                    <div class="card-header">
                        <h6 class="card-title mb-0">Existing API Keys</h6>
                    </div>
                    <div class="card-body">
                        <?php if (!empty($apiKeys)): ?>
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Name</th>
                                        <th>API Key</th>
                                        <th>Permissions</th>
                                        <th>Rate Limit</th>
                                        <th>Status</th>
                                        <th>Last Used</th>
                                        <th>Usage Count</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($apiKeys as $key): ?>
                                    <tr>
                                        <td>
                                            <strong><?php echo htmlspecialchars($key['key_name']); ?></strong>
                                            <?php if ($key['notes']): ?>
                                            <br><small class="text-muted"><?php echo htmlspecialchars($key['notes']); ?></small>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <code class="small"><?php echo htmlspecialchars(substr($key['api_key'], 0, 20) . '...'); ?></code>
                                            <button type="button" class="btn btn-sm btn-outline-secondary ms-1" 
                                                    onclick="copyToClipboard('<?php echo htmlspecialchars($key['api_key']); ?>')">
                                                <i class="fa fa-copy"></i>
                                            </button>
                                        </td>
                                        <td>
                                            <?php if (!empty($key['permissions'])): ?>
                                                <?php foreach ($key['permissions'] as $perm => $enabled): ?>
                                                    <?php if ($enabled): ?>
                                                        <span class="badge bg-info me-1"><?php echo ucwords(str_replace('_', ' ', $perm)); ?></span>
                                                    <?php endif; ?>
                                                <?php endforeach; ?>
                                            <?php else: ?>
                                                <span class="text-muted">None</span>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo number_format($key['rate_limit_per_hour']); ?>/hour</td>
                                        <td>
                                            <span class="badge <?php echo $key['is_active'] ? 'bg-success' : 'bg-danger'; ?>">
                                                <?php echo $key['is_active'] ? 'Active' : 'Inactive'; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php if ($key['last_used_at']): ?>
                                                <small><?php echo date('M j, Y g:i A', strtotime($key['last_used_at'])); ?></small>
                                            <?php else: ?>
                                                <small class="text-muted">Never</small>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo number_format($key['usage_count']); ?></td>
                                        <td>
                                            <?php if ($key['is_active']): ?>
                                            <form method="post" class="d-inline" onsubmit="return confirm('Are you sure you want to deactivate this API key?');">
                                                <input type="hidden" name="action" value="deactivate_api_key">
                                                <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                                                <input type="hidden" name="key_id" value="<?php echo $key['id']; ?>">
                                                <button type="submit" class="btn btn-sm btn-outline-danger">
                                                    <i class="fa fa-times"></i> Deactivate
                                                </button>
                                            </form>
                                            <?php else: ?>
                                                <span class="text-muted small">Deactivated</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        <?php else: ?>
                        <div class="text-center text-muted py-4">
                            <i class="fa fa-key fa-3x mb-3"></i>
                            <h5>No API Keys</h5>
                            <p>Create your first API key to enable external integrations.</p>
                        </div>
                        <?php endif; ?>
                        
                        <!-- Utility Actions -->
                        <hr>
                        <div class="d-flex gap-2">
                            <form method="post" class="d-inline">
                                <input type="hidden" name="action" value="cleanup_sso_tokens">
                                <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                                <button type="submit" class="btn btn-sm btn-outline-warning">
                                    <i class="fa fa-trash"></i> Cleanup Expired SSO Tokens
                                </button>
                            </form>
                        </div>
                        
                        <div class="mt-3">
                            <small class="text-muted">
                                <strong>API Usage:</strong><br>
                                • <strong>User Management:</strong> Create, delete, and modify user accounts<br>
                                • <strong>Resource Management:</strong> Update user resource limits and quotas<br>
                                • <strong>SSO Access:</strong> Generate single sign-on tokens for auto-login<br>
                                • <strong>System Statistics:</strong> Access server stats and health information<br>
                                • API keys are used with X-API-Key and X-API-Secret headers<br>
                                • Documentation: <code>/api/external/</code> endpoints
                            </small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<script>
// Bootstrap 5 toast notification function
function showToast(message, type = 'success') {
    // Create toast container if it doesn't exist
    let toastContainer = document.getElementById('toast-container');
    if (!toastContainer) {
        toastContainer = document.createElement('div');
        toastContainer.id = 'toast-container';
        toastContainer.className = 'toast-container position-fixed bottom-0 end-0 p-3';
        toastContainer.style.zIndex = '1055';
        document.body.appendChild(toastContainer);
    }
    
    // Create toast HTML
    const toastId = 'toast-' + Date.now();
    const iconClass = type === 'success' ? 'fa-check-circle text-success' : 
                     type === 'danger' ? 'fa-exclamation-triangle text-danger' : 
                     'fa-info-circle text-info';
    
    const toastHTML = `
        <div id="${toastId}" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="toast-header">
                <i class="fa ${iconClass} me-2"></i>
                <strong class="me-auto">Notification</strong>
                <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
            <div class="toast-body">
                ${message}
            </div>
        </div>
    `;
    
    // Add toast to container
    toastContainer.insertAdjacentHTML('beforeend', toastHTML);
    
    // Initialize and show toast
    const toastElement = document.getElementById(toastId);
    const toast = new bootstrap.Toast(toastElement, {
        autohide: true,
        delay: 3000
    });
    
    // Remove toast element after it's hidden
    toastElement.addEventListener('hidden.bs.toast', function() {
        toastElement.remove();
    });
    
    toast.show();
}

// Copy to clipboard function with fallback
function copyToClipboard(text) {
    if (typeof text !== 'string') {
        // If text is an element ID, get the text content
        const element = document.getElementById(text);
        text = element ? element.textContent : text;
    }
    
    // Check if modern clipboard API is available and we're in secure context
    if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(text).then(function() {
            showToast('Copied to clipboard!', 'success');
        }).catch(function(err) {
            console.error('Clipboard API failed: ', err);
            fallbackCopyToClipboard(text);
        });
    } else {
        // Fallback for older browsers or non-HTTPS
        fallbackCopyToClipboard(text);
    }
}

// Fallback copy method using execCommand
function fallbackCopyToClipboard(text) {
    const textArea = document.createElement('textarea');
    textArea.value = text;
    textArea.style.position = 'fixed';
    textArea.style.left = '-999999px';
    textArea.style.top = '-999999px';
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    
    try {
        const successful = document.execCommand('copy');
        if (successful) {
            showToast('Copied to clipboard!', 'success');
        } else {
            showToast('Failed to copy to clipboard', 'danger');
        }
    } catch (err) {
        console.error('Fallback copy failed: ', err);
        showToast('Copy to clipboard not supported in this browser', 'danger');
    } finally {
        document.body.removeChild(textArea);
    }
}
</script>

<script>
// AJAX-based service management
document.addEventListener('DOMContentLoaded', function() {
    // CSRF token for AJAX requests
    const csrfToken = '<?php echo get_csrf_token(); ?>';
    
    // Service restart form handling
    const serviceRestartForm = document.getElementById('serviceRestartForm');
    if (serviceRestartForm) {
        serviceRestartForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const checkedServices = this.querySelectorAll('input[name="services[]"]:checked');
            if (checkedServices.length === 0) {
                showAlert('Please select at least one service to restart.', 'warning');
                return;
            }
            
            if (!confirm('Are you sure you want to restart the selected services? This may cause temporary service interruption.')) {
                return;
            }
            
            const formData = new FormData(this);
            const submitBtn = document.getElementById('restartServicesBtn');
            const originalText = submitBtn.innerHTML;
            
            // Show loading state
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Restarting...';
            
            // Make AJAX request
            fetch('index.php?page=server-settings', {
                method: 'POST',
                headers: {
                    'X-CSRF-Token': csrfToken
                },
                body: formData
            })
            .then(response => response.text())
            .then(data => {
                // Parse the response to extract message
                const parser = new DOMParser();
                const doc = parser.parseFromString(data, 'text/html');
                const alertElement = doc.querySelector('.alert');
                
                if (alertElement) {
                    const message = alertElement.textContent.trim();
                    const alertClass = alertElement.className.includes('alert-success') ? 'success' : 
                                     alertElement.className.includes('alert-danger') ? 'danger' : 'info';
                    showAlert(message, alertClass);
                    
                    if (alertClass === 'success') {
                        // Update service status after successful restart
                        setTimeout(updateServiceStatus, 2000);
                    }
                } else {
                    showAlert('Service restart completed. Status will update shortly.', 'success');
                    setTimeout(updateServiceStatus, 2000);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showAlert('An error occurred while restarting services.', 'danger');
            })
            .finally(() => {
                // Restore button state
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            });
        });
    }
    
    // Docker container form handling
    const dockerContainerForm = document.getElementById('dockerContainerForm');
    if (dockerContainerForm) {
        dockerContainerForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const container = this.querySelector('select[name="container"]').value;
            const operation = this.querySelector('select[name="operation"]').value;
            
            if (!container || !operation) {
                showAlert('Please select both container and operation.', 'warning');
                return;
            }
            
            let message = `Are you sure you want to ${operation} the ${container} container?`;
            if (operation === 'pull_recreate') {
                message = `Are you sure you want to pull the latest image and recreate the ${container} container? This will stop the current container and start a new one.`;
            }
            
            if (!confirm(message)) {
                return;
            }
            
            const formData = new FormData(this);
            const submitBtn = document.getElementById('executeDockerBtn');
            const originalText = submitBtn.innerHTML;
            
            // Show loading state
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Executing...';
            
            // Make AJAX request
            fetch('index.php?page=server-settings', {
                method: 'POST',
                headers: {
                    'X-CSRF-Token': csrfToken
                },
                body: formData
            })
            .then(response => response.text())
            .then(data => {
                // Parse the response to extract message
                const parser = new DOMParser();
                const doc = parser.parseFromString(data, 'text/html');
                const alertElement = doc.querySelector('.alert');
                
                if (alertElement) {
                    const message = alertElement.textContent.trim();
                    const alertClass = alertElement.className.includes('alert-success') ? 'success' : 
                                     alertElement.className.includes('alert-danger') ? 'danger' : 'info';
                    showAlert(message, alertClass);
                    
                    if (alertClass === 'success') {
                        // Update container status after successful operation
                        setTimeout(updateContainerStatus, 2000);
                    }
                } else {
                    showAlert('Container operation completed. Status will update shortly.', 'success');
                    setTimeout(updateContainerStatus, 2000);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showAlert('An error occurred while executing container operation.', 'danger');
            })
            .finally(() => {
                // Restore button state
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
                
                // Reset form
                this.reset();
            });
        });
    }

    // Shared httpd pool operations form
    const sharedHttpdForm = document.getElementById('sharedHttpdForm');
    if (sharedHttpdForm) {
        sharedHttpdForm.addEventListener('submit', function(e) {
            e.preventDefault();

            // Find which button was clicked
            const clickedBtn = e.submitter;
            if (!clickedBtn) return;

            const operation = clickedBtn.value;
            const operationLabels = {
                'scale': 'scale the shared httpd pool',
                'restart_all': 'restart all shared httpd instances',
                'pull_recreate_all': 'pull the latest image and recreate all shared httpd instances',
                'stop_all': 'stop all shared httpd instances',
                'start_all': 'start all shared httpd instances'
            };

            if (!confirm('Are you sure you want to ' + (operationLabels[operation] || operation) + '?')) {
                return;
            }

            const formData = new FormData(this);
            formData.set('operation', operation);
            const originalText = clickedBtn.innerHTML;
            clickedBtn.disabled = true;
            clickedBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Working...';

            // Disable all buttons during operation
            const allBtns = this.querySelectorAll('.shared-httpd-btn');
            allBtns.forEach(btn => btn.disabled = true);

            fetch('index.php?page=server-settings', {
                method: 'POST',
                headers: { 'X-CSRF-Token': csrfToken },
                body: formData
            })
            .then(response => response.text())
            .then(data => {
                const parser = new DOMParser();
                const doc = parser.parseFromString(data, 'text/html');
                const alertElement = doc.querySelector('.alert');
                if (alertElement) {
                    const message = alertElement.textContent.trim();
                    const alertClass = alertElement.className.includes('alert-success') ? 'success' :
                                     alertElement.className.includes('alert-danger') ? 'danger' : 'info';
                    showAlert(message, alertClass);
                } else {
                    showAlert('Shared httpd operation completed.', 'success');
                }
                // Reload page after a moment to update instance status
                setTimeout(() => location.reload(), 2000);
            })
            .catch(error => {
                console.error('Error:', error);
                showAlert('An error occurred during the shared httpd operation.', 'danger');
            })
            .finally(() => {
                clickedBtn.disabled = false;
                clickedBtn.innerHTML = originalText;
                allBtns.forEach(btn => btn.disabled = false);
            });
        });
    }

    // Shared httpd settings form
    const sharedHttpdSettingsForm = document.getElementById('sharedHttpdSettingsForm');
    if (sharedHttpdSettingsForm) {
        sharedHttpdSettingsForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            const saveBtn = document.getElementById('saveSharedHttpdSettingsBtn');
            const originalText = saveBtn.innerHTML;
            saveBtn.disabled = true;
            saveBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Saving...';

            fetch('index.php?page=server-settings', {
                method: 'POST',
                headers: { 'X-CSRF-Token': csrfToken },
                body: formData
            })
            .then(response => response.text())
            .then(data => {
                const parser = new DOMParser();
                const doc = parser.parseFromString(data, 'text/html');
                const alertElement = doc.querySelector('.alert');
                if (alertElement) {
                    const message = alertElement.textContent.trim();
                    const alertClass = alertElement.className.includes('alert-success') ? 'success' : 'danger';
                    showAlert(message, alertClass);
                } else {
                    showAlert('Shared httpd settings saved.', 'success');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showAlert('An error occurred saving shared httpd settings.', 'danger');
            })
            .finally(() => {
                saveBtn.disabled = false;
                saveBtn.innerHTML = originalText;
            });
        });
    }

    // Function to show alerts
    function showAlert(message, type = 'info') {
        // Remove existing alerts
        const existingAlerts = document.querySelectorAll('.alert');
        existingAlerts.forEach(alert => alert.remove());
        
        // Create new alert
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type} alert-dismissible`;
        alertDiv.innerHTML = `
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            <i class="fa fa-${type === 'success' ? 'check' : type === 'danger' ? 'exclamation-triangle' : 'info-circle'}"></i>
            ${message}
        `;
        
        // Insert at the top of the page
        const container = document.querySelector('.row:first-child');
        container.insertBefore(alertDiv, container.firstChild);
        
        // Auto-dismiss success messages after 5 seconds
        if (type === 'success') {
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.remove();
                }
            }, 5000);
        }
    }
    
    // Function to update service status
    function updateServiceStatus() {
        fetch('ajax-status.php')
            .then(response => {
                console.log('Response status:', response.status);
                console.log('Response headers:', response.headers);
                return response.text();
            })
            .then(text => {
                console.log('Raw response:', text.substring(0, 200) + '...');
                try {
                    const data = JSON.parse(text);
                    console.log('Parsed data:', data);
                    if (data.service_status) {
                        Object.keys(data.service_status).forEach(service => {
                            const status = data.service_status[service];
                            const statusElement = document.querySelector(`[data-service="${service}"]`);
                            if (statusElement) {
                                const badge = statusElement.querySelector('.badge');
                                if (badge) {
                                    badge.className = status === 'active' ? 'badge bg-success fs-6' : 'badge bg-danger fs-6';
                                    badge.textContent = status === 'active' ? 'Active' : 'Inactive';
                                }
                            }
                        });
                    }
                } catch (e) {
                    console.error('JSON parse error:', e);
                    console.error('Response text:', text);
                }
            })
            .catch(error => console.error('Error updating service status:', error));
    }
    
    // Function to update container status
    function updateContainerStatus() {
        fetch('ajax-status.php')
            .then(response => {
                console.log('Container status response status:', response.status);
                return response.text();
            })
            .then(text => {
                console.log('Container status raw response:', text.substring(0, 200) + '...');
                try {
                    const data = JSON.parse(text);
                    console.log('Container status parsed data:', data);
                    if (data.container_status) {
                        Object.keys(data.container_status).forEach(container => {
                            const status = data.container_status[container];
                            const statusElement = document.querySelector(`[data-container="${container}"]`);
                            if (statusElement) {
                                const badge = statusElement.querySelector('.badge');
                                if (badge) {
                                    let statusClass = 'bg-success';
                                    let statusText = 'Running';
                                    
                                    if (status === 'stopped') {
                                        statusClass = 'bg-warning';
                                        statusText = 'Stopped';
                                    } else if (status === 'not_found') {
                                        statusClass = 'bg-danger';
                                        statusText = 'Not Found';
                                    }
                                    
                                    badge.className = `badge ${statusClass} fs-6`;
                                    badge.textContent = statusText;
                                }
                            }
                        });
                    }
                } catch (e) {
                    console.error('Container status JSON parse error:', e);
                    console.error('Container status response text:', text);
                }
            })
            .catch(error => console.error('Error updating container status:', error));
    }
});
</script> 