<?php
//  -------------------------------------------------------------
//  Wechselnde Sprücke mit Begrüßung und Nachwort (zeitgesteuert) anzeigen.
//  Diese Datei kann in Ihrer Website includiert werden (Anleitung beachten).
//  
//  Bitte zuerst die Datei readme.html lesen ! Datei darf nicht bearbeitet werden!
//  
//  © S.G.Schiffer 2025 - sgs-visual.de
//  Es gelten die Nutzungsbedingungen, der Haftungsausschluss und 
//  das Copyright (darf nicht entfernt werden - Urheberrecht) wie in der 
//  readme.html beschrieben.
//  
// --------------------------------------------------------------

if (function_exists('mb_internal_encoding')) {
    mb_internal_encoding('UTF-8');
}

$sprueche_ordner = __DIR__ . '/sprueche';
$webfonts_ordner = __DIR__ . '/webfonts';
$aktuelle_konfiguration = $sprueche_ordner . '/AKTUELL_sprueche.json';
$path_config_file = __DIR__ . '/path_config.php';

if (file_exists($path_config_file)) {
    require_once $path_config_file;
}

if (!defined('SGS_BASE_PATH')) {
    define('SGS_BASE_PATH', rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\'));
}

function getWebFontData($font_dir) {
    $font_groups = [];
    $font_families_for_select = [];
    $font_files = glob($font_dir . '/*.{eot,otf,woff,woff2,svg,ttf}', GLOB_BRACE);
    if (!is_array($font_files)) { return ['families' => [], 'groups' => []]; }
    foreach ($font_files as $file) {
        $base_name = pathinfo($file, PATHINFO_FILENAME);
        $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        $family_name = preg_replace('/-(Regular|Bold|Italic|Thin|Light|Medium|SemiBold|ExtraBold|Black|Oblique).*/i', '', $base_name);
        if (!in_array($family_name, $font_families_for_select)) { $font_families_for_select[] = $family_name; }
        $style_name = str_replace($family_name . '-', '', $base_name);
        if(empty($style_name) || $style_name == $family_name) $style_name = 'Regular';
        $font_groups[$family_name][$style_name][$extension] = basename($file);
    }
    sort($font_families_for_select);
    return ['families' => $font_families_for_select, 'groups' => $font_groups];
}

function buildFontFacesCss($font_groups, $base_url = 'webfonts') {
    $faces = '';
    foreach ($font_groups as $family_name => $styles) {
        foreach ($styles as $style_name => $formats) {
            $weight = '400'; $style = 'normal'; $style_name_lower = strtolower($style_name);
            if (strpos($style_name_lower, 'italic') !== false) $style = 'italic';
            if (strpos($style_name_lower, 'oblique') !== false) $style = 'oblique';
            if (strpos($style_name_lower, 'thin') !== false) $weight = '100';
            else if (strpos($style_name_lower, 'extralight') !== false) $weight = '200';
            else if (strpos($style_name_lower, 'light') !== false) $weight = '300';
            else if (strpos($style_name_lower, 'regular') !== false) $weight = '400';
            else if (strpos($style_name_lower, 'medium') !== false) $weight = '500';
            else if (strpos($style_name_lower, 'semibold') !== false) $weight = '600';
            else if (strpos($style_name_lower, 'bold') !== false) $weight = '700';
            else if (strpos($style_name_lower, 'extrabold') !== false) $weight = '800';
            else if (strpos($style_name_lower, 'black') !== false) $weight = '900';
            $faces .= "@font-face {\n";
            $faces .= "    font-family: '" . $family_name . "';\n";
            $faces .= "    font-style: " . $style . ";\n";
            $faces .= "    font-weight: " . $weight . ";\n";
            $faces .= "    font-display: swap;\n";
            $srcs = [];
            if (isset($formats['eot'])) { $url = $base_url . '/' . $formats['eot']; $faces .= "    src: url('" . $url . "');\n"; $srcs[] = "url('" . $url . "?#iefix') format('embedded-opentype')"; }
            if (isset($formats['woff2'])) { $url = $base_url . '/' . $formats['woff2']; $srcs[] = "url('" . $url . "') format('woff2')"; }
            if (isset($formats['woff'])) { $url = $base_url . '/' . $formats['woff']; $srcs[] = "url('" . $url . "') format('woff')"; }
            if (isset($formats['ttf'])) { $url = $base_url . '/' . $formats['ttf']; $srcs[] = "url('" . $url . "') format('truetype')"; }
            if (isset($formats['otf'])) { $url = $base_url . '/' . $formats['otf']; $srcs[] = "url('" . $url . "') format('opentype')"; }
            if (isset($formats['svg'])) { $url = $base_url . '/' . $formats['svg']; $srcs[] = "url('" . $url . "#" . pathinfo($formats['svg'], PATHINFO_FILENAME) . "') format('svg')"; }
            if (!empty($srcs)) { $faces .= "    src: " . implode(",\n         ", $srcs) . ";\n"; }
            $faces .= "}\n";
        }
    }
    return $faces;
}

function generateCodeFromData($data, $all_webfont_data) {
    $font_face_css = '';
    $used_webfonts = [];
    foreach ($data['styles'] as $style) {
        $font_family = trim($style['font_family'], " '\"");
        if (in_array($font_family, $all_webfont_data['families'])) {
            $used_webfonts[$font_family] = true;
        }
    }
    if (!empty($used_webfonts)) {
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
        $host = $_SERVER['HTTP_HOST'];
        $base_font_url = $protocol . "://" . $host . SGS_BASE_PATH . "/webfonts";
        $used_font_groups = array_intersect_key($all_webfont_data['groups'], $used_webfonts);
        $font_face_css = "<style>\n" . buildFontFacesCss($used_font_groups, $base_font_url) . "</style>\n";
    }
    $styles = $data['styles'];
    $sprueche_array = !empty($data['sprueche']) ? $data['sprueche'] : array(array('text' => '', 'autor' => ''));
    $zeitraeume = !empty($data['zeitraeume']) ? $data['zeitraeume'] : array();
    $json_options = JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE;
    $code = "<!-- Script Anfang -->\n";
    $code .= $font_face_css;
    $code .= "<div id=\"sgs-gruss-container\"></div>\n\n";
    $code .= "<script>\n";
    $code .= "document.addEventListener('DOMContentLoaded', function() {\n";
    $code .= "    var config = {\n";
    $code .= "        styles: " . json_encode($styles, $json_options) . ",\n";
    $code .= "        sprueche: " . json_encode($sprueche_array, $json_options) . ",\n";
    $code .= "        zeitraeume: " . json_encode($zeitraeume, $json_options) . "\n";
    $code .= "    };\n\n";
    $code .= "    function getStyleString(styleObject) { return 'font-family: ' + styleObject.font_family + '; ' + 'font-size: ' + styleObject.font_size + 'px; ' + 'font-weight: ' + styleObject.font_weight + '; ' + 'font-style: ' + styleObject.font_style + '; ' + 'color: ' + styleObject.color + ';'; }\n\n";
    $code .= "    function zeigeBegruessung() {\n";
    $code .= "        var jetzt = new Date(); var stunde = jetzt.getHours(); var aktuelleBegruessung = ''; var aktuellesNachwort = '';\n";
    $code .= "        for (var i = 0; i < config.zeitraeume.length; i++) { if (stunde >= config.zeitraeume[i].von && stunde <= config.zeitraeume[i].bis) { aktuelleBegruessung = config.zeitraeume[i].begruessung; aktuellesNachwort = config.zeitraeume[i].nachwort; break; } }\n\n";
    $code .= "        var aktuellerSpruch = null;\n";
    $code .= "        if (config.sprueche.length > 0 && config.sprueche[0].text !== '') { aktuellerSpruch = config.sprueche[Math.floor(Math.random() * config.sprueche.length)]; }\n\n";
    $code .= "        var container = document.getElementById('sgs-gruss-container');\n";
    $code .= "        if (container) {\n";
    $code .= "            var html = '';\n";
    $code .= "            if (aktuelleBegruessung) { html += '<p style=\"' + getStyleString(config.styles.begruessung) + ' margin: 0; padding: 0;\">' + aktuelleBegruessung + '</p>'; }\n";
    $code .= "            if (aktuellerSpruch) { html += '<p style=\"' + getStyleString(config.styles.spruch) + ' margin: 5px 0; padding: 0;\">' + aktuellerSpruch.text + '</p>'; if (aktuellerSpruch.autor) { html += '<p style=\"' + getStyleString(config.styles.autor) + ' margin: 2px 0 5px 0; padding: 0;\">' + aktuellerSpruch.autor + '</p>'; } }\n";
    $code .= "            if (aktuellesNachwort) { html += '<p style=\"' + getStyleString(config.styles.nachwort) + ' margin: 0; padding: 0;\">' + aktuellesNachwort + '</p>'; }\n";
    $code .= "            container.innerHTML = html;\n";
    $code .= "        }\n";
    $code .= "    }\n\n";
    $code .= "    zeigeBegruessung();\n";
    $code .= "});\n";
    $code .= "</script>\n";
    $code .= "<!-- Script Ende - &copy; sgs-visual.de 2025 -->";
    return $code;
}

if (file_exists($aktuelle_konfiguration)) {
    $json_inhalt = file_get_contents($aktuelle_konfiguration);
    $form_data = json_decode($json_inhalt, true);

    if (is_array($form_data)) {
        $all_webfont_data = getWebFontData($webfonts_ordner);
        echo generateCodeFromData($form_data, $all_webfont_data);
    } else {
        echo "<!-- Fehler: Die Konfigurationsdatei 'AKTUELL_sprueche.json' ist fehlerhaft. -->";
    }
} else {
    echo "<!-- Fehler: Es wurde noch keine Konfiguration als 'AKTUELL' festgelegt. Bitte im Generator eine Datei auswählen und als aktuell festlegen. -->";
}

?>