#!/bin/bash
#
# Synex Services Control v1.0
# Administración centralizada de servicios para Synex Server
#
# Soporta: SSH, SAMBA, NFS, FIREWALL (UFW), ACTUALIZACIONES AUTOMATICAS
#

set -e

# ============================================================================
# IMPORTS
# ============================================================================

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
COMMON_LIB="${SCRIPT_DIR}/../lib/common.sh"

if [ ! -f "$COMMON_LIB" ]; then
    echo "Error: common.sh not found at $COMMON_LIB"
    exit 1
fi

source "$COMMON_LIB"

# ============================================================================
# GLOBAL VARIABLES
# ============================================================================

# Services array with package names and systemd service names
declare -A SERVICE_DISPLAY_KEYS=(
    [ssh]="service_ssh"
    [samba]="service_samba"
    [nfs]="service_nfs"
    [firewall]="service_firewall"
    [updates]="service_updates"
)

# Service package:systemd pairs
declare -A SERVICES=(
    [ssh]="openssh-server:ssh"
    [samba]="samba:smbd"
    [nfs]="nfs-kernel-server:nfs-server"
    [firewall]="nftables:nftables"
    [updates]="unattended-upgrades:unattended-upgrades"
)

# Service display names
declare -A SERVICE_NAMES=(
    [ssh]="SSH"
    [samba]="SAMBA"
    [nfs]="NFS"
    [firewall]="FIREWALL (nftables)"
    [updates]="ACTUALIZACIONES AUTOMATICAS"
)

# ============================================================================
# SERVICE STATUS FUNCTIONS
# ============================================================================

is_service_installed() {
    local package="$1"
    dpkg -l 2>/dev/null | grep -q "^ii.*$package" && return 0 || return 1
}

is_service_enabled() {
    local service="$1"
    systemctl is-enabled "$service" >/dev/null 2>&1 && return 0 || return 1
}

is_service_active() {
    local service="$1"
    systemctl is-active "$service" >/dev/null 2>&1 && return 0 || return 1
}

get_service_status() {
    local service_key="$1"
    local package="${SERVICES[$service_key]%%:*}"
    local service_name="${SERVICES[$service_key]##*:}"

    if ! is_service_installed "$package"; then
        echo "not_installed"
    elif is_service_active "$service_name"; then
        echo "active"
    else
        echo "inactive"
    fi
}

# ============================================================================
# DISPLAY FUNCTIONS
# ============================================================================

show_status_all() {
    show_header
    print_info "$(msg view_all_status)"
    echo ""
    echo "|------------------------------------------------------------------------------------"

    for service_key in ssh samba nfs firewall updates; do
        local status=$(get_service_status "$service_key")
        local display_key="${SERVICE_DISPLAY_KEYS[$service_key]}"
        local display_name="$(msg $display_key)"

        case "$status" in
            active)
                echo -n "| $display_name"
                echo -n "$(printf '%*s' $((50 - ${#display_name})) '')"
                print_success "$(msg status_active)"
                ;;
            inactive)
                echo -n "| $display_name"
                echo -n "$(printf '%*s' $((50 - ${#display_name})) '')"
                print_warning "$(msg status_inactive)"
                ;;
            not_installed)
                echo -n "| $display_name"
                echo -n "$(printf '%*s' $((50 - ${#display_name})) '')"
                print_error "$(msg status_not_installed)"
                ;;
        esac
    done

    echo "|------------------------------------------------------------------------------------"
    echo ""
    pause_execution
}

# ============================================================================
# MAIN MENU
# ============================================================================

show_main_menu() {
    show_header
    print_info "$(msg services_menu)"
    echo ""
    echo "  1) $(msg view_all_status)"
    echo "  2) $(msg service_ssh)"
    echo "  3) $(msg service_samba)"
    echo "  4) $(msg service_nfs)"
    echo "  5) $(msg service_firewall)"
    echo "  6) $(msg service_updates)"
    echo ""
    echo -e "  ${YELLOW}0) $(msg menu_back-control)${NC}"
    echo ""
}

# ============================================================================
# PLACEHOLDER FUNCTIONS (se implementan luego)
# ============================================================================

# ============================================================================
# SSH MENU
# ============================================================================

get_ssh_status() {
    local package="openssh-server"
    local service="ssh"

    if ! is_service_installed "$package"; then
        echo "not_installed"
        return
    fi

    if is_service_active "$service"; then
        echo "active"
    else
        echo "inactive"
    fi
}

get_ssh_current_settings() {
    # Get effective SSH configuration
    local port=$(sshd -T 2>/dev/null | grep "^port" | awk '{print $2}')
    local permit_root=$(sshd -T 2>/dev/null | grep "^permitrootlogin" | awk '{print $2}')
    local password_auth=$(sshd -T 2>/dev/null | grep "^passwordauthentication" | awk '{print $2}')

    echo "$port|$permit_root|$password_auth"
}

show_ssh_status() {
    local status=$(get_ssh_status)
    local settings=$(get_ssh_current_settings)

    IFS='|' read -r port permit_root password_auth <<< "$settings"

    show_header
    print_info "$(msg ssh_title)"
    echo ""

    # Service status
    case "$status" in
        active)
            echo -e "${GREEN}[+] $(msg service_active)${NC}"
            ;;
        inactive)
            echo -e "${YELLOW}[-] $(msg service_inactive)${NC}"
            ;;
        not_installed)
            echo -e "${RED}[X] $(msg service_not_installed)${NC}"
            return
            ;;
    esac

    echo ""
    echo "$(msg ssh_port): $port"
    echo "$(msg ssh_permit_root): $permit_root"
    echo "$(msg ssh_password_auth): $password_auth"
    echo ""
}

install_and_enable_ssh() {
    print_info "$(msg service_installing)"
    apt-get update >/dev/null 2>&1
    apt-get install -y openssh-server >/dev/null 2>&1

    print_success "$(msg service_installed_success)"
    systemctl enable ssh >/dev/null 2>&1
    systemctl start ssh >/dev/null 2>&1
    print_success "$(msg service_started)"
    log_message "INFO" "SSH installed and started"
}

enable_ssh() {
    if [ "$(get_ssh_status)" = "not_installed" ]; then
        install_and_enable_ssh
    else
        print_info "$(msg service_activating)"
        systemctl enable ssh >/dev/null 2>&1
        systemctl start ssh >/dev/null 2>&1
        print_success "$(msg service_started)"
        print_success "$(msg service_enabled_boot)"
        log_message "INFO" "SSH enabled and started"
    fi
}

disable_ssh() {
    print_info "$(msg service_deactivating)"
    systemctl stop ssh >/dev/null 2>&1
    systemctl disable ssh >/dev/null 2>&1
    print_success "$(msg service_stopped)"
    print_success "$(msg service_disabled_boot)"
    log_message "INFO" "SSH disabled and stopped"
}

configure_ssh_port() {
    show_ssh_status

    local current_port=$(sshd -T 2>/dev/null | grep "^port" | awk '{print $2}')
    echo "$(msg ssh_port_change)"
    read_input_with_escape "$(msg ssh_new_port) (actual: $current_port)"
    local new_port="$READ_INPUT"

    if [ -z "$new_port" ] || [ "$new_port" = "ESC" ] || [ "$new_port" = "BACK" ]; then
        return
    fi

    # Validate port number
    if ! [[ "$new_port" =~ ^[0-9]+$ ]] || [ "$new_port" -lt 1 ] || [ "$new_port" -gt 65535 ]; then
        print_error "$(msg ssh_invalid_port)"
        pause_execution
        return
    fi

    if [ "$new_port" = "$current_port" ]; then
        print_info "$(msg ssh_port_unchanged)"
        pause_execution
        return
    fi

    # Create config directory if not exists
    mkdir -p /etc/ssh/sshd_config.d

    # Add port configuration to synex.conf
    echo "Port $new_port" > /etc/ssh/sshd_config.d/synex.conf

    # Restart SSH
    systemctl restart ssh >/dev/null 2>&1

    print_success "$(msg ssh_port_change)"
    print_info "$(msg ssh_port_changed_to) $new_port"
    log_message "INFO" "SSH port changed from $current_port to $new_port"
    pause_execution
}

configure_ssh_permit_root() {
    show_ssh_status

    local current=$(sshd -T 2>/dev/null | grep "^permitrootlogin" | awk '{print $2}')
    echo ""
    echo "$(msg ssh_permit_root_change)"
    echo "  1) $(msg option_yes)"
    echo "  2) $(msg option_no)"
    echo ""
    read_input_with_escape "$(msg select_option)"
    local choice="$READ_INPUT"

    # Check if cancelled
    if [ "$choice" = "ESC" ] || [ "$choice" = "BACK" ]; then
        return
    fi

    local new_value=""
    case "$choice" in
        1) new_value="yes" ;;
        2) new_value="no" ;;
        *)
            print_error "$(msg invalid_option)"
            pause_execution
            return
            ;;
    esac

    if [ "$new_value" = "$current" ]; then
        print_info "$(msg config_value_unchanged)"
        pause_execution
        return
    fi

    # Create config directory if not exists
    mkdir -p /etc/ssh/sshd_config.d

    # Add to synex.conf (preserve other settings)
    if [ -f /etc/ssh/sshd_config.d/synex.conf ]; then
        sed -i "/^PermitRootLogin/d" /etc/ssh/sshd_config.d/synex.conf
    fi
    echo "PermitRootLogin $new_value" >> /etc/ssh/sshd_config.d/synex.conf

    # Restart SSH
    systemctl restart ssh >/dev/null 2>&1

    print_success "$(msg ssh_permit_root_changed_to) $new_value"
    log_message "INFO" "SSH PermitRootLogin changed to $new_value"
    pause_execution
}

configure_ssh_password_auth() {
    show_ssh_status

    local current=$(sshd -T 2>/dev/null | grep "^passwordauthentication" | awk '{print $2}')
    echo ""
    echo "$(msg ssh_password_auth_change)"
    echo "  1) $(msg option_yes)"
    echo "  2) $(msg option_no)"
    echo ""
    read_input_with_escape "$(msg select_option)"
    local choice="$READ_INPUT"

    # Check if cancelled
    if [ "$choice" = "ESC" ] || [ "$choice" = "BACK" ]; then
        return
    fi

    local new_value=""
    case "$choice" in
        1) new_value="yes" ;;
        2) new_value="no" ;;
        *)
            print_error "$(msg invalid_option)"
            pause_execution
            return
            ;;
    esac

    if [ "$new_value" = "$current" ]; then
        print_info "$(msg config_value_unchanged)"
        pause_execution
        return
    fi

    # Create config directory if not exists
    mkdir -p /etc/ssh/sshd_config.d

    # Add to synex.conf (preserve other settings)
    if [ -f /etc/ssh/sshd_config.d/synex.conf ]; then
        sed -i "/^PasswordAuthentication/d" /etc/ssh/sshd_config.d/synex.conf
    fi
    echo "PasswordAuthentication $new_value" >> /etc/ssh/sshd_config.d/synex.conf

    # Restart SSH
    systemctl restart ssh >/dev/null 2>&1

    print_success "$(msg ssh_password_auth_change) $new_value"
    log_message "INFO" "SSH PasswordAuthentication changed to $new_value"
    pause_execution
}

menu_ssh() {
    breadcrumb_push "SSH"

    while true; do
        show_ssh_status

        echo "  1) $(msg activate_service)"
        echo "  2) $(msg deactivate_service)"
        echo "  3) $(msg configure_service)"
        echo ""
echo -e "  ${YELLOW}0) $(msg back)${NC}"
        echo ""
        read_menu_option "$(msg select_option): "
        local choice="$MENU_INPUT"

        [[ "$choice" == "ESC" || "$choice" == "0" ]] && {
            breadcrumb_pop
            break
        }

        case "$choice" in
            1)
                enable_ssh
                pause_execution
                ;;
            2)
                disable_ssh
                pause_execution
                ;;
            3)
                breadcrumb_push "$(msg configure_service)"
                while true; do
                    show_ssh_status
                    echo ""
                    echo "  1) $(msg ssh_port_change)"
                    echo "  2) $(msg ssh_permit_root_change)"
                    echo "  3) $(msg ssh_password_auth_change)"
                    echo ""
                    echo -e "  ${YELLOW}0) $(msg back)${NC}"
                    echo ""
                    read_menu_option "$(msg select_option): "
                    local config_choice="$MENU_INPUT"

                    [[ "$config_choice" == "ESC" || "$config_choice" == "0" ]] && break

                    case "$config_choice" in
                        1) configure_ssh_port ;;
                        2) configure_ssh_permit_root ;;
                        3) configure_ssh_password_auth ;;
                        *)
                            print_error "$(msg invalid_option)"
                            pause_execution
                            ;;
                    esac
                done
                breadcrumb_pop
                ;;
            *)
                print_error "$(msg invalid_option)"
                pause_execution
                ;;
        esac
    done
}


#menu_ssh() {
#    show_header
#    print_info "$(msg ssh_title)"
#    echo ""
#    print_warning "[SSH - IMPLEMENTACION EN PROGRESO]"
#    echo ""
#    pause_execution
#}

# ============================================================================
# SAMBA MODULE - SERVICE MANAGEMENT
# ============================================================================

# Global variables
SAMBA_BASE_DIR="/srv/samba"
SAMBA_CONFIG="/etc/samba/smb.conf"
SAMBA_BACKUP_DIR="/etc/samba/backups"

# ============================================================================
# UTILITY FUNCTIONS
# ============================================================================

# Check if Samba is installed
is_samba_installed() {
    dpkg -l | grep -q "^ii.*samba " && dpkg -l | grep -q "^ii.*samba-common-bin "
}

# Get Samba service status
get_samba_status() {
    if ! is_samba_installed; then
        echo "not_installed"
        return
    fi

    if systemctl is-active --quiet smbd && systemctl is-active --quiet nmbd; then
        echo "active"
    else
        echo "inactive"
    fi
}

# Count configured shares (excluding defaults)
count_samba_shares() {
    if [ ! -f "$SAMBA_CONFIG" ]; then
        echo "0"
        return
    fi

    # Count sections excluding [global], [homes], [printers]
    grep -c "^\[" "$SAMBA_CONFIG" | awk '{print $1-1}' || echo "0"
}

# Count Samba users
count_samba_users() {
    pdbedit -L 2>/dev/null | wc -l || echo "0"
}

# Get current workgroup
get_samba_workgroup() {
    testparm -s --parameter-name=workgroup 2>/dev/null || echo "WORKGROUP"
}

# Get server description
get_samba_description() {
    testparm -s --parameter-name="server string" 2>/dev/null || echo "Samba Server"
}

# Get NetBIOS name
get_samba_netbios_name() {
    testparm -s --parameter-name="netbios name" 2>/dev/null || hostname
}

# Validate share name (alphanumeric, hyphens, underscores)
validate_share_name() {
    local name="$1"

    # Check if empty
    if [ -z "$name" ]; then
        return 1
    fi

    # Check format (alphanumeric + hyphen + underscore)
    if ! echo "$name" | grep -qE '^[a-zA-Z0-9_-]+$'; then
        return 1
    fi

    # Check reserved names
    case "$name" in
        global|homes|printers|print$)
            return 1
            ;;
    esac

    return 0
}

# Check if share exists
share_exists() {
    local share_name="$1"
    grep -qE "^\[$share_name\]" "$SAMBA_CONFIG" 2>/dev/null
}

# Check if user exists in system
user_exists_in_system() {
    local username="$1"
    id "$username" >/dev/null 2>&1
}

# Check if user exists in Samba
user_exists_in_samba() {
    local username="$1"
    pdbedit -L 2>/dev/null | grep -q "^$username:"
}

# Validate IP or subnet format
validate_ip_subnet() {
    local input="$1"

    # Simple validation for IP or CIDR
    if echo "$input" | grep -qE '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}(/[0-9]{1,2})?$'; then
        return 0
    fi

    return 1
}

# ============================================================================
# BACKUP AND VALIDATION FUNCTIONS
# ============================================================================

# Create backup of smb.conf
backup_samba_config() {
    mkdir -p "$SAMBA_BACKUP_DIR"
    local timestamp=$(date +%Y%m%d-%H%M%S)
    local backup_file="$SAMBA_BACKUP_DIR/smb.conf.backup-$timestamp"

    if [ -f "$SAMBA_CONFIG" ]; then
        cp "$SAMBA_CONFIG" "$backup_file"
        log_message "INFO" "Samba config backed up to $backup_file"
        echo "$backup_file"
    fi
}

# Restore last backup
restore_samba_backup() {
    local backup_file="$1"

    if [ -f "$backup_file" ]; then
        cp "$backup_file" "$SAMBA_CONFIG"
        log_message "INFO" "Samba config restored from $backup_file"
        return 0
    fi

    return 1
}

# Validate Samba configuration
validate_samba_config() {
    testparm -s "$SAMBA_CONFIG" >/dev/null 2>&1
    return $?
}

# Reload Samba configuration safely
reload_samba_config() {
    # Backup first
    local backup_file=$(backup_samba_config)

    # Validate
    if ! validate_samba_config; then
        print_error "$(msg samba_config_invalid)"

        # Show errors
        echo ""
        testparm -s "$SAMBA_CONFIG" 2>&1 | grep -i "error\|warning" | head -5
        echo ""

        # Restore backup
        if [ -n "$backup_file" ]; then
            restore_samba_backup "$backup_file"
            print_info "$(msg samba_config_restored)"
        fi

        return 1
    fi

    # Reload services
    systemctl reload smbd nmbd >/dev/null 2>&1
    print_success "$(msg samba_config_reloaded)"
    log_message "INFO" "Samba configuration reloaded successfully"
    return 0
}

# ============================================================================
# STATUS AND LISTING FUNCTIONS
# ============================================================================

# Show main status
show_samba_status() {
    local status=$(get_samba_status)
    local shares=$(count_samba_shares)
    local users=$(count_samba_users)
    local workgroup=$(get_samba_workgroup)

    show_header
    print_info "$(msg samba_status_title)"
    echo ""

    # Service status
    case "$status" in
        active)
            echo -e "${GREEN}[+] $(msg service_active)${NC}"
            ;;
        inactive)
            echo -e "${YELLOW}[-] $(msg service_inactive)${NC}"
            ;;
        not_installed)
            echo -e "${RED}[X] $(msg service_not_installed)${NC}"
            echo ""
            return
            ;;
    esac

    echo ""
    echo "$(msg samba_shares_configured): $shares"
    echo "$(msg samba_users_total): $users"
    echo "$(msg samba_workgroup): $workgroup"
    echo ""
}

# List all shares with details
list_samba_shares() {
    print_info "$(msg samba_shares_list)"
    echo ""

    if [ ! -f "$SAMBA_CONFIG" ]; then
        print_info "$(msg samba_no_shares)"
        return
    fi

    # Parse smb.conf for shares
    local in_share=0
    local share_name=""
    local share_path=""
    local share_users=""
    local share_public=""

    while IFS= read -r line; do
        # Detect share section
        if echo "$line" | grep -qE '^\[.*\]'; then
            # Print previous share if exists
            if [ -n "$share_name" ] && [ "$share_name" != "global" ]; then
                local access_type="$(msg samba_private)"
                if [ "$share_public" = "yes" ]; then
                    access_type="$(msg samba_public)"
                fi

                printf "  [%-15s] %-30s %s\n" "$share_name" "$share_path" "$access_type"
                if [ -n "$share_users" ]; then
                    printf "                  $(msg samba_users): %s\n" "$share_users"
                fi
            fi

            # Start new share
            share_name=$(echo "$line" | sed 's/^\[\(.*\)\]/\1/')
            share_path=""
            share_users=""
            share_public="no"
        fi

        # Parse share parameters
        if [ -n "$share_name" ] && [ "$share_name" != "global" ]; then
            if echo "$line" | grep -qE '^\s*path\s*='; then
                share_path=$(echo "$line" | sed 's/.*=\s*//')
            fi
            if echo "$line" | grep -qE '^\s*valid users\s*='; then
                share_users=$(echo "$line" | sed 's/.*=\s*//')
            fi
            if echo "$line" | grep -qE '^\s*guest ok\s*=\s*yes'; then
                share_public="yes"
            fi
        fi
    done < "$SAMBA_CONFIG"

    # Print last share
    if [ -n "$share_name" ] && [ "$share_name" != "global" ]; then
        local access_type="$(msg samba_private)"
        if [ "$share_public" = "yes" ]; then
            access_type="$(msg samba_public)"
        fi

        printf "  [%-15s] %-30s %s\n" "$share_name" "$share_path" "$access_type"
        if [ -n "$share_users" ]; then
            printf "                  $(msg samba_users): %s\n" "$share_users"
        fi
    fi

    echo ""
}

# List all Samba users
list_samba_users() {
    print_info "$(msg samba_users_list)"
    echo ""

    if ! pdbedit -L >/dev/null 2>&1; then
        print_info "$(msg samba_no_users)"
        return
    fi

    pdbedit -L 2>/dev/null | while IFS=: read -r username uid desc; do
        local system_user="[+]"
        if ! user_exists_in_system "$username"; then
            system_user="[X]"
        fi
        printf "  %-20s %s $(msg samba_system_user)\n" "$username" "$system_user"
    done

    echo ""
}

# ============================================================================
# SHARE MANAGEMENT FUNCTIONS
# ============================================================================

# Get share details
get_share_details() {
    local share_name="$1"

    if ! share_exists "$share_name"; then
        return 1
    fi

    echo ""
    print_info "$(msg samba_share_details): [$share_name]"
    echo ""

    # Extract share configuration and format with colors
    local in_section=0
    local comment="" path="" browseable="" valid_users="" read_only="" 
    local create_mask="" directory_mask="" hosts_allow=""
    
    while IFS= read -r line; do
        if echo "$line" | grep -qE "^\[$share_name\]"; then
            in_section=1
            continue
        fi

        if [ $in_section -eq 1 ]; then
            if echo "$line" | grep -qE '^\[.*\]'; then
                break
            fi

            # Parse configuration lines
            if echo "$line" | grep -qE '^\s*comment\s*='; then
                comment=$(echo "$line" | sed 's/.*=\s*//')
            elif echo "$line" | grep -qE '^\s*path\s*='; then
                path=$(echo "$line" | sed 's/.*=\s*//')
            elif echo "$line" | grep -qE '^\s*browseable\s*='; then
                browseable=$(echo "$line" | sed 's/.*=\s*//')
            elif echo "$line" | grep -qE '^\s*valid users\s*='; then
                valid_users=$(echo "$line" | sed 's/.*=\s*//')
            elif echo "$line" | grep -qE '^\s*read only\s*='; then
                read_only=$(echo "$line" | sed 's/.*=\s*//')
            elif echo "$line" | grep -qE '^\s*create mask\s*='; then
                create_mask=$(echo "$line" | sed 's/.*=\s*//')
            elif echo "$line" | grep -qE '^\s*directory mask\s*='; then
                directory_mask=$(echo "$line" | sed 's/.*=\s*//')
            elif echo "$line" | grep -qE '^\s*hosts allow\s*='; then
                hosts_allow=$(echo "$line" | sed 's/.*=\s*//')
            fi
        fi
    done < "$SAMBA_CONFIG"

    # Display formatted information with colors
    echo -e "${BLUE}$(msg samba_share_information)${NC}"
    echo ""
    echo -e "  ${GREEN}> $(msg samba_share_name):${NC} $share_name"
    echo ""
    
    if [ -n "$path" ]; then
        echo -e "  ${GREEN}|- $(msg samba_path):${NC} $path"
    fi
    if [ -n "$comment" ]; then
        echo -e "  ${GREEN}|- $(msg samba_description):${NC} $comment"
    fi
    
    # Access type
    if [ "$valid_users" ]; then
        echo -e "  ${GREEN}|- $(msg samba_type):${NC} $(msg samba_type_private)"
        echo -e "  ${GREEN}|  $(msg samba_users):${NC} $valid_users"
    else
        if [ "$read_only" = "yes" ]; then
            echo -e "  ${GREEN}|- $(msg samba_type):${NC} $(msg samba_type_public_ro)"
        else
            echo -e "  ${GREEN}|- $(msg samba_type):${NC} $(msg samba_type_public_rw)"
        fi
    fi
    
    # Permissions
    if [ "$read_only" = "yes" ]; then
        echo -e "  ${GREEN}|- $(msg samba_permissions):${NC} $(msg samba_read_only)"
    else
        echo -e "  ${GREEN}|- $(msg samba_permissions):${NC} $(msg samba_read_write)"
    fi
    
    # Network visibility
    if [ "$browseable" = "no" ]; then
        echo -e "  ${GREEN}|- $(msg samba_browseable):${NC} $(msg no)"
    else
        echo -e "  ${GREEN}|- $(msg samba_browseable):${NC} $(msg yes)"
    fi
    
    # Hosts restriction
    if [ -n "$hosts_allow" ]; then
        echo -e "  ${GREEN}|- $(msg samba_allowed_hosts):${NC} $hosts_allow"
    fi
    
    # File permissions
    if [ -n "$create_mask" ]; then
        echo -e "  ${GREEN}|- $(msg samba_file_mask):${NC} $create_mask"
    fi
    if [ -n "$directory_mask" ]; then
        echo -e "  ${GREEN}'- $(msg samba_directory_mask):${NC} $directory_mask"
    fi

    echo ""
}

# Helper function for pager
get_share_details_and_pause() {
    local share_name="$1"
    get_share_details "$share_name"
    echo "$(msg info_go_back)"
    read_menu_option ""
}

# Create directory structure for share
create_share_directory() {
    local dir_name="$1"
    local share_type="$2"  # ← NUEVO PARÁMETRO
    local full_path="$SAMBA_BASE_DIR/$dir_name"

    # Create base directory if doesn't exist
    if [ ! -d "$SAMBA_BASE_DIR" ]; then
        mkdir -p "$SAMBA_BASE_DIR"
    fi

    # Create share directory
    mkdir -p "$full_path"

    # Set ownership and permissions based on share type
    case "$share_type" in
        public_ro|public_rw)
            # Public shares: accessible by guest (nobody)
            chown nobody:nogroup "$full_path"
            chmod 2775 "$full_path"
            log_message "INFO" "Created public share directory: $full_path"
            ;;
        private|*)
            # Private shares: restricted to sambashare group
            chown root:sambashare "$full_path"
            chmod 2770 "$full_path"
            log_message "INFO" "Created private share directory: $full_path"
            ;;
    esac

    echo "$full_path"
}

# Add share to smb.conf
add_share_to_config() {
    local share_name="$1"
    local share_path="$2"
    local share_comment="$3"
    local share_type="$4"
    local valid_users="$5"
    local read_only="$6"
    local browseable="$7"
    local recycle="$8"
    local hosts_allow="$9"

    # Start share section
    cat >> "$SAMBA_CONFIG" << EOF

[$share_name]
    comment = $share_comment
    path = $share_path
    browseable = $browseable
EOF

    # Configure access type
    case "$share_type" in
        public_ro)
            cat >> "$SAMBA_CONFIG" << EOF
    guest ok = yes
    read only = yes
    create mask = 0644
    directory mask = 0755
EOF
            ;;
        public_rw)
            cat >> "$SAMBA_CONFIG" << EOF
    guest ok = yes
    read only = no
    create mask = 0664
    directory mask = 2775
EOF
            ;;
        private)
            cat >> "$SAMBA_CONFIG" << EOF
    valid users = $valid_users
    read only = $read_only
    create mask = 0664
    directory mask = 2775
EOF
            ;;
    esac

    # Add recycle bin if enabled
    if [ "$recycle" = "yes" ]; then
        cat >> "$SAMBA_CONFIG" << EOF
    vfs objects = recycle
    recycle:repository = .recycle
    recycle:keeptree = yes
    recycle:versions = yes
    recycle:touch = yes
EOF
    fi

    # Add host restrictions if specified
    if [ -n "$hosts_allow" ]; then
        cat >> "$SAMBA_CONFIG" << EOF
    hosts allow = $hosts_allow
    hosts deny = all
EOF
    fi
}

# Delete share from smb.conf
delete_share_from_config() {
    local share_name="$1"
    local temp_file=$(mktemp)

    # Remove share section
    awk -v share="[$share_name]" '
        $0 ~ "^\\[" {in_section=0}
        $0 == share {in_section=1; next}
        !in_section {print}
    ' "$SAMBA_CONFIG" > "$temp_file"

    mv "$temp_file" "$SAMBA_CONFIG"
}

# ============================================================================
# SHARE CREATION WIZARD
# ============================================================================

create_samba_share_wizard() {
    show_header
    print_info "$(msg samba_create_share_wizard)"
    echo ""

    # STEP 1: Share name
    local share_name=""
    while true; do
        echo "$(msg samba_wizard_step) 1/9: $(msg samba_share_name)"
        echo ""
        read_input_with_escape "$(msg samba_share_name_prompt)"
        share_name="$READ_INPUT"

        if [ -z "$share_name" ] || [ "$share_name" = "ESC" ] || [ "$share_name" = "BACK" ]; then
            print_info "$(msg operation_cancelled)"
            pause_execution
            return
        fi

        if ! validate_share_name "$share_name"; then
            print_error "$(msg samba_invalid_share_name)"
            echo ""
            continue
        fi

        if share_exists "$share_name"; then
            print_error "$(msg samba_share_exists)"
            echo ""
            continue
        fi

        break
    done

    # STEP 2: Directory name
    echo ""
    echo "$(msg samba_wizard_step) 2/9: $(msg samba_directory_name)"
    echo "$(msg samba_base_path): $SAMBA_BASE_DIR/"
    echo ""
    read_input_with_escape "$(msg samba_directory_prompt) [$share_name]"
    local dir_name="$READ_INPUT"
    [ "$dir_name" = "ESC" ] || [ "$dir_name" = "BACK" ] && return
    dir_name=${dir_name:-$share_name}

    local full_path="$SAMBA_BASE_DIR/$dir_name"

    # STEP 3: Description
    echo ""
    echo "$(msg samba_wizard_step) 3/9: $(msg samba_description)"
    echo ""
    read_input_with_escape "$(msg samba_description_prompt)"
    local share_comment="$READ_INPUT"
    [ "$share_comment" = "ESC" ] || [ "$share_comment" = "BACK" ] && return
    share_comment=${share_comment:-"Samba Share"}

    # STEP 4: Access type
    local share_type=""
    while true; do
        echo ""
        echo "$(msg samba_wizard_step) 4/9: $(msg samba_access_type)"
        echo ""
        echo "  1) $(msg samba_public_ro)"
        echo "  2) $(msg samba_public_rw)"
        echo "  3) $(msg samba_private)"
        echo ""
        read_menu_option "$(msg select_option): "
        local access_choice="$MENU_INPUT"

        [ "$access_choice" = "ESC" ] && return

        case "$access_choice" in
            1) share_type="public_ro"; break ;;
            2) share_type="public_rw"; break ;;
            3) share_type="private"; break ;;
            *) print_error "$(msg invalid_option)" ;;
        esac
    done

    # STEP 5: Valid users (only if private)
    local valid_users=""
    local read_only="no"

    if [ "$share_type" = "private" ]; then
        echo ""
        echo "$(msg samba_wizard_step) 5/9: $(msg samba_valid_users)"
        echo ""
        echo "$(msg samba_available_users):"
        pdbedit -L 2>/dev/null | cut -d: -f1 | sed 's/^/  - /'
        echo ""
        read_input_with_escape "$(msg samba_valid_users_prompt)"
        valid_users="$READ_INPUT"

        if [ -z "$valid_users" ] || [ "$valid_users" = "ESC" ] || [ "$valid_users" = "BACK" ]; then
            [ "$valid_users" != "ESC" ] && [ "$valid_users" != "BACK" ] && print_error "$(msg samba_no_users_specified)"
            pause_execution
            return
        fi

        # Validar cada usuario
        for user in $valid_users; do
            # Saltar grupos (@grupo)
            if [[ "$user" == @* ]]; then
                continue
            fi

            # Verificar si existe en Samba
            if ! user_exists_in_samba "$user"; then
                echo ""
                print_warning "$(printf "$(msg samba_user_not_in_samba)" "$user")"

                # Verificar si existe en sistema
                if ! user_exists_in_system "$user"; then
                    echo ""
                    read_input_with_escape "$(printf "$(msg samba_create_system_user_prompt)" "$user")"
                    local create_sys="$READ_INPUT"
                    [ "$create_sys" = "ESC" ] || [ "$create_sys" = "BACK" ] && return
                    if [ "$create_sys" = "s" ] || [ "$create_sys" = "S" ] || [ "$create_sys" = "y" ] || [ "$create_sys" = "Y" ]; then
                        useradd -M -s /usr/sbin/nologin "$user"
                        print_success "$(msg samba_system_user_created)"
                    else
                        print_error "$(msg samba_system_user_required)"
                        pause_execution
                        return
                    fi
                fi

                # Agregar al grupo sambashare
                usermod -aG sambashare "$user"
                print_success "$(msg samba_user_added_to_group)"

                # Establecer contraseña Samba
                echo ""
                print_info "$(printf "$(msg samba_set_password_for)" "$user")"
                echo ""
                smbpasswd -a "$user"

                if [ $? -ne 0 ]; then
                    print_error "$(msg samba_user_config_failed)"
                    pause_execution
                    return
                fi

                print_success "$(printf "$(msg samba_user_configured)" "$user")"
            fi
        done

        # STEP 6: Permissions
        echo ""
        echo "$(msg samba_wizard_step) 6/9: $(msg samba_permissions)"
        echo ""
        echo "  1) $(msg samba_read_only)"
        echo "  2) $(msg samba_read_write)"
        echo ""
        read_menu_option "$(msg select_option): "
        local perm_choice="$MENU_INPUT"
        [ "$perm_choice" = "ESC" ] && return

        case "$perm_choice" in
            1) read_only="yes" ;;
            2) read_only="no" ;;
            *) read_only="no" ;;
        esac
    else
        echo ""
        echo "$(msg samba_wizard_step) 5/9: $(msg samba_valid_users)"
        echo "$(msg samba_skipped_public)"
        echo ""
        echo "$(msg samba_wizard_step) 6/9: $(msg samba_permissions)"
        echo "$(msg samba_skipped_public)"
    fi

    # STEP 7: IP restrictions
    echo ""
    echo "$(msg samba_wizard_step) 7/9: $(msg samba_ip_restrictions)"
    echo ""
    echo "  1) $(msg samba_allow_all_ips)"
    echo "  2) $(msg samba_restrict_ips)"
    echo ""
    read_menu_option "$(msg select_option) [1]: "
    local ip_choice="$MENU_INPUT"
    [ "$ip_choice" = "ESC" ] && return
    ip_choice=${ip_choice:-1}

    local hosts_allow=""
    if [ "$ip_choice" = "2" ]; then
        echo ""
        read_input_with_escape "$(msg samba_hosts_allow_prompt)"
        hosts_allow="$READ_INPUT"
        [ "$hosts_allow" = "ESC" ] || [ "$hosts_allow" = "BACK" ] && return
    fi

    # STEP 8: Recycle bin
    echo ""
    echo "$(msg samba_wizard_step) 8/9: $(msg samba_recycle_bin)"
    echo ""
    read_input_with_escape "$(msg samba_enable_recycle) (s/n) [n]"
    local recycle_choice="$READ_INPUT"
    [ "$recycle_choice" = "ESC" ] || [ "$recycle_choice" = "BACK" ] && return
    local recycle="no"
    if [ "$recycle_choice" = "s" ] || [ "$recycle_choice" = "S" ]; then
        recycle="yes"
    fi

    # STEP 9: Browseable
    echo ""
    echo "$(msg samba_wizard_step) 9/9: $(msg samba_browseable)"
    echo ""
    read_input_with_escape "$(msg samba_visible_network) (s/n) [s]"
    local browse_choice="$READ_INPUT"
    [ "$browse_choice" = "ESC" ] || [ "$browse_choice" = "BACK" ] && return
    local browseable="yes"
    if [ "$browse_choice" = "n" ] || [ "$browse_choice" = "N" ]; then
        browseable="no"
    fi

    # SUMMARY
    echo ""
    print_info "$(msg samba_summary)"
    echo ""
    echo -e "  ${BLUE}$(msg samba_share_name):${NC} ${GREEN}$share_name${NC}"
    echo -e "  ${BLUE}$(msg samba_path):${NC} ${GREEN}$full_path${NC}"
    echo -e "  ${BLUE}$(msg samba_description):${NC} $share_comment"
    echo -e "  ${BLUE}$(msg samba_type):${NC} $(msg samba_type_${share_type})"
    if [ -n "$valid_users" ]; then
        echo -e "  ${BLUE}$(msg samba_users):${NC} ${GREEN}$valid_users${NC}"
        echo -e "  ${BLUE}$(msg samba_permissions):${NC} $([ "$read_only" = "yes" ] && echo "$(msg samba_read_only)" || echo "$(msg samba_read_write)")"
    fi
    if [ -n "$hosts_allow" ]; then
        echo -e "  ${BLUE}$(msg samba_allowed_hosts):${NC} $hosts_allow"
    fi
    echo -e "  ${BLUE}$(msg samba_recycle_bin):${NC} $([ "$recycle" = "yes" ] && echo "${GREEN}$(msg enabled)${NC}" || echo "${YELLOW}$(msg disabled)${NC}")"
    echo -e "  ${BLUE}$(msg samba_browseable):${NC} $([ "$browseable" = "yes" ] && echo "${GREEN}$(msg yes)${NC}" || echo "${YELLOW}$(msg no)${NC}")"
    echo ""

    read_input_with_escape "$(msg confirm_operation)"
    local confirm="$READ_INPUT"
    if [ "$confirm" = "ESC" ] || [ "$confirm" = "BACK" ] || ([ "$confirm" != "s" ] && [ "$confirm" != "S" ] && [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]); then
        print_info "$(msg operation_cancelled)"
        pause_execution
        return
    fi

    # CREATE SHARE
    print_info "$(msg samba_creating_share)"

    # Create directory
    create_share_directory "$dir_name" "$share_type" >/dev/null

    # Add to config
    add_share_to_config "$share_name" "$full_path" "$share_comment" \
        "$share_type" "$valid_users" "$read_only" "$browseable" \
        "$recycle" "$hosts_allow"

    # Reload configuration
    if reload_samba_config; then
        print_success "$(msg samba_share_created)"
        log_message "INFO" "Samba share created: $share_name"
    else
        print_error "$(msg samba_share_creation_failed)"
    fi

    pause_execution
}

# ============================================================================
# SHARE MODIFICATION
# ============================================================================

modify_samba_share() {
    list_samba_shares

    echo ""
    read_input_with_escape "$(msg samba_share_to_modify)"
    local share_name="$READ_INPUT"

    if [ -z "$share_name" ] || [ "$share_name" = "ESC" ] || [ "$share_name" = "BACK" ]; then
        return
    fi

    if ! share_exists "$share_name"; then
        print_error "$(msg samba_share_not_found)"
        pause_execution
        return
    fi

    # Show current details
    get_share_details "$share_name"

    print_warning "$(msg samba_modify_warning)"
    echo ""
    read_input_with_escape "$(msg confirm_operation)"
    local confirm="$READ_INPUT"

    if [ "$confirm" = "ESC" ] || [ "$confirm" = "BACK" ] || ([ "$confirm" != "s" ] && [ "$confirm" != "S" ] && [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]); then
        print_info "$(msg operation_cancelled)"
        pause_execution
        return
    fi

    # For simplicity, delete and recreate
    print_info "$(msg samba_recreate_share)"
    pause_execution
}

# ============================================================================
# SHARE DELETION
# ============================================================================

delete_samba_share() {
    list_samba_shares

    echo ""
    read_input_with_escape "$(msg samba_share_to_delete)"
    local share_name="$READ_INPUT"

    if [ -z "$share_name" ] || [ "$share_name" = "ESC" ] || [ "$share_name" = "BACK" ]; then
        return
    fi

    if ! share_exists "$share_name"; then
        print_error "$(msg samba_share_not_found)"
        pause_execution
        return
    fi

    # Get share path
    local share_path=$(grep -A 10 "^\[$share_name\]" "$SAMBA_CONFIG" | grep "path" | sed 's/.*=\s*//' | head -1)

    echo ""
    print_info "$(msg samba_delete_share): [$share_name]"
    echo ""
    echo "$(msg samba_path): $share_path"
    echo ""
    print_warning "$(msg samba_delete_warning)"
    echo ""
    echo "  1) $(msg samba_keep_directory)"
    echo "  2) $(msg samba_delete_directory)"
    echo "  3) $(msg cancel)"
    echo ""
    read_menu_option "$(msg select_option): "
    local delete_choice="$MENU_INPUT"

    case "$delete_choice" in
        1)
            # Remove from config only
            delete_share_from_config "$share_name"

            if reload_samba_config; then
                print_success "$(msg samba_share_removed)"
                print_info "$(msg samba_directory_kept): $share_path"
                log_message "INFO" "Samba share removed (directory kept): $share_name"
            fi
            ;;
        2)
            # Remove from config and delete directory
            delete_share_from_config "$share_name"

            if reload_samba_config; then
                rm -rf "$share_path"
                print_success "$(msg samba_share_removed)"
                print_success "$(msg samba_directory_deleted)"
                log_message "INFO" "Samba share and directory deleted: $share_name"
            fi
            ;;
        *)
            print_info "$(msg operation_cancelled)"
            ;;
    esac

    pause_execution
}



# Listar usuarios de un share
list_share_users() {
    local share_name="$1"
    testparm -s --section-name="$share_name" 2>/dev/null | \
        grep "valid users" | \
        cut -d= -f2 | \
        xargs
}

# Agregar usuario a un share
add_user_to_share() {
    local share_name="$1"
    local username="$2"

    # Obtener usuarios actuales
    local current_users=$(list_share_users "$share_name")

    # Verificar si ya existe
    if echo "$current_users" | grep -qw "$username"; then
        return 1  # Ya existe
    fi

    # Agregar usuario
    local new_users="$current_users $username"
    sed -i "/^\[$share_name\]/,/^\[/ s/valid users = .*/valid users = $new_users/" "$SAMBA_CONFIG"

    # Validar y recargar
    validate_samba_config && reload_samba_config
}

# Quitar usuario de un share
remove_user_from_share() {
    local share_name="$1"
    local username="$2"

    # Obtener usuarios actuales
    local current_users=$(list_share_users "$share_name")

    # Verificar si el usuario está en el share
    if ! echo "$current_users" | grep -qw "$username"; then
        return 1  # Usuario no está en el share
    fi

    # Quitar usuario
    local new_users=$(echo "$current_users" | sed "s/\b$username\b//g" | sed 's/  */ /g' | xargs)

    # Si queda vacío después de quitar el usuario, poner un espacio
    if [ -z "$new_users" ]; then
        new_users=" "
    fi

    sed -i "/^\[$share_name\]/,/^\[/ s/valid users = .*/valid users = $new_users/" "$SAMBA_CONFIG"

    # Validar y recargar
    validate_samba_config && reload_samba_config
}

# ============================================================================
# SHARE USER MANAGEMENT
# ============================================================================

# Menú de gestión de usuarios por share
menu_share_users() {
    breadcrumb_push "$(msg samba_manage_share_users)"
    
    while true; do
        show_header
        print_info "$(msg samba_manage_share_users)"
        echo ""

        # Buscar shares con usuarios específicos (privados)
        local shares_with_users=""
        while IFS= read -r line; do
            if [[ "$line" =~ ^\[([^\]]+)\]$ ]]; then
                local share="${BASH_REMATCH[1]}"
                if [[ "$share" != "global" && "$share" != "printers" && "$share" != "print$" ]]; then
                    # Verificar si el share tiene "valid users"
                    local has_users=$(grep -A20 "^\[$share\]" "$SAMBA_CONFIG" | grep -E "^\s*valid users\s*=" | head -1)
                    if [ -n "$has_users" ]; then
                        if [ -n "$shares_with_users" ]; then
                            shares_with_users="$shares_with_users\n"
                        fi
                        # Obtener lista de usuarios
                        local users=$(echo "$has_users" | sed 's/.*=\s*//')
                        shares_with_users="${shares_with_users}  - ${share} ($(msg samba_users): $users)"
                    fi
                fi
            fi
        done < "$SAMBA_CONFIG"

        if [ -z "$shares_with_users" ]; then
            print_warning "$(msg samba_no_private_shares)"
            read_menu_option ""
            breadcrumb_pop
            return
        fi

        local content="${BLUE}[$(msg samba_select_share_to_manage)]${NC}\n\n"
        content+="$shares_with_users"
        
        while true; do
            show_with_pager "$content"
            
            # Check if user selected something
            if [ -n "${PAGER_SELECTED_ITEM:-}" ]; then
                # Extract share name from selected line (format: "  - sharename (Users: ...)")
                local selected_share
                selected_share=$(echo "$PAGER_SELECTED_ITEM" | sed 's/^[[:space:]]*-[[:space:]]*//; s/[[:space:]]*(.*//' | xargs)
                
                if [ -n "$selected_share" ]; then
                    manage_single_share_users "$selected_share"
                    PAGER_SELECTED_ITEM=""
                fi
            else
                # User pressed ESC or 'b' to go back
                break
            fi
        done
        break
    done
    breadcrumb_pop
}
# Gestionar usuarios de un share específico
manage_single_share_users() {
    local share_name="$1"
    breadcrumb_push "$share_name"
    
    while true; do
        show_header
        print_info "Share: $share_name"
        echo ""
        
        # Mostrar usuarios actuales del share
        local current_users=$(list_share_users "$share_name")
        if [ -n "$current_users" ] && [ "$current_users" != " " ]; then
            echo -e "${BLUE}$(msg samba_current_users):${NC} $current_users"
        else
            echo -e "${BLUE}$(msg samba_current_users):${NC} $(msg samba_no_users)"
        fi
        
        echo ""
        
        # Mostrar usuarios disponibles para agregar
        local available_users=$(list_samba_users | tr ' ' '\n' | while read user; do
            if [ -n "$user" ] && ! echo "$current_users" | grep -qwF "$user"; then
                echo "$user"
            fi
        done | xargs)
        
        if [ -n "$available_users" ]; then
            echo -e "${BLUE}$(msg samba_available_users):${NC} $available_users"
        else
            echo -e "${BLUE}$(msg samba_available_users):${NC} $(msg samba_no_available_users)"
        fi
        
        echo ""
        echo "  1) $(msg samba_add_user_to_share)"
        echo "  2) $(msg samba_remove_user_from_share)"
        echo ""
        echo -e "  ${YELLOW}0) $(msg back)${NC}"
        echo ""
        read_menu_option "$(msg select_option): "
        local option="$MENU_INPUT"

        [[ "$option" == "ESC" || "$option" == "0" || "$option" == "" ]] && {
            breadcrumb_pop
            break
        }

        case "$option" in
            1)
                if [ -z "$available_users" ]; then
                    print_warning "$(msg samba_no_available_users)"
                    read_menu_option ""
                    continue
                fi
                echo ""
                read_input_with_escape "$(msg samba_user_to_add) ($available_users)"
                local user="$READ_INPUT"
                if [ -n "$user" ] && [ "$user" != "ESC" ] && [ "$user" != "BACK" ]; then
                    if ! user_exists_in_samba "$user"; then
                        print_error "$(msg samba_user_not_found)"
                    elif add_user_to_share "$share_name" "$user"; then
                        print_success "$(msg samba_user_added_to_share)"
                    else
                        print_error "$(msg samba_user_already_in_share)"
                    fi
                    read_menu_option ""
                fi
                ;;
            2)
                if [ -z "$current_users" ] || [ "$current_users" = " " ]; then
                    print_warning "$(msg samba_no_users)"
                    read_menu_option ""
                    continue
                fi
                echo ""
                read_input_with_escape "$(msg samba_user_to_remove) ($current_users)"
                local user="$READ_INPUT"
                if [ -n "$user" ] && [ "$user" != "ESC" ] && [ "$user" != "BACK" ]; then
                    if remove_user_from_share "$share_name" "$user"; then
                        print_success "$(msg samba_user_removed_from_share)"
                    else
                        print_error "$(msg samba_user_not_in_share)"
                    fi
                    read_menu_option ""
                fi
                ;;
            *)
                print_error "$(msg invalid_option)"
                read_menu_option ""
                ;;
        esac
    done
}

# ============================================================================
# USER MANAGEMENT FUNCTIONS
# ============================================================================

# Add Samba user
add_samba_user() {
    show_header
    print_info "$(msg samba_add_user)"
    echo ""

    read_input_with_escape "$(msg samba_username_prompt)"
    local username="$READ_INPUT"

    if [ -z "$username" ] || [ "$username" = "ESC" ] || [ "$username" = "BACK" ]; then
        return
    fi

    # Check if user already exists in Samba
    if user_exists_in_samba "$username"; then
        print_error "$(msg samba_user_already_exists)"
        pause_execution
        return
    fi

    # Check if user exists in system
    if ! user_exists_in_system "$username"; then
        echo ""
        print_warning "$(msg samba_user_not_in_system)"
        echo ""
        read_input_with_escape "$(msg samba_create_system_user) (s/n)"
        local create_user="$READ_INPUT"

        if [ "$create_user" = "ESC" ] || [ "$create_user" = "BACK" ]; then
            return
        fi

        if [ "$create_user" = "s" ] || [ "$create_user" = "S" ] || [ "$create_user" = "y" ] || [ "$create_user" = "Y" ]; then
            # Create system user
            useradd -M -s /usr/sbin/nologin "$username"
            usermod -aG sambashare "$username"
            print_success "$(msg samba_system_user_created)"
        else
            print_info "$(msg operation_cancelled)"
            pause_execution
            return
        fi
    else
        # Add to sambashare group
        usermod -aG sambashare "$username"
    fi

    # Set Samba password
    echo ""
    print_info "$(msg samba_set_password):"
    echo ""
    smbpasswd -a "$username"

    if [ $? -eq 0 ]; then
        print_success "$(msg samba_user_added)"
        log_message "INFO" "Samba user added: $username"
    else
        print_error "$(msg samba_user_add_failed)"
    fi

    pause_execution
}

# Change Samba password
change_samba_password() {
    list_samba_users
    echo ""
    read_input_with_escape "$(msg samba_username_prompt)"
    local username="$READ_INPUT"
    if [ -z "$username" ] || [ "$username" = "ESC" ] || [ "$username" = "BACK" ]; then
        return
    fi
    if ! user_exists_in_samba "$username"; then
        print_error "$(msg samba_user_not_found)"
        pause_execution
        return
    fi
    echo ""
    print_info "$(msg samba_new_password):"
    echo ""
    if smbpasswd -a "$username"; then
        echo ""
        print_success "$(msg samba_password_changed)"
        log_message "INFO" "Samba password changed for: $username"
    else
        echo ""
        print_error "$(msg samba_password_change_failed)"
    fi
    pause_execution
}

# Delete Samba user
delete_samba_user() {
    list_samba_users

    echo ""
    read_input_with_escape "$(msg samba_username_prompt)"
    local username="$READ_INPUT"

    if [ -z "$username" ] || [ "$username" = "ESC" ] || [ "$username" = "BACK" ]; then
        return
    fi

    if ! user_exists_in_samba "$username"; then
        print_error "$(msg samba_user_not_found)"
        pause_execution
        return
    fi

    echo ""
    print_warning "$(msg samba_delete_user_warning)"
    echo ""
    read_input_with_escape "$(msg confirm_operation)"
    local confirm="$READ_INPUT"

    if [ "$confirm" = "ESC" ] || [ "$confirm" = "BACK" ] || ([ "$confirm" != "s" ] && [ "$confirm" != "S" ] && [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]); then
        print_info "$(msg operation_cancelled)"
        pause_execution
        return
    fi

    smbpasswd -x "$username" >/dev/null 2>&1

    if [ $? -eq 0 ]; then
        print_success "$(msg samba_user_deleted)"
        log_message "INFO" "Samba user deleted: $username"
    else
        print_error "$(msg samba_user_delete_failed)"
    fi

    pause_execution
}

# Enable/Disable Samba user
toggle_samba_user() {
    list_samba_users

    echo ""
    read_input_with_escape "$(msg samba_username_prompt)"
    local username="$READ_INPUT"

    if [ -z "$username" ] || [ "$username" = "ESC" ] || [ "$username" = "BACK" ]; then
        return
    fi

    if ! user_exists_in_samba "$username"; then
        print_error "$(msg samba_user_not_found)"
        pause_execution
        return
    fi

    echo ""
    echo "  1) $(msg samba_enable_user)"
    echo "  2) $(msg samba_disable_user)"
    echo ""
    read_menu_option "$(msg select_option): "
    local action="$MENU_INPUT"

    [ "$action" = "ESC" ] && return

    case "$action" in
        1)
            smbpasswd -e "$username" >/dev/null 2>&1
            print_success "$(msg samba_user_enabled)"
            log_message "INFO" "Samba user enabled: $username"
            ;;
        2)
            smbpasswd -d "$username" >/dev/null 2>&1
            print_success "$(msg samba_user_disabled)"
            log_message "INFO" "Samba user disabled: $username"
            ;;
        *)
            print_error "$(msg invalid_option)"
            ;;
    esac

    pause_execution
}

# ============================================================================
# GLOBAL CONFIGURATION FUNCTIONS
# ============================================================================

# Change workgroup
set_samba_workgroup() {
    local current_workgroup=$(get_samba_workgroup)

    echo ""
    echo "$(msg samba_current_label): $current_workgroup"
    echo ""
    read_input_with_escape "$(msg samba_new_workgroup)"
    local new_workgroup="$READ_INPUT"

    if [ -z "$new_workgroup" ] || [ "$new_workgroup" = "ESC" ] || [ "$new_workgroup" = "BACK" ]; then
        return
    fi

    # Update in smb.conf
    sed -i "s/^\s*workgroup\s*=.*/   workgroup = $new_workgroup/" "$SAMBA_CONFIG"

    if reload_samba_config; then
        print_success "$(msg samba_workgroup_changed)"
        log_message "INFO" "Samba workgroup changed to: $new_workgroup"
    fi

    pause_execution
}

# Change server description
set_samba_description() {
    local current_desc=$(get_samba_description)

    echo ""
    echo "$(msg samba_current_label): $current_desc"
    echo ""
    read_input_with_escape "$(msg samba_new_description)"
    local new_desc="$READ_INPUT"

    if [ -z "$new_desc" ] || [ "$new_desc" = "ESC" ] || [ "$new_desc" = "BACK" ]; then
        return
    fi

    # Update in smb.conf
    sed -i "s/^\s*server string\s*=.*/   server string = $new_desc/" "$SAMBA_CONFIG"

    if reload_samba_config; then
        print_success "$(msg samba_description_changed)"
        log_message "INFO" "Samba description changed to: $new_desc"
    fi

    pause_execution
}

# Change NetBIOS name
set_samba_netbios_name() {
    local current_name=$(get_samba_netbios_name)

    echo ""
    echo "$(msg samba_current_label): $current_name"
    echo ""
    read_input_with_escape "$(msg samba_new_netbios)"
    local new_name="$READ_INPUT"

    if [ -z "$new_name" ] || [ "$new_name" = "ESC" ] || [ "$new_name" = "BACK" ]; then
        return
    fi

    # Check if netbios name line exists
    if grep -q "^\s*netbios name\s*=" "$SAMBA_CONFIG"; then
        sed -i "s/^\s*netbios name\s*=.*/   netbios name = $new_name/" "$SAMBA_CONFIG"
    else
        # Add after workgroup line
        sed -i "/^\s*workgroup\s*=/a\\   netbios name = $new_name" "$SAMBA_CONFIG"
    fi

    if reload_samba_config; then
        print_success "$(msg samba_netbios_changed)"
        log_message "INFO" "Samba NetBIOS name changed to: $new_name"
    fi

    pause_execution
}

# Show complete configuration
show_samba_config() {
    show_header
    print_info "$(msg samba_complete_config)"
    echo ""

    testparm -s "$SAMBA_CONFIG" 2>/dev/null | less

    pause_execution
}

# ============================================================================
# MONITORING FUNCTIONS
# ============================================================================

# Show active connections
show_samba_connections() {
    show_header
    print_info "$(msg samba_active_connections)"
    echo ""

    if ! smbstatus -b >/dev/null 2>&1; then
        print_info "$(msg samba_no_connections)"
    else
        smbstatus -b 2>/dev/null
    fi

    echo ""
    pause_execution
}

# Show locked files
show_samba_locks() {
    show_header
    print_info "$(msg samba_locked_files)"
    echo ""

    if ! smbstatus -L >/dev/null 2>&1; then
        print_info "$(msg samba_no_locks)"
    else
        smbstatus -L 2>/dev/null
    fi

    echo ""
    pause_execution
}

# Show shares in use
show_samba_shares_usage() {
    show_header
    print_info "$(msg samba_shares_usage)"
    echo ""

    if ! smbstatus -S >/dev/null 2>&1; then
        print_info "$(msg samba_no_shares_in_use)"
    else
        smbstatus -S 2>/dev/null
    fi

    echo ""
    pause_execution
}

# Show usage statistics
show_samba_stats() {
    show_header
    print_info "$(msg samba_statistics)"
    echo ""

    smbstatus 2>/dev/null

    echo ""
    pause_execution
}

# ============================================================================
# TEMPLATES / PRESETS
# ============================================================================

create_share_from_template() {
    show_header
    print_info "$(msg samba_templates)"
    echo ""
    echo "  1) $(msg samba_template_public_docs)"
    echo "  2) $(msg samba_template_private_project)"
    echo "  3) $(msg samba_template_team_share)"
    echo "  4) $(msg samba_template_home_dirs)"
    echo ""
    echo -e "  ${YELLOW}0) $(msg back)${NC}"
    echo ""
    read_menu_option "$(msg select_option): "
    local template_choice="$MENU_INPUT"

    [ "$template_choice" = "ESC" ] || [ "$template_choice" = "0" ] && return

    case "$template_choice" in
        1)
            # Public documents share
            local share_name="documentos"
            read_input_with_escape "$(msg samba_share_name) [$share_name]"
            local custom_name="$READ_INPUT"
            [ "$custom_name" = "ESC" ] || [ "$custom_name" = "BACK" ] && return
            share_name=${custom_name:-$share_name}

            create_share_directory "$share_name" "public_ro" >/dev/null
            add_share_to_config "$share_name" "$SAMBA_BASE_DIR/$share_name" \
                "Public Documents" "public_ro" "" "yes" "yes" "no" ""

            if reload_samba_config; then
                print_success "$(msg samba_template_created)"
            fi
            ;;
        2)
            # Private project share
            list_samba_users
            echo ""
            read_input_with_escape "$(msg samba_share_name)"
            local share_name="$READ_INPUT"
            [ "$share_name" = "ESC" ] || [ "$share_name" = "BACK" ] || [ -z "$share_name" ] && return

            read_input_with_escape "$(msg samba_valid_users_prompt)"
            local valid_users="$READ_INPUT"
            [ "$valid_users" = "ESC" ] || [ "$valid_users" = "BACK" ] || [ -z "$valid_users" ] && return

            create_share_directory "$share_name" "private" >/dev/null
            add_share_to_config "$share_name" "$SAMBA_BASE_DIR/$share_name" \
                "Private Project" "private" "$valid_users" "no" "yes" "yes" ""

            if reload_samba_config; then
                print_success "$(msg samba_template_created)"
            fi
            ;;
        3)
            # Team share
            echo ""
            read_input_with_escape "$(msg samba_team_name)"
            local team_name="$READ_INPUT"
            [ "$team_name" = "ESC" ] || [ "$team_name" = "BACK" ] || [ -z "$team_name" ] && return

            read_input_with_escape "$(msg samba_valid_users_prompt)"
            local valid_users="$READ_INPUT"
            [ "$valid_users" = "ESC" ] || [ "$valid_users" = "BACK" ] || [ -z "$valid_users" ] && return

            create_share_directory "$team_name" "private" >/dev/null
            add_share_to_config "$team_name" "$SAMBA_BASE_DIR/$team_name" \
                "Team Share: $team_name" "private" "$valid_users" "no" "yes" "yes" ""

            if reload_samba_config; then
                print_success "$(msg samba_template_created)"
            fi
            ;;
        4)
            # Home directories
            print_info "$(msg samba_home_dirs_info)"
            echo ""
            read_input_with_escape "$(msg confirm_operation)"
            local confirm="$READ_INPUT"

            if [ "$confirm" = "s" ] || [ "$confirm" = "S" ] || [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
                # Enable [homes] section
                if ! grep -q "^\[homes\]" "$SAMBA_CONFIG"; then
                    cat >> "$SAMBA_CONFIG" << 'EOF'

[homes]
    comment = Home Directories
    browseable = no
    read only = no
    create mask = 0700
    directory mask = 0700
    valid users = %S
EOF
                    if reload_samba_config; then
                        print_success "$(msg samba_home_dirs_enabled)"
                    fi
                else
                    print_info "$(msg samba_home_dirs_already_enabled)"
                fi
            fi
            ;;
        0)
            return
            ;;
        *)
            print_error "$(msg invalid_option)"
            ;;
    esac

    pause_execution
}

# ============================================================================
# INSTALLATION AND SERVICE CONTROL
# ============================================================================

# Install and enable Samba
install_and_enable_samba() {
    print_info "$(msg service_installing)"

    apt-get update >/dev/null 2>&1
    apt-get install -y samba samba-common-bin >/dev/null 2>&1

    print_success "$(msg service_installed_success)"

    # Create base directory
    mkdir -p "$SAMBA_BASE_DIR"

    # Create sambashare group if doesn't exist
    if ! getent group sambashare >/dev/null; then
        groupadd sambashare
    fi

    # Backup original config
    if [ -f "$SAMBA_CONFIG" ]; then
        backup_samba_config >/dev/null
    fi

    # Create basic config with full_audit
    cat > "$SAMBA_CONFIG" << 'EOF'
[global]
   workgroup = SYNEX
   server string = Synex Samba Server
   security = user
   map to guest = bad user
   log file = /var/log/samba/%m.log
   max log size = 50

   # Full audit logging
   vfs objects = full_audit
   full_audit:prefix = %u|%I|%S
   full_audit:success = open close read write unlinkat mkdirat renameat
   full_audit:failure = none
   full_audit:facility = local5
   full_audit:priority = notice
   full_audit:syslog = true

   # Performance
   socket options = TCP_NODELAY IPTOS_LOWDELAY SO_RCVBUF=65536 SO_SNDBUF=65536
   read raw = yes
   write raw = yes

   # Printing disabled
   load printers = no
   printing = bsd
   printcap name = /dev/null
   disable spoolss = yes
EOF

    # Enable and start services
    systemctl enable smbd nmbd >/dev/null 2>&1
    systemctl start smbd nmbd >/dev/null 2>&1

    print_success "$(msg service_started)"
    log_message "INFO" "Samba installed and enabled"

    pause_execution
}

# Enable Samba service
enable_samba() {
    if ! is_samba_installed; then
        install_and_enable_samba
        return
    fi

    print_info "$(msg service_starting)"

    systemctl enable smbd nmbd >/dev/null 2>&1
    systemctl start smbd nmbd >/dev/null 2>&1

    print_success "$(msg service_started)"
    log_message "INFO" "Samba service enabled"

    pause_execution
}

# Disable Samba service
disable_samba() {
    print_warning "$(msg service_stop_warning)"
    echo ""
    read_input_with_escape "$(msg confirm_operation)"
    local confirm="$READ_INPUT"

    if [ "$confirm" = "ESC" ] || [ "$confirm" = "BACK" ] || ([ "$confirm" != "s" ] && [ "$confirm" != "S" ] && [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]); then
        print_info "$(msg operation_cancelled)"
        pause_execution
        return
    fi

    print_info "$(msg service_stopping)"

    systemctl stop smbd nmbd >/dev/null 2>&1
    systemctl disable smbd nmbd >/dev/null 2>&1

    print_success "$(msg service_stopped)"
    log_message "INFO" "Samba service disabled"

    pause_execution
}

# ============================================================================
# MENUS
# ============================================================================

# Submenu: Manage shares
menu_manage_shares() {
    breadcrumb_push "Shares"

    while true; do
        show_header
        print_info "$(msg samba_manage_shares)"
        echo ""
        list_samba_shares
        echo "  1) $(msg samba_create_share)"
        echo "  2) $(msg samba_modify_share)"
        echo "  3) $(msg samba_delete_share)"
        echo "  4) $(msg samba_view_share_details)"
        echo "  5) $(msg samba_create_from_template)"
        echo "  6) $(msg samba_manage_share_users)"
        echo ""
        echo -e "  ${YELLOW}0) $(msg back)${NC}"
        echo ""
        read_menu_option "$(msg select_option): "
        local option="$MENU_INPUT"

        [[ "$option" == "ESC" || "$option" == "0" ]] && {
            breadcrumb_pop
            break
        }

        case $option in
            1) create_samba_share_wizard ;;
            2) modify_samba_share ;;
            3) delete_samba_share ;;
            4)
                # Usar pager para seleccionar share
                local shares_list=""
                while IFS= read -r line; do
                    if [[ "$line" =~ ^\[([^\]]+)\]$ ]]; then
                        local share="${BASH_REMATCH[1]}"
                        if [[ "$share" != "global" && "$share" != "printers" && "$share" != "print$" ]]; then
                            if [ -n "$shares_list" ]; then
                                shares_list="$shares_list\n"
                            fi
                            shares_list="${shares_list}  - ${share}"
                        fi
                    fi
                done < "$SAMBA_CONFIG"

                if [ -z "$shares_list" ]; then
                    print_warning "$(msg samba_no_shares)"
                    read_menu_option ""
                else
                    local content="${BLUE}[$(msg samba_select_share_to_view)]${NC}\n\n"
                    content+="$shares_list"
                    
                    while true; do
                        show_with_pager "$content"
                        
                        # Check if user selected something
                        if [ -n "${PAGER_SELECTED_ITEM:-}" ]; then
                            # Extract share name from selected line (format: "  - sharename")
                            local selected_share
                            selected_share=$(echo "$PAGER_SELECTED_ITEM" | sed 's/^[[:space:]]*-[[:space:]]*//; s/[[:space:]]*$//' | xargs)
                            
                            if [ -n "$selected_share" ]; then
                                get_share_details_and_pause "$selected_share"
                                PAGER_SELECTED_ITEM=""
                            fi
                        else
                            # User pressed ESC or 'b' to go back
                            break
                        fi
                    done
                fi
                ;;
            5) create_share_from_template ;;
            6) menu_share_users ;;
            *)
                print_error "$(msg invalid_option)"
                pause_execution
                ;;
        esac
    done
}

# Submenu: Manage users
menu_manage_users() {
    breadcrumb_push "$(msg bc_samba_users)"

    while true; do
        show_header
        print_info "$(msg samba_manage_users)"
        echo ""
        list_samba_users
        echo "  1) $(msg samba_add_user)"
        echo "  2) $(msg samba_change_password)"
        echo "  3) $(msg samba_toggle_user)"
        echo "  4) $(msg samba_delete_user)"
        echo ""
        echo -e "  ${YELLOW}0) $(msg back)${NC}"
        echo ""
        read_menu_option "$(msg select_option): "
        local option="$MENU_INPUT"

        [[ "$option" == "ESC" || "$option" == "0" ]] && {
            breadcrumb_pop
            break
        }

        case $option in
            1) add_samba_user ;;
            2) change_samba_password ;;
            3) toggle_samba_user ;;
            4) delete_samba_user ;;
            *)
                print_error "$(msg invalid_option)"
                pause_execution
                ;;
        esac
    done
}

# Submenu: Global configuration
menu_global_config() {
    breadcrumb_push "$(msg bc_configuration)"

    while true; do
        show_header
        print_info "$(msg samba_global_config)"
        echo ""
        echo "$(msg samba_workgroup): $(get_samba_workgroup)"
        echo "$(msg samba_description): $(get_samba_description)"
        echo "$(msg samba_netbios_name): $(get_samba_netbios_name)"
        echo ""
        echo "  1) $(msg samba_change_workgroup)"
        echo "  2) $(msg samba_change_description)"
        echo "  3) $(msg samba_change_netbios)"
        echo "  4) $(msg samba_view_complete_config)"
        echo ""
        echo -e "  ${YELLOW}0) $(msg back)${NC}"
        echo ""
        read_menu_option "$(msg select_option): "
        local option="$MENU_INPUT"

        [[ "$option" == "ESC" || "$option" == "0" ]] && {
            breadcrumb_pop
            break
        }

        case $option in
            1) set_samba_workgroup ;;
            2) set_samba_description ;;
            3) set_samba_netbios_name ;;
            4) show_samba_config ;;
            *)
                print_error "$(msg invalid_option)"
                pause_execution
                ;;
        esac
    done
}

# Submenu: Monitoring
menu_monitoring() {
    breadcrumb_push "$(msg bc_monitoring)"

    while true; do
        show_header
        print_info "$(msg samba_monitoring)"
        echo ""
        echo "  1) $(msg samba_view_connections)"
        echo "  2) $(msg samba_view_locks)"
        echo "  3) $(msg samba_view_shares_usage)"
        echo "  4) $(msg samba_view_statistics)"
        echo ""
        echo -e "  ${YELLOW}0) $(msg back)${NC}"
        echo ""
        read_menu_option "$(msg select_option): "
        local option="$MENU_INPUT"

        [[ "$option" == "ESC" || "$option" == "0" ]] && {
            breadcrumb_pop
            break
        }

        case $option in
            1) show_samba_connections ;;
            2) show_samba_locks ;;
            3) show_samba_shares_usage ;;
            4) show_samba_stats ;;
            *)
                print_error "$(msg invalid_option)"
                pause_execution
                ;;
        esac
    done
}

# Main Samba menu
menu_samba() {
    breadcrumb_push "Samba"

    while true; do
        show_samba_status
        echo ""
        echo "  1) $(msg activate_service)"
        echo "  2) $(msg deactivate_service)"
        echo "  3) $(msg samba_manage_shares)"
        echo "  4) $(msg samba_manage_users)"
        echo "  5) $(msg samba_global_config)"
        echo "  6) $(msg samba_monitoring)"
        echo ""
echo -e "  ${YELLOW}0) $(msg back)${NC}"
        echo ""
        read_menu_option "$(msg select_option): "
        local option="$MENU_INPUT"

        [[ "$option" == "ESC" || "$option" == "0" ]] && {
            breadcrumb_pop
            break
        }

        case $option in
            1) enable_samba ;;
            2) disable_samba ;;
            3) menu_manage_shares ;;
            4) menu_manage_users ;;
            5) menu_global_config ;;
            6) menu_monitoring ;;
            *)
                print_error "$(msg invalid_option)"
                pause_execution
                ;;
        esac
    done
}

#menu_samba() {
#    show_header
#    print_info "$(msg samba_title)"
#    echo ""
#    print_warning "[SAMBA - IMPLEMENTACION EN PROGRESO]"
#    echo ""
#    pause_execution
#}

# ============================================================================
# NFS MENU - HELPER FUNCTIONS
# ============================================================================

get_nfs_status() {
    local package="nfs-kernel-server"
    local service="nfs-server"

    if ! is_service_installed "$package"; then
        echo "not_installed"
        return
    fi

    if is_service_active "$service"; then
        echo "active"
    else
        echo "inactive"
    fi
}

get_nfs_primary_subnet() {
    # Get primary network interface (same logic as synex-control-net)
    local interface=$(ip link show | grep -E "^[0-9]+:" | grep "UP" | grep -v "lo:" | awk -F': ' '{print $2}' | head -1)

    if [ -z "$interface" ]; then
        echo ""
        return
    fi

    # Get IP address
    local ip=$(ip addr show "$interface" | grep "inet " | awk '{print $2}' | cut -d/ -f1)

    if [ -z "$ip" ]; then
        echo ""
        return
    fi

    # Calculate subnet (first 3 octets + .0/24)
    local subnet=$(echo "$ip" | cut -d. -f1-3).0/24
    echo "$subnet"
}

get_nfs_export_dir() {
    if [ -f /etc/exports.d/synex.exports ]; then
        grep -oP '^\S+' /etc/exports.d/synex.exports | head -1
    else
        echo ""
    fi
}

show_nfs_status() {
    local status=$(get_nfs_status)
    local export_dir=$(get_nfs_export_dir)
    local subnets=$(get_nfs_current_subnets)

    show_header
    print_info "$(msg nfs_title)"
    echo ""

    # Service status
    case "$status" in
        active)
            echo -e "${GREEN}[+] $(msg service_active)${NC}"
            ;;
        inactive)
            echo -e "${YELLOW}[-] $(msg service_inactive)${NC}"
            ;;
        not_installed)
            echo -e "${RED}[X] $(msg service_not_installed)${NC}"
            return
            ;;
    esac

    echo ""

    if [ -n "$export_dir" ]; then
        echo "$(msg nfs_share_dir): $export_dir"
        if [ -n "$subnets" ]; then
            echo "$(msg nfs_subnet): $subnets"
        fi
    else
        echo "$(msg nfs_no_exports)"
    fi

    echo ""
}

install_and_enable_nfs() {
    print_info "$(msg service_installing)"
    apt-get update >/dev/null 2>&1
    apt-get install -y nfs-kernel-server nfs-common >/dev/null 2>&1

    print_success "$(msg service_installed_success)"

    # Create default NFS directory
    mkdir -p /srv/nfs/shared
    chmod 755 /srv/nfs/shared

    # Create default exports
    mkdir -p /etc/exports.d
    echo "/srv/nfs/shared $(get_nfs_primary_subnet)(rw,sync,no_root_squash,no_subtree_check)" > /etc/exports.d/synex.exports

    # Enable and start NFS
    systemctl enable nfs-server >/dev/null 2>&1
    systemctl start nfs-server >/dev/null 2>&1

    # Export shares
    exportfs -ra >/dev/null 2>&1

    print_success "$(msg service_started)"
    print_success "$(msg nfs_export_created)"
    log_message "INFO" "NFS installed, enabled and started with default export"
}

enable_nfs() {
    if [ "$(get_nfs_status)" = "not_installed" ]; then
        install_and_enable_nfs
    else
        print_info "$(msg service_activating)"
        systemctl enable nfs-server >/dev/null 2>&1
        systemctl start nfs-server >/dev/null 2>&1
        print_success "$(msg service_started)"
        print_success "$(msg service_enabled_boot)"
        log_message "INFO" "NFS enabled and started"
    fi
}

disable_nfs() {
    print_info "$(msg service_deactivating)"
    systemctl stop nfs-server >/dev/null 2>&1
    systemctl disable nfs-server >/dev/null 2>&1
    print_success "$(msg service_stopped)"
    print_success "$(msg service_disabled_boot)"
    log_message "INFO" "NFS disabled and stopped"
}

configure_nfs_directory() {
    show_nfs_status

    local current_dir=$(get_nfs_export_dir)

    # Extract just the directory name from current path
    local current_name=""
    if [ -n "$current_dir" ]; then
        current_name=$(basename "$current_dir")
    fi

    echo ""
    echo "$(msg nfs_share_dir):"
    echo "$(msg nfs_base_path_info): /srv/nfs/"
    echo ""
    read_input_with_escape "$(msg nfs_new_directory_prompt) ($current_name)"
    local new_name="$READ_INPUT"

    # Cancel if empty or ESC
    if [ -z "$new_name" ] || [ "$new_name" = "ESC" ] || [ "$new_name" = "BACK" ]; then
        return
    fi

    # Validate: no slashes, no special chars
    if [[ "$new_name" =~ [/\\\:\*\?\"\<\>\|] ]]; then
        print_error "$(msg nfs_invalid_directory_name)"
        pause_execution
        return
    fi

    # Build full path with fixed base
    local new_dir="/srv/nfs/$new_name"

    # Check if unchanged
    if [ "$new_dir" = "$current_dir" ]; then
        print_info "$(msg config_value_unchanged)"
        pause_execution
        return
    fi

    # Create base directory if not exists
    mkdir -p /srv/nfs

    # Create target directory
    if [ ! -d "$new_dir" ]; then
        mkdir -p "$new_dir"
        chmod 777 "$new_dir"
        chown nobody:nogroup "$new_dir"
        print_success "$(msg directory_created)"
    else
        chmod 777 "$new_dir"
        chown nobody:nogroup "$new_dir"
    fi

    # Preserve existing subnets and permissions
    mkdir -p /etc/exports.d
    local current_subnets=$(get_nfs_current_subnets)
    local current_perms=$(grep -oP '\(\K[^)]+' /etc/exports.d/synex.exports 2>/dev/null | head -1)

    # Fallback to default if empty
    if [ -z "$current_perms" ]; then
        current_perms="rw,sync,no_root_squash,no_subtree_check"
    fi

    # If no subnets exist, use primary subnet
    if [ -z "$current_subnets" ]; then
        current_subnets=$(get_nfs_primary_subnet)
    fi

    # Build export line with preserved subnets
    local export_line="$new_dir"
    IFS=',' read -ra SUBNETS <<< "$current_subnets"
    for subnet in "${SUBNETS[@]}"; do
        subnet=$(echo "$subnet" | xargs)
        export_line="$export_line $subnet($current_perms)"
    done

    echo "$export_line" > /etc/exports.d/synex.exports

    # Apply changes (never fail)
    exportfs -ra >/dev/null 2>&1 || true
    systemctl reload nfs-server >/dev/null 2>&1 || true

    print_success "$(msg nfs_export_dir_changed_to) $new_dir"
    log_message "INFO" "NFS export directory changed to $new_dir"
    pause_execution
}

configure_nfs_permissions() {
    show_nfs_status

    local current_dir=$(get_nfs_export_dir)

    if [ -z "$current_dir" ]; then
        print_error "$(msg nfs_no_export_configured)"
        pause_execution
        return
    fi

    # Check current permissions (take only FIRST match)
    local current_perms=$(grep -oP '\(\K[^)]+' /etc/exports.d/synex.exports | head -1)
    local is_ro=false

    if [[ "$current_perms" == *"ro"* ]]; then
        is_ro=true
    fi

    echo ""
    echo "$(msg nfs_share_perms):"
    if [ "$is_ro" = true ]; then
        echo "  1) $(msg nfs_readwrite) (rw)"
        echo "  2) $(msg nfs_readonly) (ro) - ACTUAL"
    else
        echo "  1) $(msg nfs_readwrite) (rw) - ACTUAL"
        echo "  2) $(msg nfs_readonly) (ro)"
    fi
    echo ""
    read_menu_option "$(msg select_option): "
    local choice="$MENU_INPUT"

    [ "$choice" = "ESC" ] && return

    local new_perms=""
    case "$choice" in
        1)
            new_perms="rw,sync,no_root_squash,no_subtree_check"
            ;;
        2)
            new_perms="ro,sync,no_root_squash,no_subtree_check"
            ;;
        *)
            print_error "$(msg invalid_option)"
            pause_execution
            return
            ;;
    esac

    # Preserve existing subnets
    local current_subnets=$(get_nfs_current_subnets)

    # Build export line with preserved subnets
    local export_line="$current_dir"
    IFS=',' read -ra SUBNETS <<< "$current_subnets"
    for subnet in "${SUBNETS[@]}"; do
        subnet=$(echo "$subnet" | xargs)
        export_line="$export_line $subnet($new_perms)"
    done

    echo "$export_line" > /etc/exports.d/synex.exports

    # Apply changes (never fail)
    exportfs -ra >/dev/null 2>&1 || true
    systemctl reload nfs-server >/dev/null 2>&1 || true

    local perm_name=$([ "$choice" = "1" ] && echo "rw" || echo "ro")
    print_success "$(msg nfs_permissions_changed_to) $perm_name"
    log_message "INFO" "NFS permissions changed to $perm_name"
    pause_execution
}

show_nfs_exports() {
    show_nfs_status

    echo ""
    print_info "$(msg nfs_current_exports)"
    echo ""

    if [ -f /etc/exports.d/synex.exports ]; then
        cat /etc/exports.d/synex.exports
    else
        echo "$(msg nfs_no_exports)"
    fi

    echo ""
    print_info "$(msg nfs_export_status)"
    echo ""

    if is_service_active "nfs-server"; then
        showmount -e localhost 2>/dev/null || echo "$(msg nfs_cannot_show_exports)"
    else
        print_warning "$(msg nfs_not_active)"
    fi

    echo ""
}

configure_nfs_subnet() {
    show_nfs_status

    local current_dir=$(get_nfs_export_dir)
    local current_subnets=$(get_nfs_current_subnets)

    if [ -z "$current_dir" ]; then
        echo "$(msg nfs_no_exports):"
        pause_execution
        return
    fi

    echo ""
    print_info "$(msg nfs_manage_subnets)"
    echo ""
    echo "$(msg nfs_subnet_example)"
    echo "$(msg nfs_current_label): $current_subnets"
    echo ""
    read_input_with_escape "$(msg nfs_new_subnets_prompt)"
    local new_subnets="$READ_INPUT"

    if [ -z "$new_subnets" ] || [ "$new_subnets" = "ESC" ] || [ "$new_subnets" = "BACK" ]; then
        return
    fi

    # Validate subnet format
    local valid=true
    IFS=',' read -ra SUBNETS <<< "$new_subnets"
    for subnet in "${SUBNETS[@]}"; do
        subnet=$(echo "$subnet" | xargs)  # trim whitespace
        if ! [[ "$subnet" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/[0-9]{1,2}$ ]]; then
            print_error "$(msg nfs_invalid_subnet) $subnet"
            valid=false
        fi
    done

    if [ "$valid" = false ]; then
        print_error "$(msg nfs_invalid_subnet_format)"
        pause_execution
        return
    fi

    if [ "$new_subnets" = "$current_subnets" ]; then
        print_info "$(msg config_value_unchanged)"
        pause_execution
        return
    fi

    # Get current permissions
    local current_perms=$(grep -oP '\(\K[^)]+' /etc/exports.d/synex.exports)

    # Build export line with multiple subnets
    local export_line="$current_dir"
    IFS=',' read -ra SUBNETS <<< "$new_subnets"
    for subnet in "${SUBNETS[@]}"; do
        subnet=$(echo "$subnet" | xargs)  # trim whitespace
        export_line="$export_line $subnet($current_perms)"
    done

    # Update exports
    echo "$export_line" > /etc/exports.d/synex.exports

    # Apply changes
    exportfs -ra >/dev/null 2>&1 || true
    systemctl reload nfs-server >/dev/null 2>&1 || true

    print_success "$(msg nfs_subnets_changed_to) $new_subnets"
    log_message "INFO" "NFS subnets changed to $new_subnets"
    pause_execution
}

get_nfs_current_subnets() {
    if [ -f /etc/exports.d/synex.exports ]; then
        # Extract subnets from line like: /srv/nfs/shared 192.168.122.0/24(rw,...) 192.1.1.0/24(rw,...)
        grep -oP '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/[0-9]{1,2}' /etc/exports.d/synex.exports | tr '\n' ',' | sed 's/,$//'
    else
        echo ""
    fi
}

# ============================================================================
# NFS MENU
# ============================================================================

menu_nfs() {
    breadcrumb_push "NFS"

    while true; do
        show_nfs_status

        echo "  1) $(msg activate_service)"
        echo "  2) $(msg deactivate_service)"
        echo "  3) $(msg configure_service)"
        echo ""
echo -e "  ${YELLOW}0) $(msg back)${NC}"
        echo ""
        read_menu_option "$(msg select_option): "
        local choice="$MENU_INPUT"

        [[ "$choice" == "ESC" || "$choice" == "0" ]] && {
            breadcrumb_pop
            break
        }

        case "$choice" in
            1)
                enable_nfs
                pause_execution
                ;;
            2)
                disable_nfs
                pause_execution
                ;;
            3)
                breadcrumb_push "$(msg configure_service)"
                while true; do
                    show_nfs_status
                    echo ""
                    echo "  1) $(msg nfs_change_directory)"
                    echo "  2) $(msg nfs_change_subnet)"
                    echo "  3) $(msg nfs_change_permissions)"
                    echo "  4) $(msg nfs_view_exports)"
                    echo ""
                    echo -e "  ${YELLOW}0) $(msg back)${NC}"
                    echo ""
                    read_menu_option "$(msg select_option): "
                    local config_choice="$MENU_INPUT"

                    [[ "$config_choice" == "ESC" || "$config_choice" == "0" ]] && break

                    case "$config_choice" in
                        1)
                            configure_nfs_directory
                            ;;
                        2)
                            configure_nfs_subnet
                            ;;
                        3)
                            configure_nfs_permissions
                            ;;
                        4)
                            show_nfs_exports
                            pause_execution
                            ;;
                        *)
                            print_error "$(msg invalid_option)"
                            pause_execution
                            ;;
                    esac
                done
                breadcrumb_pop
                ;;
            *)
                print_error "$(msg invalid_option)"
                pause_execution
                ;;
        esac
    done
}

#menu_nfs() {
#    show_header
#    print_info "$(msg nfs_title)"
#    echo ""
#    print_warning "[NFS - IMPLEMENTACION EN PROGRESO]"
#    echo ""
#    pause_execution
#}

# ============================================================================
# FIREWALL MENU - HELPER FUNCTIONS (nftables)
# ============================================================================

get_firewall_status() {
    # nftables está siempre disponible en Debian, verificar si está activo
    if systemctl is-active --quiet nftables; then
        echo "active"
    else
        echo "inactive"
    fi
}

get_listening_ports() {
    ss -tlnp 2>/dev/null | grep LISTEN | awk '{print $4}' | awk -F: '{print $NF}' | sort -u -n | tr '\n' ',' | sed 's/,$//'
}

validate_port() {
    local port=$1
    if ! [[ "$port" =~ ^[0-9]+$ ]] || [ "$port" -lt 1 ] || [ "$port" -gt 65535 ]; then
        return 1
    fi
    return 0
}

is_port_open() {
    local port=$1
    local protocol=${2:-tcp}
    # Verificar si existe regla en nftables
    nft list table inet filter 2>/dev/null | grep -qE "dport.*$port" && return 0 || return 1
}

get_open_ports() {
    # Extrae puertos abiertos de nftables
    nft list table inet filter 2>/dev/null | grep -oE "dport [0-9]+" | awk '{print $2}' | sort -u | tr '\n' ',' | sed 's/,$//'
}

# ============================================================================
# FIREWALL STATUS FUNCTIONS
# ============================================================================

show_firewall_status() {
    local status=$(get_firewall_status)

    show_header
    print_info "$(msg firewall_title)"
    echo ""

    case "$status" in
        active)
            echo -e "${GREEN}[+] $(msg service_active)${NC}"
            echo ""
            ;;
        inactive)
            echo -e "${YELLOW}[-] $(msg service_inactive)${NC}"
            echo ""
            ;;
    esac

    echo ""
}

# ============================================================================
# FIREWALL ENABLE/DISABLE
# ============================================================================

enable_firewall() {
    set +e

    print_info "$(msg service_activating)"

    # Flush existing rules and recreate with correct policy
    nft flush table inet filter 2>/dev/null || true
    nft delete table inet filter 2>/dev/null || true
    
    # Create table and chains with DROP policy
    nft add table inet filter
    nft add chain inet filter input { type filter hook input priority 0 \; policy drop \; }
    nft add chain inet filter forward { type filter hook forward priority 0 \; policy drop \; }
    nft add chain inet filter output { type filter hook output priority 0 \; policy accept \; }

    # Add essential rules
    nft add rule inet filter input iif lo accept
    nft add rule inet filter input ct state established,related accept
    nft add rule inet filter input tcp dport 22 accept

    # Save rules BEFORE enabling service
    save_firewall_rules

    # Now enable and start service (will load the correct config)
    systemctl enable nftables >/dev/null 2>&1
    systemctl restart nftables >/dev/null 2>&1

    print_success "$(msg service_started)"
    print_success "$(msg service_enabled_boot)"

    log_message "INFO" "$(msg firewall_enabled_log)"
    set -e
}

disable_firewall() {
    print_info "$(msg service_deactivating)"
    systemctl stop nftables >/dev/null 2>&1
    systemctl disable nftables >/dev/null 2>&1
    print_success "$(msg service_stopped)"
    print_success "$(msg service_disabled_boot)"
    log_message "INFO" "nftables firewall disabled"
    set -e
}

# ============================================================================
# FIREWALL CONFIGURATION FUNCTIONS
# ============================================================================

configure_firewall_open_port() {
    set +e

    show_firewall_status

    if [ "$(get_firewall_status)" = "inactive" ]; then
        print_error "$(msg service_inactive)"
        pause_execution
        set -e
        return
    fi

    # Limpiar duplicados antes de continuar
    nft list -a table inet filter 2>/dev/null | grep -oE "# handle [0-9]+" | awk '{print $3}' | sort | uniq -d | while read handle; do
        nft delete rule inet filter input handle "$handle" 2>/dev/null || true
    done

    echo ""
    echo "$(msg firewall_currently_detected):"
    echo "$(get_listening_ports)"
    echo ""
    echo "$(msg firewall_port_format_help)"
    echo ""

    read_input_with_escape "$(msg firewall_port_to_open)"
    local port_input="$READ_INPUT"

    if [ -z "$port_input" ] || [ "$port_input" = "ESC" ] || [ "$port_input" = "BACK" ]; then
        set -e
        return
    fi

    # Seleccionar protocolo
    echo ""
    echo "$(msg firewall_protocol):"
    echo "  1) $(msg protocol_tcp)"
    echo "  2) $(msg protocol_udp)"
    echo "  3) $(msg firewall_both)"
    echo ""
    read_menu_option "$(msg select_option): "
    local protocol_choice="$MENU_INPUT"

    [ "$protocol_choice" = "ESC" ] && { set -e; return; }

    local protocol=""
    case $protocol_choice in
        1) protocol="tcp" ;;
        2) protocol="udp" ;;
        3) protocol="" ;;
        *)
            print_error "$(msg invalid_option)"
            pause_execution
            set -e
            return
            ;;
    esac

    local ports_opened=0
    local ports_failed=0
    print_info "$(msg firewall_processing_ports)"

    # Si contiene rango (80:90)
    if [[ "$port_input" =~ ^[0-9]+:[0-9]+$ ]]; then
        local start=$(echo "$port_input" | cut -d: -f1)
        local end=$(echo "$port_input" | cut -d: -f2)

        if ! validate_port "$start" || ! validate_port "$end"; then
            print_error "$(msg firewall_invalid_port)"
            pause_execution
            set -e
            return
        fi

        if [ "$start" -gt "$end" ]; then
            print_error "$(msg firewall_invalid_range)"
            pause_execution
            set -e
            return
        fi

        for port in $(seq "$start" "$end"); do
            if [ -z "$protocol" ]; then
                nft add rule inet filter input tcp dport "$port" accept 2>/dev/null || true
                nft add rule inet filter input udp dport "$port" accept 2>/dev/null || true
            else
                nft add rule inet filter input "$protocol" dport "$port" accept 2>/dev/null || true
            fi
            ((ports_opened++))
        done

    # Si contiene comas (80,443,8080)
    elif [[ "$port_input" =~ ^[0-9,]+$ ]]; then
        IFS=',' read -ra PORTS <<< "$port_input"
        for port in "${PORTS[@]}"; do
            port=$(echo "$port" | xargs)

            if ! validate_port "$port"; then
                ((ports_failed++))
                continue
            fi

            if [ -z "$protocol" ]; then
                nft add rule inet filter input tcp dport "$port" accept 2>/dev/null || true
                nft add rule inet filter input udp dport "$port" accept 2>/dev/null || true
            else
                nft add rule inet filter input "$protocol" dport "$port" accept 2>/dev/null || true
            fi
            ((ports_opened++))
        done

    # Un solo puerto (80)
    elif validate_port "$port_input"; then
        if [ -z "$protocol" ]; then
            nft add rule inet filter input tcp dport "$port_input" accept 2>/dev/null || true
            nft add rule inet filter input udp dport "$port_input" accept 2>/dev/null || true
        else
            nft add rule inet filter input "$protocol" dport "$port_input" accept 2>/dev/null || true
        fi
        log_message "INFO" "Firewall port $port_input opened"
        pause_execution
        set -e
        return

    else
        print_error "$(msg firewall_invalid_format)"
        pause_execution
        set -e
        return
    fi

    # Mostrar resumen una sola vez
    print_success "$(msg firewall_ports_opened_summary) $ports_opened"
    if [ "$ports_failed" -gt 0 ]; then
        print_warning "$ports_failed $(msg firewall_ports_failed)"
    fi
    log_message "INFO" "Firewall opened $ports_opened ports"

    pause_execution
    set -e
}

configure_firewall_close_port() {
    set +e

    show_firewall_status

    if [ "$(get_firewall_status)" = "inactive" ]; then
        print_error "$(msg service_inactive)"
        pause_execution
        set -e
        return
    fi

    echo ""
    echo "$(msg firewall_active_rules):"
    local rules_output=$(nft -a list table inet filter 2>/dev/null | grep -E "tcp dport|udp dport")

    if [ -z "$rules_output" ]; then
        print_warning "$(msg none)"
        pause_execution
        set -e
        return
    fi

    echo "$rules_output"
    echo ""

    read_input_with_escape "$(msg firewall_port_to_close)"
    local port_input="$READ_INPUT"

    if [ -z "$port_input" ] || [ "$port_input" = "ESC" ] || [ "$port_input" = "BACK" ]; then
        set -e
        return
    fi

    local ports_closed=0
    local ports_failed=0
    print_info "Procesando puertos..."

    # Si contiene comas (80,443,8080)
    if [[ "$port_input" =~ ^[0-9,]+$ ]]; then
        IFS=',' read -ra PORTS <<< "$port_input"
        for port in "${PORTS[@]}"; do
            port=$(echo "$port" | xargs)

            if ! validate_port "$port"; then
                ((ports_failed++))
                continue
            fi

            local handles=$(nft -a list table inet filter 2>/dev/null | grep -E "dport $port " | grep -oE "# handle [0-9]+" | awk '{print $3}')

            if [ -z "$handles" ]; then
                ((ports_failed++))
                continue
            fi

            while IFS= read -r handle; do
                if [ -n "$handle" ]; then
                    nft delete rule inet filter input handle "$handle" 2>/dev/null || true
                    ((ports_closed++))
                fi
            done <<< "$handles"
        done

    # Un solo puerto (80)
    elif validate_port "$port_input"; then
        local handles=$(nft -a list table inet filter 2>/dev/null | grep -E "dport $port_input " | grep -oE "# handle [0-9]+" | awk '{print $3}')

        if [ -z "$handles" ]; then
            print_warning "$(msg firewall_port_not_in_rules): $port_input"
            pause_execution
            set -e
            return
        fi

        while IFS= read -r handle; do
            if [ -n "$handle" ]; then
                nft delete rule inet filter input handle "$handle" 2>/dev/null || true
                ((ports_closed++))
            fi
        done <<< "$handles"

        log_message "INFO" "Firewall port $port_input closed"
        pause_execution
        set -e
        return

    # Si contiene rango (80:90)
    elif [[ "$port_input" =~ ^[0-9]+:[0-9]+$ ]]; then
        local start=$(echo "$port_input" | cut -d: -f1)
        local end=$(echo "$port_input" | cut -d: -f2)

        if ! validate_port "$start" || ! validate_port "$end"; then
            print_error "$(msg firewall_invalid_port)"
            pause_execution
            set -e
            return
        fi

        if [ "$start" -gt "$end" ]; then
            print_error "$(msg firewall_invalid_range)"
            pause_execution
            set -e
            return
        fi

        for port in $(seq "$start" "$end"); do
            local handles=$(nft -a list table inet filter 2>/dev/null | grep -E "dport $port " | grep -oE "# handle [0-9]+" | awk '{print $3}')

            if [ -z "$handles" ]; then
                ((ports_failed++))
                continue
            fi

            while IFS= read -r handle; do
                if [ -n "$handle" ]; then
                    nft delete rule inet filter input handle "$handle" 2>/dev/null || true
                    ((ports_closed++))
                fi
            done <<< "$handles"
        done

    else
        print_error "$(msg firewall_invalid_format)"
        pause_execution
        set -e
        return
    fi

    # Mostrar resumen una sola vez
    print_success "$(msg firewall_ports_closed_summary) $ports_closed"
    if [ "$ports_failed" -gt 0 ]; then
        print_warning "$ports_failed $(msg firewall_ports_failed)"
    fi
    log_message "INFO" "Firewall closed $ports_closed ports"

    pause_execution
    set -e
}

show_firewall_rules() {
    show_firewall_status

    if [ "$(get_firewall_status)" = "inactive" ]; then
        print_warning "$(msg service_inactive)"
        pause_execution
        return
    fi

    echo ""
    echo "$(msg firewall_active_rules):"
    nft list table inet filter
    echo ""
    pause_execution
}

save_firewall_rules() {
    set +e

    print_info "$(msg firewall_saving_rules)..."

    # Crear backup del archivo original
    [ -f /etc/nftables.conf ] && cp /etc/nftables.conf /etc/nftables.conf.bak

    # Guardar ruleset completo
    nft list ruleset > /etc/nftables.conf 2>/dev/null

    if [ $? -eq 0 ]; then
        print_success "$(msg firewall_rules_saved)"
    else
        print_error "$(msg firewall_rules_save_failed)"
    fi

    set -e
}

# ============================================================================
# FIREWALL MENU
# ============================================================================

menu_firewall() {
    breadcrumb_push "Firewall"

    while true; do
        show_firewall_status

        echo "  1) $(msg activate_service)"
        echo "  2) $(msg deactivate_service)"
        echo "  3) $(msg configure_service)"
        echo ""
echo -e "  ${YELLOW}0) $(msg back)${NC}"
        echo ""
        read_menu_option "$(msg select_option): "
        local choice="$MENU_INPUT"

        [[ "$choice" == "ESC" || "$choice" == "0" ]] && {
            breadcrumb_pop
            break
        }

        case $choice in
            1)
                enable_firewall
                pause_execution
                ;;
            2)
                disable_firewall
                pause_execution
                ;;
            3)
                breadcrumb_push "$(msg configure_service)"
                while true; do
                    show_firewall_status
                    echo ""
                    echo "  1) $(msg firewall_open_port)"
                    echo "  2) $(msg firewall_close_port)"
                    echo "  3) $(msg firewall_view_rules)"
                    echo ""
                    echo -e "  ${YELLOW}0) $(msg back)${NC}"
                    echo ""
                    read_menu_option "$(msg select_option): "
                    local sub_choice="$MENU_INPUT"

                    [[ "$sub_choice" == "ESC" || "$sub_choice" == "0" ]] && break

                    case $sub_choice in
                        1)
                            configure_firewall_open_port
                            ;;
                        2)
                            configure_firewall_close_port
                            ;;
                        3)
                            show_firewall_rules
                            ;;
                        *)
                            print_error "$(msg invalid_option)"
                            pause_execution
                            ;;
                    esac
                done
                breadcrumb_pop
                ;;
            *)
                print_error "$(msg invalid_option)"
                pause_execution
                ;;
        esac
    done
}

#menu_firewall() {
#    show_header
#    print_info "$(msg firewall_title)"
#    echo ""
#    print_warning "[FIREWALL - IMPLEMENTACION EN PROGRESO]"
#    echo ""
#    pause_execution
#}

# ============================================================================
# UPDATES MENU - HELPER FUNCTIONS
# ============================================================================

get_updates_status() {
    # Check if unattended-upgrades package is installed
    if ! is_service_installed "unattended-upgrades"; then
        echo "not_installed"
        return
    fi

    # Check if both timers are active
    if systemctl is-active --quiet apt-daily.timer && \
       systemctl is-active --quiet apt-daily-upgrade.timer; then
        echo "active"
    else
        echo "inactive"
    fi
}

get_current_download_time() {
    # Get OnCalendar from apt-daily.timer override or default
    local override_file="/etc/systemd/system/apt-daily.timer.d/override.conf"

    if [ -f "$override_file" ]; then
        grep -oP "OnCalendar=.*\K[0-9]{2}:[0-9]{2}" "$override_file" | head -1
    else
        # Default from system
        echo "06:00"
    fi
}

get_current_install_time() {
    # Get OnCalendar from apt-daily-upgrade.timer override or default
    local override_file="/etc/systemd/system/apt-daily-upgrade.timer.d/override.conf"

    if [ -f "$override_file" ]; then
        grep -oP "OnCalendar=.*\K[0-9]{2}:[0-9]{2}" "$override_file" | head -1
    else
        # Default from system
        echo "06:00"
    fi
}

get_current_days() {
    # Get days from apt-daily.timer override or default
    local override_file="/etc/systemd/system/apt-daily.timer.d/override.conf"

    if [ -f "$override_file" ]; then
        local calendar_line=$(grep "OnCalendar=" "$override_file" | grep -v "^OnCalendar=$" | head -1)

        # Extract day part (before time)
        if [[ "$calendar_line" =~ OnCalendar=([A-Za-z,0-9-]+)[[:space:]] ]]; then
            local days="${BASH_REMATCH[1]}"

            # Convert systemd day names to numbers
            days=$(echo "$days" | sed 's/Mon/1/g; s/Tue/2/g; s/Wed/3/g; s/Thu/4/g; s/Fri/5/g; s/Sat/6/g; s/Sun/0/g')
            echo "$days"
        else
            echo "0-6"
        fi
    else
        echo "0-6"
    fi
}

validate_time_format() {
    local time="$1"

    # Check format HH:MM
    if ! [[ "$time" =~ ^[0-9]{2}:[0-9]{2}$ ]]; then
        return 1
    fi

    # Extract hour and minute
    local hour=$(echo "$time" | cut -d: -f1)
    local minute=$(echo "$time" | cut -d: -f2)

    # Validate ranges
    if [ "$hour" -lt 0 ] || [ "$hour" -gt 23 ]; then
        return 1
    fi

    if [ "$minute" -lt 0 ] || [ "$minute" -gt 59 ]; then
        return 1
    fi

    return 0
}

validate_days_format() {
    local days="$1"

    # Allow patterns like: 0-6, 1,3,5, 0,2-4,6
    if ! [[ "$days" =~ ^[0-6,\-]+$ ]]; then
        return 1
    fi

    # Validate individual numbers don't exceed 0-6
    local IFS=','
    for segment in $days; do
        if [[ "$segment" =~ ^[0-9]$ ]]; then
            if [ "$segment" -lt 0 ] || [ "$segment" -gt 6 ]; then
                return 1
            fi
        elif [[ "$segment" =~ ^([0-9])-([0-9])$ ]]; then
            local start="${BASH_REMATCH[1]}"
            local end="${BASH_REMATCH[2]}"

            if [ "$start" -lt 0 ] || [ "$start" -gt 6 ] || \
               [ "$end" -lt 0 ] || [ "$end" -gt 6 ] || \
               [ "$start" -gt "$end" ]; then
                return 1
            fi
        else
            return 1
        fi
    done

    return 0
}

convert_days_to_systemd() {
    local days="$1"

    # Convert numeric format to systemd day names
    local result=""
    local IFS=','

    for segment in $days; do
        if [[ "$segment" =~ ^[0-9]$ ]]; then
            case "$segment" in
                0) result="${result}Sun," ;;
                1) result="${result}Mon," ;;
                2) result="${result}Tue," ;;
                3) result="${result}Wed," ;;
                4) result="${result}Thu," ;;
                5) result="${result}Fri," ;;
                6) result="${result}Sat," ;;
            esac
        elif [[ "$segment" =~ ^([0-9])-([0-9])$ ]]; then
            # Handle ranges (e.g., 1-5 = Mon-Fri)
            local start="${BASH_REMATCH[1]}"
            local end="${BASH_REMATCH[2]}"

            for ((i=start; i<=end; i++)); do
                case "$i" in
                    0) result="${result}Sun," ;;
                    1) result="${result}Mon," ;;
                    2) result="${result}Tue," ;;
                    3) result="${result}Wed," ;;
                    4) result="${result}Thu," ;;
                    5) result="${result}Fri," ;;
                    6) result="${result}Sat," ;;
                esac
            done
        fi
    done

    # Remove trailing comma
    result="${result%,}"
    echo "$result"
}

show_updates_status() {
    local status=$(get_updates_status)

    show_header
    print_info "$(msg updates_title)"
    echo ""

    # Service status
    case "$status" in
        active)
            echo -e "${GREEN}[+] $(msg service_active)${NC}"
            ;;
        inactive)
            echo -e "${YELLOW}[-] $(msg service_inactive)${NC}"
            ;;
        not_installed)
            echo -e "${RED}[X] $(msg service_not_installed)${NC}"
            return
            ;;
    esac

    echo ""

    # Show current configuration
    local download_time=$(get_current_download_time)
    local install_time=$(get_current_install_time)
    local days=$(get_current_days)

    echo "$(msg updates_download_hour): $download_time"
    echo "$(msg updates_install_hour): $install_time"
    echo "$(msg updates_days): $days"

    echo ""
}

install_and_enable_updates() {
    print_info "$(msg service_installing)"
    apt-get update >/dev/null 2>&1
    apt-get install -y unattended-upgrades apt-listchanges >/dev/null 2>&1

    print_success "$(msg service_installed_success)"

    # Enable automatic updates in config
    cat > /etc/apt/apt.conf.d/20auto-upgrades << 'EOF'
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
APT::Periodic::AutocleanInterval "7";
EOF

    # Configure default timers
    configure_timer "apt-daily.timer" "0-6" "02:00"
    configure_timer "apt-daily-upgrade.timer" "0-6" "04:00"

    # Enable and start timers
    systemctl enable apt-daily.timer apt-daily-upgrade.timer >/dev/null 2>&1
    systemctl start apt-daily.timer apt-daily-upgrade.timer >/dev/null 2>&1

    print_success "$(msg service_started)"
    print_success "$(msg updates_configured)"
    log_message "INFO" "Unattended-upgrades installed and enabled with default schedule"
}

enable_updates() {
    if [ "$(get_updates_status)" = "not_installed" ]; then
        install_and_enable_updates
    else
        print_info "$(msg service_activating)"
        systemctl enable apt-daily.timer apt-daily-upgrade.timer >/dev/null 2>&1
        systemctl start apt-daily.timer apt-daily-upgrade.timer >/dev/null 2>&1
        print_success "$(msg service_started)"
        print_success "$(msg service_enabled_boot)"
        log_message "INFO" "Unattended-upgrades timers enabled and started"
    fi
}

disable_updates() {
    print_info "$(msg service_deactivating)"
    systemctl stop apt-daily.timer apt-daily-upgrade.timer >/dev/null 2>&1
    systemctl disable apt-daily.timer apt-daily-upgrade.timer >/dev/null 2>&1
    print_success "$(msg service_stopped)"
    print_success "$(msg service_disabled_boot)"
    log_message "INFO" "Unattended-upgrades timers disabled and stopped"
}

configure_timer() {
    local timer_name="$1"
    local days="$2"
    local time="$3"

    # Convert days to systemd format
    local systemd_days=$(convert_days_to_systemd "$days")

    # Create override directory
    local override_dir="/etc/systemd/system/${timer_name}.d"
    mkdir -p "$override_dir"

    # Create override file
    cat > "${override_dir}/override.conf" << EOF
[Timer]
OnCalendar=
OnCalendar=${systemd_days} ${time}
RandomizedDelaySec=0
EOF

    # Reload systemd
    systemctl daemon-reload >/dev/null 2>&1
}

configure_updates_download_time() {
    show_updates_status

    local current_time=$(get_current_download_time)
    local current_days=$(get_current_days)

    echo ""
    echo "$(msg updates_example_time)"
    echo "$(msg updates_current_label): $current_time"
    echo ""
    read_input_with_escape "$(msg updates_new_download_time)"
    local new_time="$READ_INPUT"

    if [ -z "$new_time" ] || [ "$new_time" = "ESC" ] || [ "$new_time" = "BACK" ]; then
        return
    fi

    if ! validate_time_format "$new_time"; then
        print_error "$(msg updates_invalid_time_format)"
        pause_execution
        return
    fi

    if [ "$new_time" = "$current_time" ]; then
        print_info "$(msg config_value_unchanged)"
        pause_execution
        return
    fi

    # Configure timer
    configure_timer "apt-daily.timer" "$current_days" "$new_time"

    # Restart timer
    systemctl restart apt-daily.timer >/dev/null 2>&1

    print_success "$(msg updates_time_changed)"
    log_message "INFO" "Updates download time changed to $new_time"
    pause_execution
}

configure_updates_install_time() {
    show_updates_status

    local current_time=$(get_current_install_time)
    local current_days=$(get_current_days)

    echo ""
    echo "$(msg updates_example_time)"
    echo "$(msg updates_current_label): $current_time"
    echo ""
    read_input_with_escape "$(msg updates_new_install_time)"
    local new_time="$READ_INPUT"

    if [ -z "$new_time" ] || [ "$new_time" = "ESC" ] || [ "$new_time" = "BACK" ]; then
        return
    fi

    if ! validate_time_format "$new_time"; then
        print_error "$(msg updates_invalid_time_format)"
        pause_execution
        return
    fi

    if [ "$new_time" = "$current_time" ]; then
        print_info "$(msg config_value_unchanged)"
        pause_execution
        return
    fi

    # Configure timer
    configure_timer "apt-daily-upgrade.timer" "$current_days" "$new_time"

    # Restart timer
    systemctl restart apt-daily-upgrade.timer >/dev/null 2>&1

    print_success "$(msg updates_time_changed)"
    log_message "INFO" "Updates install time changed to $new_time"
    pause_execution
}

configure_updates_days() {
    show_updates_status

    local current_days=$(get_current_days)
    local download_time=$(get_current_download_time)
    local install_time=$(get_current_install_time)

    echo ""
    echo "$(msg updates_select_days_option):"
    echo "  1) $(msg updates_all_days)"
    echo "  2) $(msg updates_custom_days)"
    echo ""
    echo -e "  ${YELLOW}0) $(msg back)${NC}"
    echo ""
    read_menu_option "$(msg select_option): "
    local choice="$MENU_INPUT"

    [ "$choice" = "ESC" ] || [ "$choice" = "0" ] && return

    local new_days=""

    case "$choice" in
        1)
            new_days="0-6"
            ;;
        2)
            echo ""
            echo "$(msg updates_days_help)"
            echo "$(msg updates_current_label): $current_days"
            echo ""
            read_input_with_escape "$(msg updates_enter_custom_days)"
            new_days="$READ_INPUT"
            [ "$new_days" = "ESC" ] || [ "$new_days" = "BACK" ] && return

            if [ -z "$new_days" ]; then
                print_info "$(msg operation_cancelled)"
                pause_execution
                return
            fi

            if ! validate_days_format "$new_days"; then
                print_error "$(msg updates_invalid_days_format)"
                pause_execution
                return
            fi
            ;;
        0)
            return
            ;;
        *)
            print_error "$(msg invalid_option)"
            pause_execution
            return
            ;;
    esac

    if [ "$new_days" = "$current_days" ]; then
        print_info "$(msg config_value_unchanged)"
        pause_execution
        return
    fi

    # Configure both timers with new days
    configure_timer "apt-daily.timer" "$new_days" "$download_time"
    configure_timer "apt-daily-upgrade.timer" "$new_days" "$install_time"

    # Restart timers
    systemctl restart apt-daily.timer apt-daily-upgrade.timer >/dev/null 2>&1

    print_success "$(msg updates_days_changed)"
    log_message "INFO" "Updates days changed to $new_days"
    pause_execution
}

# ============================================================================
# UPDATES MENU
# ============================================================================

menu_updates() {
    breadcrumb_push "$(msg bc_updates)"

    while true; do
        show_updates_status

        echo "  1) $(msg activate_service)"
        echo "  2) $(msg deactivate_service)"
        echo "  3) $(msg configure_service)"
        echo ""
echo -e "  ${YELLOW}0) $(msg back)${NC}"
        echo ""
        read_menu_option "$(msg select_option): "
        local choice="$MENU_INPUT"

        [[ "$choice" == "ESC" || "$choice" == "0" ]] && {
            breadcrumb_pop
            break
        }

        case "$choice" in
            1)
                enable_updates
                pause_execution
                ;;
            2)
                disable_updates
                pause_execution
                ;;
            3)
                breadcrumb_push "$(msg configure_service)"
                while true; do
                    show_updates_status
                    echo ""
                    echo "  1) $(msg updates_change_download_time)"
                    echo "  2) $(msg updates_change_install_time)"
                    echo "  3) $(msg updates_change_days)"
                    echo ""
                    echo -e "  ${YELLOW}0) $(msg back)${NC}"
                    echo ""
                    read_menu_option "$(msg select_option): "
                    local config_choice="$MENU_INPUT"

                    [[ "$config_choice" == "ESC" || "$config_choice" == "0" ]] && break

                    case "$config_choice" in
                        1)
                            configure_updates_download_time
                            ;;
                        2)
                            configure_updates_install_time
                            ;;
                        3)
                            configure_updates_days
                            ;;
                        *)
                            print_error "$(msg invalid_option)"
                            pause_execution
                            ;;
                    esac
                done
                breadcrumb_pop
                ;;
            *)
                print_error "$(msg invalid_option)"
                pause_execution
                ;;
        esac
    done
}

#menu_updates() {
#    show_header
#    print_info "$(msg updates_title)"
#    echo ""
#    print_warning "[ACTUALIZACIONES - IMPLEMENTACION EN PROGRESO]"
#    echo ""
#    pause_execution
#}

# ============================================================================
# MAIN EXECUTION
# ============================================================================

main() {
    # Check root privileges
    if [ "$EUID" -ne 0 ]; then
        print_error "$(msg root_required)"
        sudo "$0"
        exit $?
    fi

    # Detect language
    if [[ "$LANG" =~ ^es ]]; then
        LANG_CHOICE="es"
    else
        LANG_CHOICE="en"
    fi

    # Set breadcrumb for services module
    breadcrumb_set "Synex Control" "$(msg bc_services)"

    while true; do
        show_main_menu
        read_menu_option "$(msg select_option): "
        local choice="$MENU_INPUT"

        [[ "$choice" == "ESC" || "$choice" == "0" ]] && {
            print_info "$(msg exiting)"
            return 0
        }

        case "$choice" in
            1)
                show_status_all
                pause_execution
                ;;
            2)
                menu_ssh
                ;;
            3)
                menu_samba
                ;;
            4)
                menu_nfs
                ;;
            5)
                menu_firewall
                ;;
            6)
                menu_updates
                ;;
            *)
                print_error "$(msg invalid_option)"
                pause_execution
                ;;
        esac
    done
}

# Run main if script is executed directly
if [ "${BASH_SOURCE[0]}" == "${0}" ]; then
    main "$@"
fi
