#!/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=""

    # === DOKONČNO POPRAVLJENA LOGIKA ZA PREPOZNAVANJE STRANI ===
    if [[ "$file" == "./index.html" ]]; then
        active_placeholder="{{ACTIVE_NASLOVNICA}}"
    # DOKONČEN POPRAVEK: Ta pogoj zdaj prepozna SAMO glavno stran ponudbe
    elif [[ "$file" == *"/ponudba/index.html"* ]]; then
        active_placeholder="{{ACTIVE_PONUDBA}}"
    elif [[ "$file" == *"/kdo-sem/index.html"* ]]; then
        active_placeholder="{{ACTIVE_KDO_SEM}}"
    elif [[ "$file" == *"/kontakt/index.html"* ]]; then
        active_placeholder="{{ACTIVE_KONTAKT}}"
    # DOKONČEN POPRAVEK: Ta pogoj pravilno prepozna VSE strani pod Skupaj za vključevanje
    elif [[ "$file" == *"/skupaj-za-vkljucevanje/"* ]]; then
        active_placeholder="{{ACTIVE_VKLJUCEVANJE}}"
    elif [[ "$file" == *"/cene-in-reference/index.html"* || "$file" == *"/cene-in-sodelovanja/index.html"* ]]; then
        active_placeholder="{{ACTIVE_CENE}}"
    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."