#!/bin/bash

#############################################################################
# Server Management Toolkit - Main Launcher
# Version: 2.1
#
# Streamlined menu showing only implemented features
#############################################################################

set -eo pipefail

# Configuration
SUITE_VERSION="2.1.0"
BASE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MODULES_DIR="$BASE_DIR/modules"
LIB_DIR="$BASE_DIR/lib"
CONFIG_DIR="$BASE_DIR/config"

# Load core libraries
source "$LIB_DIR/common-functions.sh"
source "$LIB_DIR/system-detect.sh"
source "$LIB_DIR/domain-discovery.sh"
source "$LIB_DIR/user-manager.sh"
source "$LIB_DIR/reference-db.sh"

# Color codes
RED='\033[0;31m'
YELLOW='\033[1;33m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
MAGENTA='\033[0;35m'
BOLD='\033[1m'
NC='\033[0m'

# Banner
show_banner() {
    clear
    echo -e "${CYAN}═══════════════════════════════════════════════════════════════${NC}"
    echo -e "${CYAN}     ⚡ Server Management Toolkit v${SUITE_VERSION}${NC}"
    echo -e "${CYAN}     Complete cPanel/Linux Server Administration Suite${NC}"
    echo -e "${CYAN}═══════════════════════════════════════════════════════════════${NC}"
    echo ""
}

# Run a module
run_module() {
    local category="$1"
    local module="$2"
    shift 2

    if [ ! -f "$MODULES_DIR/$category/$module" ]; then
        echo ""
        echo -e "${RED}✗ Module not found: $category/$module${NC}"
        echo ""
        read -p "Press Enter to continue..." < /dev/tty 2>/dev/null || true
        return 1
    fi

    echo ""
    echo -e "${CYAN}Launching: $category/$module${NC}"
    echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"

    # Run module directly - keep SYS_ variables cached for performance
    # Modules will use cached detection instead of re-detecting on every run
    "$MODULES_DIR/$category/$module" "$@"
    local exit_code=$?

    echo ""
    echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
    if [ "${exit_code:-0}" -eq 0 ]; then
        echo -e "${GREEN}✓ Completed successfully${NC}"
    else
        echo -e "${RED}✗ Exited with code: $exit_code${NC}"
    fi
    echo ""
    read -p "Press Enter to continue..." < /dev/tty 2>/dev/null || true
}

#############################################################################
# MAIN MENU
#############################################################################

show_main_menu() {
    show_banner

    echo -e "${BOLD}Quick Diagnostics:${NC}"
    echo ""
    echo -e "  ${MAGENTA}1)${NC} 🏥 System Health Check        - Full server diagnostics"
    echo ""
    echo -e "${BOLD}Main Categories:${NC}"
    echo ""
    echo -e "  ${GREEN}2)${NC} 🛡️  Security & Monitoring"
    echo -e "  ${BLUE}3)${NC} 🌐 Website Diagnostics"
    echo -e "  ${MAGENTA}4)${NC} 🔧 Performance & Maintenance"
    echo -e "  ${YELLOW}5)${NC} 💾 Backup & Recovery"
    echo -e "  ${CYAN}6)${NC} 📧 Email Troubleshooting"
    echo ""
    echo -e "${BOLD}System:${NC}"
    echo ""
    echo -e "  ${YELLOW}7)${NC} 🗑️  Cleanup Toolkit Data      - Clear cached data"
    echo ""
    echo -e "  ${RED}0)${NC} Exit"
    echo ""
    echo -e "${CYAN}═══════════════════════════════════════════════════════════════${NC}"
    echo -n "Select option: "
}

#############################################################################
# SECURITY & MONITORING
#############################################################################

#############################################################################
# SECURITY SUB-MENUS
#############################################################################

# Threat Analysis Sub-Menu
show_threat_analysis_menu() {
    show_banner
    echo -e "${GREEN}${BOLD}📊 Threat Analysis${NC}"
    echo ""
    echo -e "  ${CYAN}1)${NC} 🤖 Bot & Traffic Analyzer     - Full analysis (all logs)"
    echo -e "  ${CYAN}2)${NC} 🤖 Quick Scan (1 hour)        - Recent activity only"
    echo -e "  ${CYAN}3)${NC} 📊 IP Reputation Manager      - Query/manage IP database"
    echo -e "  ${CYAN}4)${NC} 🔐 Suspicious Login Monitor   - SSH/Panel login analysis"
    echo -e "  ${CYAN}5)${NC} 🦠 Malware Scanner            - ImunifyAV, ClamAV, Maldet"
    echo -e "  ${CYAN}6)${NC} 🛡️  Historical Attack Analysis - Scan past logs (ET Open)"
    echo ""
    echo -e "  ${RED}0)${NC} Back to Security Menu"
    echo ""
    echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
    echo -n "Select option: "
}

handle_threat_analysis_menu() {
    while true; do
        show_threat_analysis_menu
        if ! read -r choice 2>/dev/null </dev/tty; then
            return 0
        fi

        case $choice in
            1) run_module "security" "bot-analyzer.sh" ;;
            2) run_module "security" "bot-analyzer.sh" -H 1 ;;
            3) run_module "security" "ip-reputation-manager.sh" ;;
            4) run_module "security" "suspicious-login-monitor.sh" ;;
            5) run_module "security" "malware-scanner.sh" ;;
            6) bash "$BASE_DIR/tools/analyze-historical-attacks.sh" ;;
            0) return ;;
            *) echo -e "${RED}Invalid option${NC}"; sleep 1 ;;
        esac
    done
}

# Live Monitoring Sub-Menu
show_live_monitoring_menu() {
    show_banner
    echo -e "${MAGENTA}${BOLD}🔴 Live Monitoring${NC}"
    echo ""
    echo -e "  ${MAGENTA}1)${NC} 📡 Live Attack Monitor         - Unified threat intelligence"
    echo -e "  ${MAGENTA}2)${NC} 🔐 SSH Attack Monitor          - SSH brute force detection"
    echo -e "  ${MAGENTA}3)${NC} 🌐 Web Traffic Monitor         - HTTP attack detection"
    echo -e "  ${MAGENTA}4)${NC} 🔥 Firewall Activity Monitor   - CSF/iptables monitoring"
    echo ""
    echo -e "  ${RED}0)${NC} Back to Security Menu"
    echo ""
    echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
    echo -n "Select option: "
}

handle_live_monitoring_menu() {
    while true; do
        show_live_monitoring_menu
        if ! read -r choice 2>/dev/null </dev/tty; then
            return 0
        fi

        case $choice in
            1) run_module "security" "live-attack-monitor.sh" ;;
            2) run_module "security" "ssh-attack-monitor.sh" ;;
            3) run_module "security" "web-traffic-monitor.sh" ;;
            4) run_module "security" "firewall-activity-monitor.sh" ;;
            0) return ;;
            *) echo -e "${RED}Invalid option${NC}"; sleep 1 ;;
        esac
    done
}

# Log Viewers Sub-Menu
show_log_viewers_menu() {
    show_banner
    echo -e "${BLUE}${BOLD}📋 Log Viewers${NC}"
    echo ""
    echo -e "  ${BLUE}1)${NC} 🌐 Apache Access Log          - Live web access"
    echo -e "  ${BLUE}2)${NC} ❌ Apache Error Log           - Live web errors"
    echo -e "  ${BLUE}3)${NC} 📧 Mail Log                   - Live email activity"
    echo -e "  ${BLUE}4)${NC} 🔐 Security Log               - Live auth attempts"
    echo ""
    echo -e "  ${RED}0)${NC} Back to Security Menu"
    echo ""
    echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
    echo -n "Select option: "
}

handle_log_viewers_menu() {
    while true; do
        show_log_viewers_menu
        if ! read -r choice 2>/dev/null </dev/tty; then
            return 0
        fi

        case $choice in
            1) run_module "security" "tail-apache-access.sh" ;;
            2) run_module "security" "tail-apache-error.sh" ;;
            3) run_module "security" "tail-mail-log.sh" ;;
            4) run_module "security" "tail-secure-log.sh" ;;
            0) return ;;
            *) echo -e "${RED}Invalid option${NC}"; sleep 1 ;;
        esac
    done
}

# Security Actions Sub-Menu
show_security_actions_menu() {
    show_banner
    echo -e "${YELLOW}${BOLD}🔒 Security Actions${NC}"
    echo ""
    echo -e "  ${YELLOW}1)${NC} 🔒 Enable cPHulk Protection  - Brute force protection"
    echo -e "  ${YELLOW}2)${NC} ⚙️  Optimize CT_LIMIT         - Connection tracking tuning"
    echo -e "  ${YELLOW}3)${NC} 🤖 Block Malicious Bots      - User-Agent blocking (Apache)"
    echo ""
    echo -e "  ${RED}0)${NC} Back to Security Menu"
    echo ""
    echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
    echo -n "Select option: "
}

handle_security_actions_menu() {
    while true; do
        show_security_actions_menu
        if ! read -r choice 2>/dev/null </dev/tty; then
            return 0
        fi

        case $choice in
            1) run_module "security" "enable-cphulk.sh" ;;
            2) run_module "security" "optimize-ct-limit.sh" ;;
            3) run_module "security" "bot-blocker.sh" ;;
            0) return ;;
            *) echo -e "${RED}Invalid option${NC}"; sleep 1 ;;
        esac
    done
}

#############################################################################
# MAIN SECURITY MENU
#############################################################################

show_security_menu() {
    show_banner
    echo -e "${GREEN}${BOLD}🛡️  Security & Monitoring${NC}"
    echo ""
    echo -e "  ${CYAN}1)${NC} 📊 Threat Analysis        → Analyze threats & reputation"
    echo -e "  ${MAGENTA}2)${NC} 🔴 Live Monitoring         → Real-time attack detection"
    echo -e "  ${BLUE}3)${NC} 📋 Log Viewers             → Tail system/security logs"
    echo -e "  ${YELLOW}4)${NC} 🔒 Security Actions        → Hardening & protection"
    echo ""
    echo -e "  ${RED}0)${NC} Back to Main Menu"
    echo ""
    echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
    echo -n "Select option: "
}

handle_security_menu() {
    while true; do
        show_security_menu
        if ! read -r choice 2>/dev/null </dev/tty; then
            return 0
        fi

        case $choice in
            1) handle_threat_analysis_menu ;;
            2) handle_live_monitoring_menu ;;
            3) handle_log_viewers_menu ;;
            4) handle_security_actions_menu ;;
            0) return ;;
            *) echo -e "${RED}Invalid option${NC}"; sleep 1 ;;
        esac
    done
}

#############################################################################
# WEBSITE DIAGNOSTICS
#############################################################################

show_website_menu() {
    show_banner
    echo -e "${BLUE}${BOLD}🌐 Website Diagnostics${NC}"
    echo ""
    echo -e "${BOLD}Error Analysis:${NC}"
    echo ""
    echo -e "  ${BLUE}1)${NC} 🔍 Website Error Analyzer    - Find 500/config errors (filters bots)"
    echo -e "  ${RED}2)${NC} 🔥 Fast 500 Error Tracker    - ONLY 500s + root cause diagnosis"
    echo ""
    echo -e "${BOLD}Performance & Slowness:${NC}"
    echo ""
    echo -e "  ${MAGENTA}3)${NC} 🐢 Website Slowness Diagnostics - Multi-framework analysis"
    echo "     └─ WordPress, Drupal, Joomla, Magento, Laravel, Node.js, etc."
    echo ""
    echo -e "${BOLD}WordPress Management:${NC}"
    echo ""
    echo -e "  ${BLUE}4)${NC} 📦 WordPress Tools           → WP-Cron manager & more tools"
    echo ""
    echo -e "${BOLD}Domain Analysis:${NC}"
    echo ""
    echo -e "  ${BLUE}5)${NC} 🔶 Cloudflare Detector       - Which domains use Cloudflare + location"
    echo ""
    echo -e "  ${RED}0)${NC} Back to Main Menu"
    echo ""
    echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
    echo -n "Select option: "
}

handle_website_menu() {
    while true; do
        show_website_menu
        if ! read -r choice 2>/dev/null </dev/tty; then
            return 0
        fi

        case $choice in
            1) run_module "website" "website-error-analyzer.sh" ;;
            2) run_module "website" "500-error-tracker.sh" ;;
            3) run_module "website" "website-slowness-diagnostics.sh" ;;
            4) bash "$MODULES_DIR/website/wordpress-menu.sh" ;;
            5) run_module "website" "cloudflare-detector.sh" ;;
            0) return ;;
            *) echo -e "${RED}Invalid option${NC}"; sleep 1 ;;
        esac
    done
}

#############################################################################
# PERFORMANCE ANALYSIS
#############################################################################

show_performance_menu() {
    show_banner
    echo -e "${MAGENTA}${BOLD}🔧 Performance & Maintenance${NC}"
    echo ""
    echo -e "${BOLD}Database:${NC}"
    echo ""
    echo -e "  ${MAGENTA}1)${NC} 🗄️  MySQL Query Analyzer      - Find slow queries & optimize"
    echo ""
    echo -e "${BOLD}Network & Resources:${NC}"
    echo ""
    echo -e "  ${MAGENTA}2)${NC} 🌐 Network & Bandwidth        - Traffic & top consumers"
    echo -e "  ${MAGENTA}3)${NC} 💻 Hardware Health Check      - SMART, memory, CPU sensors"
    echo ""
    echo -e "${BOLD}PHP Optimization:${NC}"
    echo ""
    echo -e "  ${MAGENTA}4)${NC} ⚙️  PHP Configuration Optimizer - Per-domain PHP tuning"
    echo ""
    echo -e "${BOLD}System Health:${NC}"
    echo ""
    echo -e "  ${MAGENTA}5)${NC} 📊 Loadwatch Health Analyzer  - Historical system analysis"
    echo -e "  ${MAGENTA}6)${NC} 💿 Disk Space Analyzer        - Find space issues & cleanup files"
    echo ""
    echo -e "${BOLD}Caching Solutions:${NC}"
    echo ""
    echo -e "  ${MAGENTA}7)${NC} ⚡ Nginx + Varnish Manager   - Setup/manage caching stack"
    echo ""
    echo -e "  ${RED}0)${NC} Back to Main Menu"
    echo ""
    echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
    echo -n "Select option: "
}

handle_performance_menu() {
    while true; do
        show_performance_menu
        if ! read -r choice 2>/dev/null </dev/tty; then
            return 0
        fi

        case $choice in
            1) run_module "performance" "mysql-query-analyzer.sh" ;;
            2) run_module "performance" "network-bandwidth-analyzer.sh" ;;
            3) run_module "performance" "hardware-health-check.sh" ;;
            4) run_module "performance" "php-optimizer.sh" ;;
            5) handle_loadwatch_analyzer ;;
            6) run_module "maintenance" "disk-space-analyzer.sh" ;;
            7) run_module "performance" "nginx-varnish-manager.sh" ;;
            0) return ;;
            *) echo -e "${RED}Invalid option${NC}"; sleep 1 ;;
        esac
    done
}

handle_loadwatch_analyzer() {
    show_banner
    echo -e "${MAGENTA}${BOLD}📊 Loadwatch Health Analyzer${NC}"
    echo ""
    echo -e "Select time range for analysis:"
    echo ""
    echo -e "  ${CYAN}1)${NC} Last 1 Hour      - Recent activity"
    echo -e "  ${CYAN}2)${NC} Last 6 Hours     - Mid-term trending"
    echo -e "  ${CYAN}3)${NC} Last 24 Hours    - Full day analysis"
    echo -e "  ${CYAN}4)${NC} Last 7 Days      - Weekly patterns"
    echo -e "  ${CYAN}5)${NC} Last 30 Days     - Monthly overview"
    echo ""
    echo -e "  ${RED}0)${NC} Back"
    echo ""
    echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
    echo -n "Select time range: "

    read -r range_choice

    case $range_choice in
        1) run_module "diagnostics" "loadwatch-analyzer.sh" "-r" "1h" ;;
        2) run_module "diagnostics" "loadwatch-analyzer.sh" "-r" "6h" ;;
        3) run_module "diagnostics" "loadwatch-analyzer.sh" "-r" "24h" ;;
        4) run_module "diagnostics" "loadwatch-analyzer.sh" "-r" "7d" ;;
        5) run_module "diagnostics" "loadwatch-analyzer.sh" "-r" "30d" ;;
        0) return ;;
        *) echo -e "${RED}Invalid option${NC}"; sleep 1 ;;
    esac
}

#############################################################################
# BACKUP & RECOVERY
#############################################################################

show_backup_menu() {
    show_banner
    echo -e "${YELLOW}${BOLD}💾 Backup & Recovery${NC}"
    echo ""
    echo -e "${BOLD}Acronis Cyber Protect:${NC}"
    echo ""
    echo -e "  ${YELLOW}1)${NC} 🔷 Acronis Management        → Complete backup management"
    echo ""
    echo -e "${BOLD}Database Tools:${NC}"
    echo ""
    echo -e "  ${CYAN}2)${NC} 🔄 MySQL File Restore        - Convert restored DB files to .sql"
    echo ""
    echo -e "${BOLD}Maintenance:${NC}"
    echo ""
    echo -e "  ${RED}3)${NC} 🗑️  Cleanup Toolkit Data      - Remove IP reputation & temp files"
    echo ""
    echo -e "  ${RED}0)${NC} Back to Main Menu"
    echo ""
    echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
    echo -n "Select option: "
}

show_acronis_menu() {
    show_banner
    echo -e "${YELLOW}${BOLD}🔷 Acronis Cyber Protect${NC}"
    echo ""
    echo -e "${BOLD}Installation & Setup:${NC}"
    echo ""
    echo -e "  ${YELLOW}1)${NC} Install Acronis Agent       - Download and install"
    echo -e "  ${YELLOW}2)${NC} Register with Cloud         - Connect to Acronis Cloud"
    echo -e "  ${YELLOW}3)${NC} Configure Agent             - Adjust settings"
    echo ""
    echo -e "${BOLD}Backup Management:${NC}"
    echo ""
    echo -e "  ${GREEN}4)${NC} 📊 Manage Backups            - Complete backup interface"
    echo ""
    echo -e "${BOLD}Status & Monitoring:${NC}"
    echo ""
    echo -e "  ${CYAN}5)${NC} Check Agent Status          - Verify Acronis is running"
    echo -e "  ${CYAN}6)${NC} View Logs                   - Check Acronis logs"
    echo -e "  ${CYAN}7)${NC} Troubleshoot                - Diagnose backup failures"
    echo ""
    echo -e "${BOLD}Maintenance:${NC}"
    echo ""
    echo -e "  ${YELLOW}8)${NC} Update Agent                - Upgrade to latest version"
    echo -e "  ${RED}9)${NC} Uninstall Acronis           - Remove agent"
    echo ""
    echo -e "  ${RED}0)${NC} Back to Backup Menu"
    echo ""
    echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
    echo -n "Select option: "
}

handle_backup_menu() {
    while true; do
        show_backup_menu
        if ! read -r choice 2>/dev/null </dev/tty; then
            return 0
        fi

        case $choice in
            1) handle_acronis_menu ;;
            2) run_module "backup" "mysql-restore-to-sql.sh" ;;
            3) run_module "maintenance" "cleanup-toolkit-data.sh" ;;
            0) return ;;
            *) echo -e "${RED}Invalid option${NC}"; sleep 1 ;;
        esac
    done
}

handle_acronis_menu() {
    while true; do
        show_acronis_menu
        if ! read -r choice 2>/dev/null </dev/tty; then
            return 0
        fi

        case $choice in
            1) run_module "backup" "acronis-install.sh" ;;
            2) run_module "backup" "acronis-register.sh" ;;
            3) run_module "backup" "acronis-configure.sh" ;;
            4) run_module "backup" "acronis-backup-manager.sh" ;;
            5) run_module "backup" "acronis-agent-status.sh" ;;
            6) run_module "backup" "acronis-logs.sh" ;;
            7) run_module "backup" "acronis-troubleshoot.sh" ;;
            8) run_module "backup" "acronis-update.sh" ;;
            9) run_module "backup" "acronis-uninstall.sh" ;;
            0) return ;;
            *) echo -e "${RED}Invalid option${NC}"; sleep 1 ;;
        esac
    done
}

#############################################################################
# EMAIL TROUBLESHOOTING & MAINTENANCE
#############################################################################

show_email_menu() {
    show_banner
    echo -e "${CYAN}${BOLD}📧 Email Troubleshooting & Maintenance${NC}"
    echo ""
    echo -e "${BOLD}Diagnostics:${NC}"
    echo ""
    echo -e "  ${CYAN}1)${NC} 🔍 Email Diagnostics           - Verify email/domain is working ⭐"
    echo -e "  ${CYAN}2)${NC} 📬 Email Deliverability Test   - Test sending/receiving"
    echo -e "  ${CYAN}3)${NC} 🔍 Mail Queue Inspector        - View stuck emails"
    echo -e "  ${CYAN}4)${NC} 📊 SMTP Connection Test        - Verify mail server"
    echo -e "  ${CYAN}5)${NC} 🔐 SPF/DKIM/DMARC Check        - Email authentication"
    echo ""
    echo -e "${BOLD}Troubleshooting:${NC}"
    echo ""
    echo -e "  ${YELLOW}6)${NC} 🚫 Blacklist Check             - Check IP reputation"
    echo -e "  ${YELLOW}7)${NC} 📧 Mail Log Analyzer           - Search mail logs"
    echo -e "  ${YELLOW}8)${NC} 🔄 Flush Mail Queue            - Clear stuck emails"
    echo ""
    echo -e "${BOLD}Maintenance:${NC}"
    echo ""
    echo -e "  ${GREEN}9)${NC} 🧹 Clean Mailboxes             - Remove old emails"
    echo -e "  ${GREEN}10)${NC} 📈 Mailbox Size Report        - Show usage per account"
    echo ""
    echo -e "  ${RED}0)${NC} Back to Main Menu"
    echo ""
    echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
    echo -n "Select option: "
}

handle_email_menu() {
    while true; do
        show_email_menu
        if ! read -r choice 2>/dev/null </dev/tty; then
            return 0
        fi

        case $choice in
            1) run_module "email" "email-diagnostics.sh" ;;
            2) run_module "email" "deliverability-test.sh" ;;
            3) run_module "email" "mail-queue-inspector.sh" ;;
            4) run_module "email" "smtp-connection-test.sh" ;;
            5) run_module "email" "spf-dkim-dmarc-check.sh" ;;
            6) run_module "email" "blacklist-check.sh" ;;
            7) run_module "email" "mail-log-analyzer.sh" ;;
            8) run_module "email" "flush-mail-queue.sh" ;;
            9) run_module "email" "clean-mailboxes.sh" ;;
            10) run_module "email" "mailbox-size-report.sh" ;;
            0) return ;;
            *) echo -e "${RED}Invalid option${NC}"; sleep 1 ;;
        esac
    done
}

#############################################################################
# INITIALIZATION
#############################################################################

init_directories() {
    mkdir -p "$MODULES_DIR"/{security,website,performance,backup,diagnostics,maintenance,email}
    mkdir -p "$LIB_DIR" "$CONFIG_DIR" "$BASE_DIR/logs"
    touch "$CONFIG_DIR/whitelist-ips.txt" 2>/dev/null
    touch "$CONFIG_DIR/whitelist-user-agents.txt" 2>/dev/null
}

startup_detection() {
    # Initialize system detection first (required for proper reference database)
    if [ -z "${SYS_DETECTION_COMPLETE:-}" ]; then
        initialize_system_detection
    fi

    if ! db_is_fresh; then
        clear
        print_banner "Server Management Toolkit - Initializing"
        echo ""
        print_info "Detecting server configuration..."
        echo ""

        build_reference_database

        echo ""
        print_section "Detection Summary"
        echo ""

        echo -e "${BOLD}System:${NC}"
        echo "  Control Panel: $SYS_CONTROL_PANEL $SYS_CONTROL_PANEL_VERSION"
        echo "  OS: $SYS_OS_TYPE $SYS_OS_VERSION"
        echo "  Web Server: $SYS_WEB_SERVER $SYS_WEB_SERVER_VERSION"
        echo "  Database: $SYS_DB_TYPE $SYS_DB_VERSION"
        echo ""

        local user_count=$(grep -c "^USER|" "$SYSREF_DB" 2>/dev/null || echo 0)
        local domain_count=$(grep -c "^DOMAIN|" "$SYSREF_DB" 2>/dev/null || echo 0)
        local db_count=$(grep -c "^DB|" "$SYSREF_DB" 2>/dev/null || echo 0)
        local wp_count=$(grep -c "^WP|" "$SYSREF_DB" 2>/dev/null || echo 0)

        echo -e "${BOLD}Server Content:${NC}"
        echo "  Users: $user_count"
        echo "  Domains: $domain_count"
        echo "  Databases: $db_count"
        echo "  WordPress Sites: $wp_count"
        echo ""

        print_success "Detection complete! Cached for 1 hour."
        echo ""

        read -p "Press Enter to continue..." < /dev/tty 2>/dev/null || true
    fi
}

#############################################################################
# MAIN LOOP
#############################################################################

main() {
    init_directories
    startup_detection

    while true; do
        show_main_menu

        # Read from terminal (use /dev/tty directly for interaction)
        if ! read -r choice 2>/dev/null </dev/tty; then
            # No terminal available, return from function gracefully
            return 0
        fi

        case $choice in
            1) run_module "diagnostics" "system-health-check.sh" ;;
            2) handle_security_menu ;;
            3) handle_website_menu ;;
            4) handle_performance_menu ;;
            5) handle_backup_menu ;;
            6) handle_email_menu ;;
            7) run_module "maintenance" "cleanup-toolkit-data.sh" ;;
            0)
                echo ""
                read -p "Clean history and remove traces? (yes/no): " clean_hist

                if [ "$clean_hist" = "yes" ]; then
                    touch /tmp/.cleanup_requested
                    echo ""
                    echo "Cleanup will happen automatically..."
                    echo ""
                else
                    echo ""
                    echo -e "${GREEN}Thanks for using Server Management Toolkit!${NC}"
                    echo ""
                fi
                return 0
                ;;
            *)
                echo -e "${RED}Invalid option${NC}"
                sleep 1
                ;;
        esac
    done
}

main "$@"
