#!/bin/bash

# --- KONFIGURACIJA ---
TEMPLATE_FILE="header-template.html"
PROCESSED_TEMPLATE_TMP="header.tmp"
HTML_FILES=$(find . -name "*.html" ! -path "./$TEMPLATE_FILE")

# --- PREVERJANJA ---
if [ ! -f "$TEMPLATE_FILE" ]; then
    echo "NAPAKA: Predloga '$TEMPLATE_FILE' ne obstaja."
    exit 1
fi

# --- GLAVNA LOGIKA ---
echo "Začenjam s posodabljanjem menijev..."

template_content=$(<"$TEMPLATE_FILE")

for file in $HTML_FILES; do
    processed_header="$template_content"
    active_placeholder=""

    # === PREPOZNAVANJE AKTIVNE STRANI ===
    if [[ "$file" == "./index.html" ]]; then
        active_placeholder="{{ACTIVE_NASLOVNICA}}"
    elif [[ "$file" == *"/ponudba/"* ]]; then
        active_placeholder="{{ACTIVE_PONUDBA}}"
    elif [[ "$file" == *"/kdo-sem/"* ]]; then
        active_placeholder="{{ACTIVE_KDO_SEM}}"
    elif [[ "$file" == *"/kontakt/"* ]]; then
        active_placeholder="{{ACTIVE_KONTAKT}}"
    # Ločimo medkulturno posredovanje in delavnice
    elif [[ "$file" == *"/medkulturno-posredovanje/"* ]]; then
        active_placeholder="{{ACTIVE_VKLJUCEVANJE}}"
    elif [[ "$file" == *"/delavnice/"* || "$file" == *"/delavnica-"* ]]; then
        active_placeholder="{{ACTIVE_DELAVNICE}}"
    elif [[ "$file" == *"/cene-in-reference/"* || "$file" == *"/cene-in-sodelovanja/"* ]]; then
        active_placeholder="{{ACTIVE_CENE}}"
    elif [[ "$file" == *"/pogosta-vprasanja/"* ]]; then
        active_placeholder="{{ACTIVE_FAQ}}"
    elif [[ "$file" == *"/blog/"* ]]; then
        active_placeholder="{{ACTIVE_BLOG}}"
    fi

    if [ -n "$active_placeholder" ]; then
        processed_header="${processed_header//$active_placeholder/class=\"active\"}"
    fi

    processed_header=$(echo "$processed_header" | sed 's/{{[A-Z_]*}}//g')
    echo "$processed_header" > "$PROCESSED_TEMPLATE_TMP"

    awk '
        BEGIN { in_header = 0; replaced = 0 }
        /<header class="main-header">/ {
            if (!in_header) {
                while ((getline line < "header.tmp") > 0) {
                    print line
                }
                close("header.tmp")
                in_header = 1
                replaced = 1
            }
        }
        /<\/header>/ {
            in_header = 0
            next
        }
        !in_header { print }
        END { exit !replaced }
    ' "$file" > "$file.tmp"

    if [ $? -eq 0 ]; then
        mv "$file.tmp" "$file"
        echo "Uspešno posodobljen meni v datoteki: $file"
    else
        rm -f "$file.tmp"
        echo "NAPAKA: Meni v datoteki '$file' ni bil zamenjan. Preverite značko '<header class=\"main-header\">'."
    fi
done

rm -f "$PROCESSED_TEMPLATE_TMP"
echo "Posodabljanje zaključeno."