#!/bin/bash

viewLibrePortalConfigs()
{
    local specific_config="$1"  # Get the optional argument
    local config_files=()  # Array to store all config files with their paths
    local config_display_names=()  # Array to store display names (folder - filename)
    
    # Find all files in all subdirectories of /configs/ and sort by folder then filename
    while IFS= read -r -d '' file; do
        if [[ -f "$file" ]]; then
            local full_path="$file"
            local relative_path="${full_path#$configs_dir}"
            local folder_name=$(dirname "$relative_path")
            local file_name=$(basename "$file")
            
            # Skip .category files
            if [[ "$file_name" == ".category" ]]; then
                continue
            fi
            
            # For files in root configs folder, use "general" as folder name
            if [[ "$folder_name" == "." ]]; then
                folder_name="general"
            fi
            
            config_files+=("$full_path")
            config_display_names+=("$folder_name - $file_name")
        fi
    done < <(find "$configs_dir" -type f -print0 | sort -z -t'/' -k1,1 -k2,2)

    isHeader "Manage Config Files"

    if [ ${#config_files[@]} -eq 0 ]; then
        isNotice "No files found in /configs/ folder."
    fi

    declare -A config_timestamps  # Associative array to store config names and their modified timestamps

    # If a specific config name is provided, attempt to edit it directly
    if [[ -n "$specific_config" ]]; then
        for ((i = 0; i < ${#config_files[@]}; i++)); do
            local display_name="${config_display_names[i]}"
            local file_name=$(basename "${config_files[i]}")
            local file_name_without_prefix=${file_name#config_}
            local config_name=${file_name_without_prefix,,}

            if [[ "$file_name" == config_apps_* ]]; then
                config_name=${config_name#apps_}
            fi

            # Check if the specific config matches either the display name or config name
            if [[ "$display_name" == "$specific_config" ]] || [[ "$config_name" == "$specific_config" ]]; then
                $CFG_TEXT_EDITOR "${config_files[i]}"
                createTouch "${config_files[i]}" $sudo_user_name
                echo ""
                isNotice "Configuration file '$display_name' has been updated."
                echo ""
            fi
        done

        isNotice "No config found with the name '$specific_config'."
    fi

    PS3="Select a config to edit (Enter number, or x to exit): "
    while true; do
        for ((i = 0; i < ${#config_files[@]}; i++)); do
            local display_name="${config_display_names[i]}"
            local file_name=$(basename "${config_files[i]}")
            local file_name_without_prefix=${file_name#config_}
            local config_name=${file_name_without_prefix,,}

            if [[ "$file_name" == config_apps_* ]]; then
                config_name=${config_name#apps_}
            fi

            if [ "${config_timestamps[$display_name]}" ]; then
                local last_modified="${config_timestamps[$display_name]}"
            else
                local last_modified=$(stat -c "%y" "${config_files[i]}")
                config_timestamps["$display_name"]=$last_modified
            fi

            local formatted_last_modified=$(date -d "$last_modified" +"%m/%d %H:%M")

            isOption "$((i+1)). ${display_name,,} (Last modified: $formatted_last_modified)"
        done

        echo ""
        isOption "x. Exit"
        echo ""
        isQuestion "Enter number of config (or x to exit): "
        read -p "" selected_number

        if [[ "$selected_number" == "x" ]]; then
            if [[ $config_edited == "true" ]]; then
                echo ""
                isNotice "Reloading configuration file(s) for LibrePortal."
                echo ""
                sourceScanFiles "libreportal_configs";
            else
                isNotice "Exiting..."
                echo ""
                checkConfigFilesMissingVariables true;
                crontabSetupBackupScheduler;
            fi
        elif [[ "$selected_number" =~ ^[0-9]+$ ]] && [ "$selected_number" -ge 1 ] && [ "$selected_number" -le ${#config_files[@]} ]; then
            local index=$((selected_number - 1))
            local selected_file="${config_files[index]}"
            local selected_display_name="${config_display_names[index]}"

            $CFG_TEXT_EDITOR "$selected_file"
            createTouch "$selected_file" $sudo_user_name
            config_timestamps["$selected_display_name"]=$(stat -c "%y" "$selected_file")

            echo ""
            isNotice "Configuration file '$selected_display_name' has been updated."
            echo ""
        else
            isNotice "Invalid input. Please enter a valid number or 'x' to exit."
            echo ""
            read -p "Press Enter to continue."
        fi
    done
}
