#!/bin/bash

# WebUI system config update functions for LibrePortal
# These functions handle updating the actual config files from web interface

webuiUpdateSystemConfig() {
    local category_name="$1"
    local config_data="$2"
    
    # Validate category name
    if [[ -z "$category_name" ]]; then
        isError " Category name is required"
    fi
    
    local category_dir="$configs_dir/$category_name"
    if [[ ! -d "$category_dir" ]]; then
        isError " Category directory not found: $category_dir"
    fi
    
    echo "Updating configuration for category: $category_name"
    
    # Parse JSON data and update individual config files
    local updated_files=()
    
    # Extract config variables from JSON data
    echo "$config_data" | grep -o '"CFG_[A-Z0-9_]*":' | sed 's/[":]//g' | while read -r var_name; do
        if [[ -n "$var_name" ]]; then
            # Extract new value from JSON data
            local new_value=$(echo "$config_data" | grep -o "\"$var_name\":[[:space:]]*\"[^\"]*\"" | cut -d'"' -f4)
            
            if [[ -n "$new_value" ]]; then
                # Validate the new value
                if ! webuiValidateConfigValue "$var_name" "$new_value"; then
                    isError " Validation failed for $var_name with value: $new_value"
                    continue
                fi
                
                # Use our dynamic updateConfigOption function
                if updateConfigOption "$var_name" "$new_value"; then
                    echo "Updated $var_name = $new_value"
                    
                    # Track which category was updated for JSON regeneration
                    updated_files+=("$category_name")
                else
                    isError " Failed to update $var_name"
                fi
            fi
        fi
    done
    
    # Regenerate the unified JSON file
    if [[ ${#updated_files[@]} -gt 0 ]]; then
        echo "Regenerating unified configs.json..."
        webuiGenerateSystemConfigs
        
        echo "Configuration update completed for category: $category_name"
    else
        echo "No configuration updates were made"
    fi
    
}

# Validate config value before updating
webuiValidateConfigValue() {
    local var_name="$1"
    local var_value="$2"
    
    case "$var_name" in
        CFG_BACKUP_CRONTAB_APP)
            # Validate crontab format
            if ! echo "$var_value" | grep -qE '^[0-9*,-/]+\s+[0-9*,-/]+\s+[0-9*,-/]+\s+[0-9*,-/]+\s+[0-9*,-/]+$'; then
                isError " Invalid crontab format for $var_name"
            fi
            ;;
        CFG_BACKUP_KEEP_LAST|CFG_BACKUP_KEEP_DAILY|CFG_BACKUP_KEEP_WEEKLY|CFG_BACKUP_KEEP_MONTHLY|CFG_BACKUP_KEEP_YEARLY|CFG_BACKUP_VERIFY_DATA_PERCENT|CFG_UPDATER_CHECK|CFG_SWAPFILE_SIZE|CFG_GENERATED_PASS_LENGTH|CFG_WEBUI_LOG_STREAM_IDLE_TIMEOUT_MINUTES|CFG_WEBUI_LOG_STREAM_MAX_DURATION_MINUTES|CFG_WEBUI_LOG_STREAM_MAX_LINES_PER_SEC)
            # Validate numeric values
            if ! echo "$var_value" | grep -qE '^[0-9]+$'; then
                isError " $var_name must be a positive integer"
            fi
            ;;
        CFG_TIMEZONE)
            # Validate timezone format
            if ! echo "$var_value" | grep -qE '^[A-Za-z_]+/[A-Za-z_]+$|^Etc/UTC$'; then
                isError " Invalid timezone format for $var_name"
            fi
            ;;
        CFG_NETWORK_SUBNET)
            # Validate CIDR format
            if ! echo "$var_value" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/[0-9]+$'; then
                isError " Invalid subnet format for $var_name"
            fi
            ;;
        CFG_TRAEFIK_EMAIL)
            # Validate email format
            if ! echo "$var_value" | grep -qE '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'; then
                isError " Invalid email format for $var_name"
            fi
            ;;
        CFG_MAIL_HOST)
            # Validate hostname format
            if ! echo "$var_value" | grep -qE '^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'; then
                isError " Invalid hostname format for $var_name"
            fi
            ;;
        CFG_MAIL_PORT)
            # Validate port number (1-65535)
            if ! echo "$var_value" | grep -qE '^[0-9]+$' || [ "$var_value" -lt 1 ] || [ "$var_value" -gt 65535 ]; then
                isError " $var_name must be a valid port number (1-65535)"
            fi
            ;;
        CFG_MAIL_SECURE)
            # Validate mail security options
            if ! echo "$var_value" | grep -qE '^(tls|ssl|none)$'; then
                isError " $var_name must be tls, ssl, or none"
            fi
            ;;
        CFG_MAIL_USERNAME)
            # Validate email format for username
            if ! echo "$var_value" | grep -qE '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'; then
                isError " Invalid email format for $var_name"
            fi
            ;;
        CFG_MAIL_FROM)
            # Validate email format for from address
            if ! echo "$var_value" | grep -qE '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'; then
                isError " Invalid email format for $var_name"
            fi
            ;;
    esac
    
}
