#!/bin/bash

# Server Manager untuk CI3
# Ubuntu 24.04 - Nginx + PHP-FPM + SQL Server + Redis
# Author: Server Management Tool
# Version: 1.0

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Variables
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG_FILE="/var/log/server-manager.log"

# Check if running as root
check_root() {
    if [[ $EUID -ne 0 ]]; then
        echo -e "${RED}Script ini harus dijalankan sebagai root!${NC}"
        echo "Gunakan: sudo bash $0"
        exit 1
    fi
}

# Logging function
log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
}

# Clear screen and show header
show_header() {
    clear
    echo -e "${BLUE}╔════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${BLUE}║${NC}          ${GREEN}SERVER MANAGER - CodeIgniter 3${NC}              ${BLUE}║${NC}"
    echo -e "${BLUE}║${NC}     Ubuntu 24.04 | Nginx | PHP | SQL Server | Redis       ${BLUE}║${NC}"
    echo -e "${BLUE}╚════════════════════════════════════════════════════════════╝${NC}"
    echo ""
}

# Main Menu
show_main_menu() {
    show_header
    echo -e "${YELLOW}MAIN MENU${NC}"
    echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
    echo ""
    echo "  1) Install Full Stack (Nginx + PHP + SQL Server + Redis)"
    echo "  2) Manage Nginx"
    echo "  3) Manage PHP"
    echo "  4) Manage SQL Server"
    echo "  5) Manage Redis"
    echo "  6) Manage Website/Domain"
    echo "  7) SSL Certificate Management"
    echo "  8) Server Monitoring"
    echo "  9) Backup & Restore"
    echo " 10) System Optimization"
    echo " 11) Security Settings"
    echo " 12) Update System"
    echo "  0) Exit"
    echo ""
    echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
    echo -n "Pilih menu [0-12]: "
}

# Install Full Stack
install_full_stack() {
    show_header
    echo -e "${GREEN}INSTALASI FULL STACK${NC}"
    echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
    echo ""
    
    read -p "Apakah Anda yakin ingin install full stack? (y/n): " confirm
    if [[ $confirm != "y" ]]; then
        return
    fi
    
    echo -e "\n${YELLOW}[1/6] Update system...${NC}"
    apt update && apt upgrade -y
    apt install -y software-properties-common curl wget git unzip htop
    
    echo -e "\n${YELLOW}[2/6] Install Nginx...${NC}"
    install_nginx_internal
    
    echo -e "\n${YELLOW}[3/6] Install PHP 8.2 dan 8.4...${NC}"
    install_php_internal
    
    echo -e "\n${YELLOW}[4/6] Install SQL Server...${NC}"
    #install_sqlserver_internal
    
    echo -e "\n${YELLOW}[5/6] Install Redis...${NC}"
    install_redis_internal
    
    echo -e "\n${YELLOW}[6/6] Install ImageMagick...${NC}"
    apt install -y imagemagick
    
    echo -e "\n${GREEN}✓ Instalasi selesai!${NC}"
    log_message "Full stack installation completed"
    
    read -p "Press Enter to continue..."
}

# Install Nginx Internal
install_nginx_internal() {
    apt install -y nginx
    
    # Backup original config
    cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.backup
    
    # Create optimized config
    cat > /etc/nginx/nginx.conf << 'EOF'
user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
    worker_connections 2048;
    use epoll;
    multi_accept on;
}

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    client_max_body_size 100M;

    # Gzip
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types text/plain text/css text/xml text/javascript 
               application/json application/javascript application/xml+rss;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;
    
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}
EOF
    
    systemctl start nginx
    systemctl enable nginx
    echo "Nginx installed successfully"
}

# Install PHP Internal
install_php_internal() {
    add-apt-repository ppa:ondrej/php -y
    apt update
    
    # Install dependencies untuk compile SQL Server driver
    apt install -y php8.2-dev php8.4-dev gcc g++ make autoconf libc-dev pkg-config
    
    # Install PHP 8.2
    apt install -y php8.2-fpm php8.2-cli php8.2-common php8.2-mysql \
        php8.2-mbstring php8.2-xml php8.2-curl php8.2-zip php8.2-gd \
        php8.2-intl php8.2-bcmath php8.2-soap php8.2-imagick \
        php8.2-redis php8.2-opcache php8.2-pear
    
    # Install PHP 8.4
    apt install -y php8.4-fpm php8.4-cli php8.4-common php8.4-mysql \
        php8.4-mbstring php8.4-xml php8.4-curl php8.4-zip php8.4-gd \
        php8.4-intl php8.4-bcmath php8.4-soap php8.4-imagick \
        php8.4-redis php8.4-opcache php8.4-pear
    
    # Install ODBC Driver untuk SQL Server
    echo -e "\n${YELLOW}Installing ODBC Driver for SQL Server...${NC}"
    curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
    curl https://packages.microsoft.com/config/ubuntu/$(lsb_release -rs)/prod.list > /etc/apt/sources.list.d/mssql-release.list
    apt update
    ACCEPT_EULA=Y apt install -y msodbcsql18 unixodbc-dev
    
    # Install SQL Server driver untuk PHP 8.2
    echo -e "\n${YELLOW}Installing SQL Server drivers for PHP 8.2...${NC}"
    pecl -d php_suffix=8.2 install sqlsrv pdo_sqlsrv
    
    # Enable extensions untuk PHP 8.2
    echo "extension=sqlsrv.so" > /etc/php/8.2/mods-available/sqlsrv.ini
    echo "extension=pdo_sqlsrv.so" > /etc/php/8.2/mods-available/pdo_sqlsrv.ini
    
    ln -sf /etc/php/8.2/mods-available/sqlsrv.ini /etc/php/8.2/fpm/conf.d/20-sqlsrv.ini
    ln -sf /etc/php/8.2/mods-available/sqlsrv.ini /etc/php/8.2/cli/conf.d/20-sqlsrv.ini
    ln -sf /etc/php/8.2/mods-available/pdo_sqlsrv.ini /etc/php/8.2/fpm/conf.d/30-pdo_sqlsrv.ini
    ln -sf /etc/php/8.2/mods-available/pdo_sqlsrv.ini /etc/php/8.2/cli/conf.d/30-pdo_sqlsrv.ini
    
    # Install SQL Server driver untuk PHP 8.4
    echo -e "\n${YELLOW}Installing SQL Server drivers for PHP 8.4...${NC}"
    pecl -d php_suffix=8.4 install sqlsrv pdo_sqlsrv
    
    # Enable extensions untuk PHP 8.4
    echo "extension=sqlsrv.so" > /etc/php/8.4/mods-available/sqlsrv.ini
    echo "extension=pdo_sqlsrv.so" > /etc/php/8.4/mods-available/pdo_sqlsrv.ini
    
    ln -sf /etc/php/8.4/mods-available/sqlsrv.ini /etc/php/8.4/fpm/conf.d/20-sqlsrv.ini
    ln -sf /etc/php/8.4/mods-available/sqlsrv.ini /etc/php/8.4/cli/conf.d/20-sqlsrv.ini
    ln -sf /etc/php/8.4/mods-available/pdo_sqlsrv.ini /etc/php/8.4/fpm/conf.d/30-pdo_sqlsrv.ini
    ln -sf /etc/php/8.4/mods-available/pdo_sqlsrv.ini /etc/php/8.4/cli/conf.d/30-pdo_sqlsrv.ini
    
    # Optimize PHP 8.2
    sed -i 's/memory_limit = .*/memory_limit = 512M/' /etc/php/8.2/fpm/php.ini
    sed -i 's/upload_max_filesize = .*/upload_max_filesize = 100M/' /etc/php/8.2/fpm/php.ini
    sed -i 's/post_max_size = .*/post_max_size = 100M/' /etc/php/8.2/fpm/php.ini
    sed -i 's/;date.timezone =.*/date.timezone = Asia\/Jakarta/' /etc/php/8.2/fpm/php.ini
    
    # Enable OPcache for PHP 8.2
    cat > /etc/php/8.2/fpm/conf.d/10-opcache.ini << EOF
opcache.enable=1
opcache.enable_cli=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=10000
opcache.revalidate_freq=2
opcache.fast_shutdown=1
opcache.jit=tracing
opcache.jit_buffer_size=128M
EOF
    
    # Optimize PHP 8.4
    sed -i 's/memory_limit = .*/memory_limit = 512M/' /etc/php/8.4/fpm/php.ini
    sed -i 's/upload_max_filesize = .*/upload_max_filesize = 100M/' /etc/php/8.4/fpm/php.ini
    sed -i 's/post_max_size = .*/post_max_size = 100M/' /etc/php/8.4/fpm/php.ini
    sed -i 's/;date.timezone =.*/date.timezone = Asia\/Jakarta/' /etc/php/8.4/fpm/php.ini
    
    # Enable OPcache for PHP 8.4
    cat > /etc/php/8.4/fpm/conf.d/10-opcache.ini << EOF
opcache.enable=1
opcache.enable_cli=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=10000
opcache.revalidate_freq=2
opcache.fast_shutdown=1
opcache.jit=tracing
opcache.jit_buffer_size=128M
EOF
    
    systemctl start php8.2-fpm php8.4-fpm
    systemctl enable php8.2-fpm php8.4-fpm
    
    # Verify installation
    echo -e "\n${GREEN}Verifying SQL Server drivers...${NC}"
    php8.2 -m | grep -E "sqlsrv|pdo_sqlsrv"
    php8.4 -m | grep -E "sqlsrv|pdo_sqlsrv"
    
    echo -e "\n${GREEN}PHP 8.2 and 8.4 with SQL Server drivers installed successfully${NC}"
}

# Install SQL Server Internal
install_sqlserver_internal() {
    # Install prerequisites
    apt install -y curl gnupg2
    
    # Import Microsoft GPG key
    curl https://packages.microsoft.com/keys/microsoft.asc | tee /etc/apt/trusted.gpg.d/microsoft.asc
    
    # Add repository
    curl https://packages.microsoft.com/config/ubuntu/24.04/mssql-server-2022.list | tee /etc/apt/sources.list.d/mssql-server.list
    
    apt update
    apt install -y mssql-server
    
    echo ""
    echo -e "${YELLOW}Setup SQL Server:${NC}"
    echo "1. Pilih edition: 2 (Developer - Free)"
    echo "2. Accept license: Yes"
    echo "3. Set SA password (minimal 8 karakter dengan huruf besar/kecil/angka/simbol)"
    echo ""
    read -p "Press Enter untuk melanjutkan setup..."
    
    /opt/mssql/bin/mssql-conf setup
    
    # Install SQL tools
    curl https://packages.microsoft.com/config/ubuntu/24.04/prod.list | tee /etc/apt/sources.list.d/mssql-release.list
    apt update
    ACCEPT_EULA=Y apt install -y mssql-tools18 unixodbc-dev
    
    echo 'export PATH="$PATH:/opt/mssql-tools18/bin"' >> ~/.bashrc
    
    echo "SQL Server installed successfully"
}

# Install Redis Internal
install_redis_internal() {
    apt install -y redis-server
    
    # Configure Redis
    sed -i 's/# maxmemory <bytes>/maxmemory 1gb/' /etc/redis/redis.conf
    sed -i 's/# maxmemory-policy noeviction/maxmemory-policy allkeys-lru/' /etc/redis/redis.conf
    
    systemctl restart redis-server
    systemctl enable redis-server
    echo "Redis installed successfully"
}

# Nginx Management Menu
manage_nginx() {
    while true; do
        show_header
        echo -e "${YELLOW}MANAGE NGINX${NC}"
        echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
        echo ""
        echo "  1) Start Nginx"
        echo "  2) Stop Nginx"
        echo "  3) Restart Nginx"
        echo "  4) Reload Nginx"
        echo "  5) Check Nginx Status"
        echo "  6) Test Nginx Configuration"
        echo "  7) View Error Log"
        echo "  8) View Access Log"
        echo "  9) Edit Nginx Config"
        echo "  0) Back to Main Menu"
        echo ""
        echo -n "Pilih menu [0-9]: "
        read nginx_choice
        
        case $nginx_choice in
            1) systemctl start nginx && echo -e "${GREEN}Nginx started${NC}" ;;
            2) systemctl stop nginx && echo -e "${GREEN}Nginx stopped${NC}" ;;
            3) systemctl restart nginx && echo -e "${GREEN}Nginx restarted${NC}" ;;
            4) systemctl reload nginx && echo -e "${GREEN}Nginx reloaded${NC}" ;;
            5) systemctl status nginx ;;
            6) nginx -t ;;
            7) tail -n 50 /var/log/nginx/error.log ;;
            8) tail -n 50 /var/log/nginx/access.log ;;
            9) nano /etc/nginx/nginx.conf ;;
            0) break ;;
            *) echo -e "${RED}Pilihan tidak valid${NC}" ;;
        esac
        
        if [[ $nginx_choice != "0" ]]; then
            read -p "Press Enter to continue..."
        fi
    done
}

# PHP Management Menu
manage_php() {
    while true; do
        show_header
        echo -e "${YELLOW}MANAGE PHP${NC}"
        echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
        echo ""
        echo "  1) Start PHP 8.2-FPM"
        echo "  2) Stop PHP 8.2-FPM"
        echo "  3) Restart PHP 8.2-FPM"
        echo "  4) Start PHP 8.4-FPM"
        echo "  5) Stop PHP 8.4-FPM"
        echo "  6) Restart PHP 8.4-FPM"
        echo "  7) Check PHP 8.2 Status"
        echo "  8) Check PHP 8.4 Status"
        echo "  9) Edit PHP 8.2 Config"
        echo " 10) Edit PHP 8.4 Config"
        echo " 11) View PHP 8.2 Info"
        echo " 12) View PHP 8.4 Info"
        echo "  0) Back to Main Menu"
        echo ""
        echo -n "Pilih menu [0-12]: "
        read php_choice
        
        case $php_choice in
            1) systemctl start php8.2-fpm && echo -e "${GREEN}PHP 8.2 started${NC}" ;;
            2) systemctl stop php8.2-fpm && echo -e "${GREEN}PHP 8.2 stopped${NC}" ;;
            3) systemctl restart php8.2-fpm && echo -e "${GREEN}PHP 8.2 restarted${NC}" ;;
            4) systemctl start php8.4-fpm && echo -e "${GREEN}PHP 8.4 started${NC}" ;;
            5) systemctl stop php8.4-fpm && echo -e "${GREEN}PHP 8.4 stopped${NC}" ;;
            6) systemctl restart php8.4-fpm && echo -e "${GREEN}PHP 8.4 restarted${NC}" ;;
            7) systemctl status php8.2-fpm ;;
            8) systemctl status php8.4-fpm ;;
            9) nano /etc/php/8.2/fpm/php.ini ;;
            10) nano /etc/php/8.4/fpm/php.ini ;;
            11) php8.2 -i | less ;;
            12) php8.4 -i | less ;;
            0) break ;;
            *) echo -e "${RED}Pilihan tidak valid${NC}" ;;
        esac
        
        if [[ $php_choice != "0" ]]; then
            read -p "Press Enter to continue..."
        fi
    done
}

# SQL Server Management Menu
manage_sqlserver() {
    while true; do
        show_header
        echo -e "${YELLOW}MANAGE SQL SERVER${NC}"
        echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
        echo ""
        echo "  1) Start SQL Server"
        echo "  2) Stop SQL Server"
        echo "  3) Restart SQL Server"
        echo "  4) Check SQL Server Status"
        echo "  5) Configure SQL Server"
        echo "  6) Connect to SQL Server (sqlcmd)"
        echo "  7) View SQL Server Log"
        echo "  0) Back to Main Menu"
        echo ""
        echo -n "Pilih menu [0-7]: "
        read sql_choice
        
        case $sql_choice in
            1) systemctl start mssql-server && echo -e "${GREEN}SQL Server started${NC}" ;;
            2) systemctl stop mssql-server && echo -e "${GREEN}SQL Server stopped${NC}" ;;
            3) systemctl restart mssql-server && echo -e "${GREEN}SQL Server restarted${NC}" ;;
            4) systemctl status mssql-server ;;
            5) /opt/mssql/bin/mssql-conf setup ;;
            6) 
                echo "Gunakan: sqlcmd -S localhost -U SA"
                /opt/mssql-tools18/bin/sqlcmd -S localhost -U SA -C
                ;;
            7) tail -n 50 /var/opt/mssql/log/errorlog ;;
            0) break ;;
            *) echo -e "${RED}Pilihan tidak valid${NC}" ;;
        esac
        
        if [[ $sql_choice != "0" ]]; then
            read -p "Press Enter to continue..."
        fi
    done
}

# Redis Management Menu
manage_redis() {
    while true; do
        show_header
        echo -e "${YELLOW}MANAGE REDIS${NC}"
        echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
        echo ""
        echo "  1) Start Redis"
        echo "  2) Stop Redis"
        echo "  3) Restart Redis"
        echo "  4) Check Redis Status"
        echo "  5) Redis CLI"
        echo "  6) Flush All Redis Data"
        echo "  7) Redis Info"
        echo "  8) Edit Redis Config"
        echo "  0) Back to Main Menu"
        echo ""
        echo -n "Pilih menu [0-8]: "
        read redis_choice
        
        case $redis_choice in
            1) systemctl start redis-server && echo -e "${GREEN}Redis started${NC}" ;;
            2) systemctl stop redis-server && echo -e "${GREEN}Redis stopped${NC}" ;;
            3) systemctl restart redis-server && echo -e "${GREEN}Redis restarted${NC}" ;;
            4) systemctl status redis-server ;;
            5) redis-cli ;;
            6) 
                read -p "Yakin ingin hapus semua data Redis? (y/n): " confirm
                if [[ $confirm == "y" ]]; then
                    redis-cli FLUSHALL
                    echo -e "${GREEN}Redis data cleared${NC}"
                fi
                ;;
            7) redis-cli INFO ;;
            8) nano /etc/redis/redis.conf ;;
            0) break ;;
            *) echo -e "${RED}Pilihan tidak valid${NC}" ;;
        esac
        
        if [[ $redis_choice != "0" ]]; then
            read -p "Press Enter to continue..."
        fi
    done
}

# Website Management Menu
manage_website() {
    while true; do
        show_header
        echo -e "${YELLOW}MANAGE WEBSITE/DOMAIN${NC}"
        echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
        echo ""
        echo "  1) Add New Website"
        echo "  2) List All Websites"
        echo "  3) Enable Website"
        echo "  4) Disable Website"
        echo "  5) Delete Website"
        echo "  6) Edit Website Config"
        echo "  0) Back to Main Menu"
        echo ""
        echo -n "Pilih menu [0-6]: "
        read web_choice
        
        case $web_choice in
            1) add_new_website ;;
            2) ls -la /etc/nginx/sites-available/ ;;
            3) enable_website ;;
            4) disable_website ;;
            5) delete_website ;;
            6) edit_website_config ;;
            0) break ;;
            *) echo -e "${RED}Pilihan tidak valid${NC}" ;;
        esac
        
        if [[ $web_choice != "0" ]]; then
            read -p "Press Enter to continue..."
        fi
    done
}

# Add New Website
add_new_website() {
    echo ""
    read -p "Domain name (example: myapp.com): " domain
    read -p "Web root path (default: /var/www/$domain): " webroot
    webroot=${webroot:-/var/www/$domain}
    
    echo ""
    echo "Pilih PHP Version:"
    echo "1) PHP 8.2"
    echo "2) PHP 8.4"
    read -p "Pilih [1-2]: " php_ver
    
    if [[ $php_ver == "1" ]]; then
        php_sock="php8.2-fpm.sock"
    else
        php_sock="php8.4-fpm.sock"
    fi
    
    # Create web root
    mkdir -p "$webroot"
    chown -R www-data:www-data "$webroot"
    
    # Create Nginx config
    cat > "/etc/nginx/sites-available/$domain" << EOF
server {
    listen 80;
    server_name $domain www.$domain;
    
    root $webroot;
    index index.php index.html;

    access_log /var/log/nginx/${domain}-access.log;
    error_log /var/log/nginx/${domain}-error.log;

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;

    # CodeIgniter 3 URL Rewrite
    location / {
        try_files \$uri \$uri/ /index.php?\$query_string;
    }

    # PHP Processing
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/$php_sock;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        include fastcgi_params;
    }

    # Deny access to sensitive files
    location ~ /\.ht {
        deny all;
    }

    # Static files caching
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
}
EOF
    
    # Enable site
    ln -s "/etc/nginx/sites-available/$domain" "/etc/nginx/sites-enabled/$domain"
    
    # Test and reload Nginx
    nginx -t && systemctl reload nginx
    
    echo -e "\n${GREEN}✓ Website $domain berhasil ditambahkan!${NC}"
    echo "Web root: $webroot"
    echo "PHP Version: $php_sock"
}

# Enable Website
enable_website() {
    echo ""
    ls /etc/nginx/sites-available/
    echo ""
    read -p "Nama website yang akan dienable: " site
    
    if [[ -f "/etc/nginx/sites-available/$site" ]]; then
        ln -s "/etc/nginx/sites-available/$site" "/etc/nginx/sites-enabled/$site"
        nginx -t && systemctl reload nginx
        echo -e "${GREEN}✓ Website $site dienabled${NC}"
    else
        echo -e "${RED}Website tidak ditemukan${NC}"
    fi
}

# Disable Website
disable_website() {
    echo ""
    ls /etc/nginx/sites-enabled/
    echo ""
    read -p "Nama website yang akan didisable: " site
    
    if [[ -L "/etc/nginx/sites-enabled/$site" ]]; then
        rm "/etc/nginx/sites-enabled/$site"
        systemctl reload nginx
        echo -e "${GREEN}✓ Website $site didisabled${NC}"
    else
        echo -e "${RED}Website tidak ditemukan${NC}"
    fi
}

# Delete Website
delete_website() {
    echo ""
    ls /etc/nginx/sites-available/
    echo ""
    read -p "Nama website yang akan dihapus: " site
    read -p "Yakin ingin hapus $site? (y/n): " confirm
    
    if [[ $confirm == "y" ]]; then
        rm -f "/etc/nginx/sites-available/$site"
        rm -f "/etc/nginx/sites-enabled/$site"
        systemctl reload nginx
        echo -e "${GREEN}✓ Website $site dihapus${NC}"
    fi
}

# Edit Website Config
edit_website_config() {
    echo ""
    ls /etc/nginx/sites-available/
    echo ""
    read -p "Nama website yang akan diedit: " site
    
    if [[ -f "/etc/nginx/sites-available/$site" ]]; then
        nano "/etc/nginx/sites-available/$site"
        nginx -t && systemctl reload nginx
    else
        echo -e "${RED}Website tidak ditemukan${NC}"
    fi
}

# SSL Management Menu
manage_ssl() {
    while true; do
        show_header
        echo -e "${YELLOW}SSL CERTIFICATE MANAGEMENT${NC}"
        echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
        echo ""
        echo "  1) Install Certbot"
        echo "  2) Generate SSL Certificate"
        echo "  3) Renew All Certificates"
        echo "  4) List All Certificates"
        echo "  5) Delete Certificate"
        echo "  0) Back to Main Menu"
        echo ""
        echo -n "Pilih menu [0-5]: "
        read ssl_choice
        
        case $ssl_choice in
            1) 
                apt install -y certbot python3-certbot-nginx
                echo -e "${GREEN}✓ Certbot installed${NC}"
                ;;
            2) 
                read -p "Domain name: " domain
                certbot --nginx -d "$domain" -d "www.$domain"
                ;;
            3) certbot renew ;;
            4) certbot certificates ;;
            5) 
                read -p "Domain name: " domain
                certbot delete --cert-name "$domain"
                ;;
            0) break ;;
            *) echo -e "${RED}Pilihan tidak valid${NC}" ;;
        esac
        
        if [[ $ssl_choice != "0" ]]; then
            read -p "Press Enter to continue..."
        fi
    done
}

# Server Monitoring
server_monitoring() {
    while true; do
        show_header
        echo -e "${YELLOW}SERVER MONITORING${NC}"
        echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
        echo ""
        echo "  1) System Resource (htop)"
        echo "  2) Disk Usage"
        echo "  3) Memory Usage"
        echo "  4) CPU Usage"
        echo "  5) Network Connections"
        echo "  6) Check All Services Status"
        echo "  7) View System Logs"
        echo "  0) Back to Main Menu"
        echo ""
        echo -n "Pilih menu [0-7]: "
        read mon_choice
        
        case $mon_choice in
            1) htop ;;
            2) df -h ;;
            3) free -h ;;
            4) top -bn1 | head -20 ;;
            5) netstat -tulpn ;;
            6) 
                echo -e "\n${YELLOW}Service Status:${NC}"
                echo "Nginx: $(systemctl is-active nginx)"
                echo "PHP 8.2: $(systemctl is-active php8.2-fpm)"
                echo "PHP 8.4: $(systemctl is-active php8.4-fpm)"
                echo "SQL Server: $(systemctl is-active mssql-server)"
                echo "Redis: $(systemctl is-active redis-server)"
                ;;
            7) journalctl -xe ;;
            0) break ;;
            *) echo -e "${RED}Pilihan tidak valid${NC}" ;;
        esac
        
        if [[ $mon_choice != "0" ]]; then
            read -p "Press Enter to continue..."
        fi
    done
}

# Backup & Restore
backup_restore() {
    while true; do
        show_header
        echo -e "${YELLOW}BACKUP & RESTORE${NC}"
        echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
        echo ""
        echo "  1) Backup Website Files"
        echo "  2) Backup SQL Server Database"
        echo "  3) Backup Nginx Config"
        echo "  4) Full System Backup"
        echo "  5) Restore Website Files"
        echo "  6) Restore SQL Server Database"
        echo "  0) Back to Main Menu"
        echo ""
        echo -n "Pilih menu [0-6]: "
        read backup_choice
        
        case $backup_choice in
            1) backup_website ;;
            2) backup_sqlserver ;;
            3) backup_nginx_config ;;
            4) full_backup ;;
            5) restore_website ;;
            6) restore_sqlserver ;;
            0) break ;;
            *) echo -e "${RED}Pilihan tidak valid${NC}" ;;
        esac
        
        if [[ $backup_choice != "0" ]]; then
            read -p "Press Enter to continue..."
        fi
    done
}

# Backup Website
backup_website() {
    echo ""
    read -p "Path website yang akan dibackup: " webpath
    backup_dir="/root/backups/websites"
    mkdir -p "$backup_dir"
    
    backup_file="$backup_dir/website-$(basename $webpath)-$(date +%Y%m%d-%H%M%S).tar.gz"
    tar -czf "$backup_file" -C "$(dirname $webpath)" "$(basename $webpath)"
    
    echo -e "${GREEN}✓ Backup berhasil: $backup_file${NC}"
}

# Backup SQL Server
backup_sqlserver() {
    echo ""
    read -p "Nama database: " dbname
    read -p "SA password: " -s sapass
    echo ""
    
    backup_dir="/root/backups/sqlserver"
    mkdir -p "$backup_dir"
    backup_file="$backup_dir/$dbname-$(date +%Y%m%d-%H%M%S).bak"
    
    /opt/mssql-tools18/bin/sqlcmd -S localhost -U SA -P "$sapass" -C \
        -Q "BACKUP DATABASE [$dbname] TO DISK = N'$backup_file' WITH FORMAT"
    
    echo -e "${GREEN}✓ Backup database berhasil: $backup_file${NC}"
}

# Backup Nginx Config
backup_nginx_config() {
    backup_dir="/root/backups/nginx"
    mkdir -p "$backup_dir"
    
    backup_file="$backup_dir/nginx-config-$(date +%Y%m%d-%H%M%S).tar.gz"
    tar -czf "$backup_file" /etc/nginx/
    
    echo -e "${GREEN}✓ Backup Nginx config berhasil: $backup_file${NC}"
}

# Full Backup
full_backup() {
    backup_dir="/root/backups/full"
    mkdir -p "$backup_dir"
    backup_file="$backup_dir/full-backup-$(date +%Y%m%d-%H%M%S).tar.gz"
    
    echo "Creating full backup..."
    tar -czf "$backup_file" /etc/nginx/ /var/www/ /etc/php/
    
    echo -e "${GREEN}✓ Full backup berhasil: $backup_file${NC}"
}

# Restore Website
restore_website() {
    echo ""
    ls -lh /root/backups/websites/ 2>/dev/null
    echo ""
    read -p "Path backup file: " backup_file
    read -p "Restore ke path: " restore_path
    
    tar -xzf "$backup_file" -C "$restore_path"
    chown -R www-data:www-data "$restore_path"
    
    echo -e "${GREEN}✓ Restore berhasil${NC}"
}

# Restore SQL Server
restore_sqlserver() {
    echo ""
    ls -lh /root/backups/sqlserver/ 2>/dev/null
    echo ""
    read -p "Path backup file: " backup_file
    read -p "Nama database: " dbname
    read -p "SA password: " -s sapass
    echo ""
    
    /opt/mssql-tools18/bin/sqlcmd -S localhost -U SA -P "$sapass" -C \
        -Q "RESTORE DATABASE [$dbname] FROM DISK = N'$backup_file' WITH REPLACE"
    
    echo -e "${GREEN}✓ Restore database berhasil${NC}"
}

# System Optimization
system_optimization() {
    while true; do
        show_header
        echo -e "${YELLOW}SYSTEM OPTIMIZATION${NC}"
        echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
        echo ""
        echo "  1) Optimize PHP-FPM Pool"
        echo "  2) Optimize Nginx Worker"
        echo "  3) Clear All Cache"
        echo "  4) Optimize MySQL/MariaDB"
        echo "  5) Clean System"
        echo "  6) Optimize Redis"
        echo "  0) Back to Main Menu"
        echo ""
        echo -n "Pilih menu [0-6]: "
        read opt_choice
        
        case $opt_choice in
            1) optimize_php_pool ;;
            2) optimize_nginx_worker ;;
            3) clear_all_cache ;;
            4) echo "MySQL/MariaDB not installed" ;;
            5) clean_system ;;
            6) optimize_redis ;;
            0) break ;;
            *) echo -e "${RED}Pilihan tidak valid${NC}" ;;
        esac
        
        if [[ $opt_choice != "0" ]]; then
            read -p "Press Enter to continue..."
        fi
    done
}

# Optimize PHP Pool
optimize_php_pool() {
    echo "Optimizing PHP-FPM pool..."
    
    # Calculate optimal values based on RAM
    total_ram=$(free -m | awk 'NR==2{print $2}')
    max_children=$((total_ram / 50))
    start_servers=$((max_children / 5))
    min_spare=$((start_servers / 2))
    max_spare=$((start_servers * 2))
    
    for php_ver in 8.2 8.4; do
        if [[ -f "/etc/php/$php_ver/fpm/pool.d/www.conf" ]]; then
            sed -i "s/pm.max_children = .*/pm.max_children = $max_children/" /etc/php/$php_ver/fpm/pool.d/www.conf
            sed -i "s/pm.start_servers = .*/pm.start_servers = $start_servers/" /etc/php/$php_ver/fpm/pool.d/www.conf
            sed -i "s/pm.min_spare_servers = .*/pm.min_spare_servers = $min_spare/" /etc/php/$php_ver/fpm/pool.d/www.conf
            sed -i "s/pm.max_spare_servers = .*/pm.max_spare_servers = $max_spare/" /etc/php/$php_ver/fpm/pool.d/www.conf
            systemctl restart php$php_ver-fpm
        fi
    done
    
    echo -e "${GREEN}✓ PHP-FPM pool optimized${NC}"
    echo "Max children: $max_children"
    echo "Start servers: $start_servers"
}

# Optimize Nginx Worker
optimize_nginx_worker() {
    cpu_cores=$(nproc)
    sed -i "s/worker_processes .*/worker_processes $cpu_cores;/" /etc/nginx/nginx.conf
    systemctl reload nginx
    
    echo -e "${GREEN}✓ Nginx worker optimized untuk $cpu_cores cores${NC}"
}

# Clear All Cache
clear_all_cache() {
    echo "Clearing caches..."
    
    # Clear Nginx cache
    rm -rf /var/cache/nginx/*
    
    # Clear PHP OPcache
    systemctl reload php8.2-fpm php8.4-fpm
    
    # Clear Redis cache
    redis-cli FLUSHALL
    
    # Clear system cache
    sync && echo 3 > /proc/sys/vm/drop_caches
    
    echo -e "${GREEN}✓ All caches cleared${NC}"
}

# Clean System
clean_system() {
    echo "Cleaning system..."
    
    apt autoremove -y
    apt autoclean -y
    apt clean
    
    # Clear old logs
    find /var/log -type f -name "*.log" -mtime +30 -delete
    journalctl --vacuum-time=7d
    
    echo -e "${GREEN}✓ System cleaned${NC}"
}

# Optimize Redis
optimize_redis() {
    echo "Optimizing Redis..."
    
    # Set maxmemory based on available RAM
    total_ram=$(free -m | awk 'NR==2{print $2}')
    redis_mem=$((total_ram / 8))
    
    redis-cli CONFIG SET maxmemory "${redis_mem}mb"
    redis-cli CONFIG SET maxmemory-policy allkeys-lru
    redis-cli CONFIG REWRITE
    
    echo -e "${GREEN}✓ Redis optimized with ${redis_mem}MB memory${NC}"
}

# Security Settings
security_settings() {
    while true; do
        show_header
        echo -e "${YELLOW}SECURITY SETTINGS${NC}"
        echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
        echo ""
        echo "  1) Setup Firewall (UFW)"
        echo "  2) Change SSH Port"
        echo "  3) Disable Root Login"
        echo "  4) Install Fail2Ban"
        echo "  5) Setup Auto Security Updates"
        echo "  6) Check Open Ports"
        echo "  0) Back to Main Menu"
        echo ""
        echo -n "Pilih menu [0-6]: "
        read sec_choice
        
        case $sec_choice in
            1) setup_firewall ;;
            2) change_ssh_port ;;
            3) disable_root_login ;;
            4) install_fail2ban ;;
            5) setup_auto_updates ;;
            6) netstat -tulpn ;;
            0) break ;;
            *) echo -e "${RED}Pilihan tidak valid${NC}" ;;
        esac
        
        if [[ $sec_choice != "0" ]]; then
            read -p "Press Enter to continue..."
        fi
    done
}

# Setup Firewall
setup_firewall() {
    apt install -y ufw
    
    ufw default deny incoming
    ufw default allow outgoing
    ufw allow 22/tcp
    ufw allow 80/tcp
    ufw allow 443/tcp
    ufw allow 1433/tcp
    
    read -p "Enable firewall? (y/n): " confirm
    if [[ $confirm == "y" ]]; then
        ufw --force enable
        echo -e "${GREEN}✓ Firewall enabled${NC}"
    fi
}

# Change SSH Port
change_ssh_port() {
    read -p "New SSH port (default 22): " new_port
    
    if [[ -n "$new_port" ]] && [[ "$new_port" != "22" ]]; then
        sed -i "s/#Port 22/Port $new_port/" /etc/ssh/sshd_config
        sed -i "s/Port 22/Port $new_port/" /etc/ssh/sshd_config
        
        systemctl restart sshd
        ufw allow $new_port/tcp
        
        echo -e "${GREEN}✓ SSH port changed to $new_port${NC}"
        echo -e "${YELLOW}PENTING: Jangan lupa update firewall rules!${NC}"
    fi
}

# Disable Root Login
disable_root_login() {
    sed -i 's/PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
    systemctl restart sshd
    echo -e "${GREEN}✓ Root login disabled${NC}"
}

# Install Fail2Ban
install_fail2ban() {
    apt install -y fail2ban
    systemctl enable fail2ban
    systemctl start fail2ban
    echo -e "${GREEN}✓ Fail2Ban installed and started${NC}"
}

# Setup Auto Updates
setup_auto_updates() {
    apt install -y unattended-upgrades
    dpkg-reconfigure -plow unattended-upgrades
    echo -e "${GREEN}✓ Auto security updates enabled${NC}"
}

# Update System
update_system() {
    show_header
    echo -e "${YELLOW}UPDATE SYSTEM${NC}"
    echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
    echo ""
    
    read -p "Update system sekarang? (y/n): " confirm
    if [[ $confirm == "y" ]]; then
        echo "Updating system..."
        apt update
        apt upgrade -y
        apt dist-upgrade -y
        apt autoremove -y
        
        echo -e "\n${GREEN}✓ System updated${NC}"
        
        read -p "Restart services? (y/n): " restart
        if [[ $restart == "y" ]]; then
            systemctl restart nginx php8.2-fpm php8.4-fpm redis-server
            echo -e "${GREEN}✓ Services restarted${NC}"
        fi
    fi
    
    read -p "Press Enter to continue..."
}

# Main Program
main() {
    check_root
    
    # Create log file if not exists
    touch "$LOG_FILE"
    
    while true; do
        show_main_menu
        read main_choice
        
        case $main_choice in
            1) install_full_stack ;;
            2) manage_nginx ;;
            3) manage_php ;;
            4) manage_sqlserver ;;
            5) manage_redis ;;
            6) manage_website ;;
            7) manage_ssl ;;
            8) server_monitoring ;;
            9) backup_restore ;;
            10) system_optimization ;;
            11) security_settings ;;
            12) update_system ;;
            0) 
                echo -e "\n${GREEN}Terima kasih telah menggunakan Server Manager!${NC}"
                log_message "Server Manager exited"
                exit 0
                ;;
            *) 
                echo -e "${RED}Pilihan tidak valid!${NC}"
                sleep 2
                ;;
        esac
    done
}

# Run main program
main