<?php
//  -------------------------------------------------------------
//  Wechselnde Sprücke mit Begrüßung und Nachwort (zeitgesteuert)
//  
//  Bitte zuerst die Datei readme.html lesen !
//  
//  © 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.
//  
// --------------------------------------------------------------

session_start();

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

header('Content-Type: text/html; charset=utf-8');

$password = 'passwort';  //  ---------  'passwort' anpassen!  -----
$is_logged_in = (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true);
$login_success = false;

if (isset($_GET['logout'])) {
    $_SESSION['loggedin'] = false;
    session_destroy();
    header('Location: ' . basename(__FILE__));
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['password'])) {
    if ($_POST['password'] === $password) {
        $_SESSION['loggedin'] = true;
        $is_logged_in = true;
        $login_success = true;
    } else {
        $login_error = 'Falsches Passwort!';
    }
}

$sprueche_ordner = __DIR__ . '/sprueche';
$webfonts_ordner = __DIR__ . '/webfonts';
$json_suffix = '_sprueche.json';

$generated_code = '';
$form_data = array();
$feedback = array();
$current_file_basename = '';

if ($is_logged_in) {
    if (!is_dir($sprueche_ordner)) { @mkdir($sprueche_ordner, 0777, true); }
    if (!is_dir($webfonts_ordner)) { @mkdir($webfonts_ordner, 0777, true); }
}

function set_feedback($type, $message, $context_id) {
    $_SESSION['feedback'] = ['type' => $type, 'message' => $message, 'context' => $context_id];
}

if ($is_logged_in && $_SERVER["REQUEST_METHOD"] == "POST") {
    if (isset($_POST['upload_font']) && isset($_FILES['webfont']) && $_FILES['webfont']['error'] !== UPLOAD_ERR_NO_FILE) {
        if ($_FILES['webfont']['error'] == 0) {
            $allowed_extensions = ['eot', 'otf', 'woff', 'woff2', 'svg', 'ttf'];
            $file_info = pathinfo($_FILES['webfont']['name']);
            $extension = strtolower($file_info['extension']);

            if (in_array($extension, $allowed_extensions)) {
                $target_file = $webfonts_ordner . '/' . basename($_FILES['webfont']['name']);
                if (move_uploaded_file($_FILES['webfont']['tmp_name'], $target_file)) {
                    set_feedback('success', "Webfont '" . htmlspecialchars(basename($_FILES['webfont']['name'])) . "' wurde hochgeladen.", 'webfonts-management');
                } else {
                    set_feedback('error', "Fehler beim Verschieben der hochgeladenen Datei.", 'webfonts-management');
                }
            } else {
                set_feedback('error', "Fehler: Dateityp nicht erlaubt.", 'webfonts-management');
            }
        } else {
            set_feedback('error', "Fehler beim Upload: Code " . $_FILES['webfont']['error'], 'webfonts-management');
        }
        $_SESSION['form_data_POST'] = $_POST;
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }

    if (isset($_POST['delete_font'])) {
        $font_to_delete = basename($_POST['delete_font']);
        $font_path = $webfonts_ordner . '/' . $font_to_delete;
        if (file_exists($font_path) && strpos(realpath($font_path), realpath($webfonts_ordner)) === 0) {
            unlink($font_path);
            set_feedback('success', "Webfont '" . htmlspecialchars($font_to_delete) . "' wurde gel&ouml;scht.", 'webfonts-management');
        }
        $_SESSION['form_data_POST'] = $_POST;
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }
}

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);
        $style_name = str_replace($family_name . '-', '', $base_name);
        if(empty($style_name) || $style_name == $family_name) $style_name = 'Regular';
        if (!in_array($family_name, $font_families_for_select)) { $font_families_for_select[] = $family_name; }
        $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 mapPostToNestedData($post) {
    $nested_data = array('styles' => array(), 'sprueche' => array(), 'zeitraeume' => array());
    $style_keys = array('begruessung', 'spruch', 'nachwort', 'autor');
    foreach ($style_keys as $key) {
        $nested_data['styles'][$key] = array(
            'font_family' => isset($post["font_family_$key"]) ? $post["font_family_$key"] : 'Arial, sans-serif', 'font_size' => isset($post["font_size_$key"]) ? (int)$post["font_size_$key"] : 14, 'font_weight' => isset($post["font_weight_$key"]) ? (int)$post["font_weight_$key"] : 500, 'font_style' => isset($post["font_italic_$key"]) ? 'italic' : 'normal', 'color' => isset($post["color_$key"]) ? $post["color_$key"] : '#333333'
        );
    }
    if (isset($post['spruch_text']) && is_array($post['spruch_text'])) {
        for ($i = 0; $i < count($post['spruch_text']); $i++) {
            if (!empty($post['spruch_text'][$i])) {
                $nested_data['sprueche'][] = array('text' => $post['spruch_text'][$i], 'autor' => isset($post['spruch_autor'][$i]) ? $post['spruch_autor'][$i] : '');
            }
        }
    }
    if (isset($post['von_stunde']) && is_array($post['von_stunde'])) {
        for ($i = 0; $i < count($post['von_stunde']); $i++) {
            if (isset($post['bis_stunde'][$i], $post['begruessung'][$i], $post['nachwort'][$i])) {
                 $nested_data['zeitraeume'][] = array('von' => (int)$post['von_stunde'][$i], 'bis' => (int)$post['bis_stunde'][$i], 'begruessung' => $post['begruessung'][$i], 'nachwort' => $post['nachwort'][$i]);
            }
        }
    }
    return $nested_data;
}

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'];
        $path = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
        $base_font_url = $protocol . "://" . $host . $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 ($is_logged_in && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['upload_font']) && !isset($_POST['delete_font'])) {
        $current_file_basename = isset($_POST['current_filename']) ? $_POST['current_filename'] : '';

        if (isset($_POST['save_as_new'])) {
            $filename = isset($_POST['filename']) ? trim($_POST['filename']) : '';
            $sanitized_filename = preg_replace('/[^a-zA-Z0-9_-]/', '', $filename);
            if (!empty($sanitized_filename)) {
                $current_file_basename = $sanitized_filename . $json_suffix;
                $full_path = $sprueche_ordner . '/' . $current_file_basename;
                $settings_to_save = mapPostToNestedData($_POST);
                file_put_contents($full_path, json_encode($settings_to_save, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
                set_feedback('success', "Einstellungen erfolgreich in '" . htmlspecialchars($current_file_basename) . "' gespeichert.", 'save-as-new');
            } else {
                set_feedback('error', "Fehler: Bitte geben Sie einen g&uuml;ltigen Dateinamen an.", 'save-as-new');
            }
        }

        if (isset($_POST['save_changes'])) {
            if (!empty($current_file_basename)) {
                $full_path = $sprueche_ordner . '/' . $current_file_basename;
                $settings_to_save = mapPostToNestedData($_POST);
                file_put_contents($full_path, json_encode($settings_to_save, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
                set_feedback('success', "&Auml;nderungen in '" . htmlspecialchars($current_file_basename) . "' erfolgreich gespeichert.", 'save-changes');
            }
        }

        if (isset($_POST['load_settings'])) {
            $selected_file = isset($_POST['file_selection']) ? $_POST['file_selection'] : '';
            $full_path = $sprueche_ordner . '/' . $selected_file;
            if (!empty($selected_file) && file_exists($full_path)) {
                $form_data = json_decode(file_get_contents($full_path), true);
                $current_file_basename = $selected_file;
                set_feedback('success', "Einstellungen aus '" . htmlspecialchars($selected_file) . "' geladen.", 'file-management');
            }
        }

        if (isset($_POST['set_as_current'])) {
            $selected_file = isset($_POST['file_selection']) ? $_POST['file_selection'] : '';
            $source_path = $sprueche_ordner . '/' . $selected_file;
            if (!empty($selected_file) && file_exists($source_path)) {
                $destination_path = $sprueche_ordner . '/AKTUELL' . $json_suffix;
                $path_config_file = __DIR__ . '/path_config.php';
                $web_path = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
                $config_content = "<?php\n// Diese Datei wird automatisch vom Spruch-Generator erstellt. Nicht manuell bearbeiten.\ndefine('SGS_BASE_PATH', '" . addslashes($web_path) . "');\n?>";
                $path_saved = @file_put_contents($path_config_file, $config_content);
                $feedback_message_text = '';

                if ($source_path === $destination_path) {
                    $feedback_message_text = "Die Konfiguration '" . htmlspecialchars($selected_file) . "' ist bereits als aktuell festgelegt.";
                } else if (copy($source_path, $destination_path)) {
                    $feedback_message_text = "Konfiguration '" . htmlspecialchars($selected_file) . "' ist jetzt live als 'AKTUELL' festgelegt.";
                } else {
                    $feedback_message_text = "Fehler: Die Konfiguration konnte nicht als aktuell festgelegt werden. (M&ouml;gliche Ursache: Fehlende Schreibrechte im Ordner 'sprueche')";
                }
                if (!$path_saved) {
                    $feedback_message_text .= "<br><strong style='color:#DC3623;'>WICHTIGER HINWEIS:</strong> Die Pfad-Konfigurationsdatei ('path_config.php') konnte nicht geschrieben werden. Webfonts werden m&ouml;glicherweise nicht korrekt angezeigt. Bitte pr&uuml;fen Sie die Schreibrechte f&uuml;r das Generator-Verzeichnis.";
                }
                set_feedback('success', $feedback_message_text, 'file-management');
            }
        }

        if (isset($_POST['delete_settings'])) {
            $selected_file = isset($_POST['file_selection']) ? $_POST['file_selection'] : '';
            $full_path = $sprueche_ordner . '/' . $selected_file;
            if (!empty($selected_file) && file_exists($full_path)) {
                @unlink($full_path);
                set_feedback('success', "Datei '" . htmlspecialchars($selected_file) . "' wurde gel&ouml;scht.", 'file-management');
                $current_file_basename = '';
            }
        }

        if (isset($_POST['download_json'])) {
            $file_to_download = isset($_POST['file_to_download']) ? basename($_POST['file_to_download']) : '';
            $full_path = $sprueche_ordner . '/' . $file_to_download;
            if (!empty($file_to_download) && file_exists($full_path)) {
                header('Content-Description: File Transfer'); header('Content-Type: application/json; charset=utf-8'); header('Content-Disposition: attachment; filename="' . $file_to_download . '"'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($full_path)); readfile($full_path); exit;
            }
        }

        $all_webfont_data = getWebFontData($webfonts_ordner);

        if (isset($_POST['generate_code'])) {
            $form_data_for_code = mapPostToNestedData($_POST);
            $generated_code = generateCodeFromData($form_data_for_code, $all_webfont_data);
            set_feedback('success', 'Code wurde erfolgreich generiert.', 'generate-code');
        }

        if (isset($_POST['download_code'])) {
            $form_data_for_code = mapPostToNestedData($_POST);
            $code_to_download = generateCodeFromData($form_data_for_code, $all_webfont_data);
            header('Content-Type: text/plain; charset=utf-8'); header('Content-Disposition: attachment; filename="spruch_code.txt"'); header('Content-Length: ' . strlen($code_to_download)); echo $code_to_download; exit;
        }

        if (empty($form_data)) {
            $form_data = mapPostToNestedData($_POST);
        }
    }
}

if (isset($_SESSION['feedback'])) {
    $feedback = $_SESSION['feedback'];
    unset($_SESSION['feedback']);
}

if (isset($_SESSION['form_data_POST'])) {
    $form_data = mapPostToNestedData($_SESSION['form_data_POST']);
    $current_file_basename = isset($_SESSION['form_data_POST']['current_filename']) ? $_SESSION['form_data_POST']['current_filename'] : '';
    unset($_SESSION['form_data_POST']);
}

if ($is_logged_in && $_SERVER['REQUEST_METHOD'] === 'GET' && empty($form_data) && empty($feedback)) {
    $json_files = glob($sprueche_ordner . '/*' . $json_suffix);
    if (!empty($json_files)) {
        usort($json_files, function($a, $b) { return filemtime($b) - filemtime($a); });
        $form_data = json_decode(file_get_contents($json_files[0]), true);
        $current_file_basename = basename($json_files[0]);
    }
}

function getFormValue($source, $key, $default = '') {
    if (empty($source)) return $default;
    $keys = explode('.', $key);
    $value = $source;
    foreach ($keys as $k) {
        if (!isset($value[$k])) return $default;
        $value = $value[$k];
    }
    return $value;
}
function isChecked($source, $key) {
    $value = getFormValue($source, $key, 'normal');
    return $value === 'italic';
}

function display_feedback($context_id, $feedback_data) {
    if (!empty($feedback_data) && $feedback_data['context'] === $context_id) {
        $type_class = $feedback_data['type'] === 'error' ? 'feedback-error' : 'feedback-success';
        echo '<div class="feedback-message ' . $type_class . '" id="feedback-' . $context_id . '">' . $feedback_data['message'] . '</div>';
    }
}

$webfont_data = $is_logged_in ? getWebFontData($webfonts_ordner) : ['families' => [], 'groups' => []];
$webfont_css = $is_logged_in ? buildFontFacesCss($webfont_data['groups']) : '';
$webfont_families = $webfont_data['families'];

?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Spruch-Code-Generator</title>
    <meta name="author" content="S.G.Schiffer">
    <meta name="robots" content="index,nofollow">
    <meta name="generator" content="SGS Sayings Generator">
    <style>
        body { font-family: Arial, sans-serif; font-size: 14px; background-color: #f0f0f0; color: #333; margin: 0; padding: 20px; }
        .container { max-width: 900px; margin: 0 auto; background-color: #fff; padding: 20px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
        .login-wrapper { max-width: 400px; margin: 50px auto; padding: 30px; background-color: #fff; border: 1px solid #ddd; text-align: center; }
        .form-wrapper { background-color: #fff; padding: 20px; }
        .form-section { margin-bottom: 20px; padding: 15px; border: 1px solid #ddd; }
        .form-section-title { font-size: 16px; font-weight: 600; margin-bottom: 15px; padding-bottom: 5px; border-bottom: 1px solid #ccc; }
        .form-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 20px; }
        .form-group { display: flex; flex-direction: column; }
        .form-group-checkbox { display: flex; flex-direction: row; align-items: center; margin-top: 10px; }
        label { font-weight: 600; margin-bottom: 5px; font-size: 14px; }
        input[type="text"], input[type="password"], input[type="number"], input[type="color"], select, textarea { border: 2px solid #000; font-family: Arial, sans-serif; font-weight: 600; padding: 8px; font-size: 14px; box-sizing: border-box; width: 100%; }
        input[type="checkbox"] { border: 2px solid #000; width: 20px; height: 20px; margin-right: 10px; }
        input[type="color"] { height: 40px; padding: 5px; }
        .zeitraum-block, .spruch-block { border: 1px solid #ccc; padding: 15px; margin-bottom: 15px; background-color: #f9f9f9; }
        .block-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
        .block-title { font-size: 15px; font-weight: 600; }
        .btn { border: 2px solid #000; font-family: Arial, sans-serif; font-weight: 600; text-decoration: none; padding: 10px 15px; cursor: pointer; background-color: #e0e0e0; color: #000; font-size: 14px; }
        .btn:disabled { background-color: #ccc; cursor: not-allowed; border-color: #999; }
        .btn-add { background-color: #28a745; color: #fff; }
        .btn-remove, .btn-delete { background-color: #DC3623; color: #FFF; }
        .btn-generate { background-color: #007bff; color: #fff; }
        .btn-preview { background-color: #0056b3; color: #fff; }
        .btn-save { background-color: #17a2b8; color: #fff; }
        .btn-load { background-color: #ffc107; color: #000; }
        .btn-download { background-color: #6c757d; color: #fff; }
        .btn-login { background-color: #DC3623; color: #FFF; width: 100%; padding: 12px; font-size: 16px; margin-top: 15px; }
        .button-group { display: flex; flex-wrap: wrap; gap: 10px; }
        .file-management-grid { display: grid; grid-template-columns: 1fr auto; gap: 10px; align-items: flex-end; margin-bottom: 10px; }
        .output-container { margin-top: 30px; position: relative; }
        #generated-code { width: 100%; min-height: 300px; font-family: 'Courier New', Courier, monospace; font-size: 12px; white-space: pre; background-color: #2d2d2d; color: #a9b7c6; border: 2px solid #000; padding: 10px; box-sizing: border-box; }
        #code-overlay { position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(255, 255, 255, 0.0); z-index: 2; }
        .copy-button-wrapper { position: absolute; top: 15px; right: 15px; z-index: 3; }
        #copy-button { background-color: #DC3623; color: #FFF; text-decoration: none; max-width: 200px; width: 100%; }
        .copyright { font-size: 10px; text-align: center; margin-top: 20px; color: #888; }
        .feedback-message { padding: 10px; margin-top: 15px; font-weight: 600; border: 1px solid; }
        .feedback-success { background-color: #d4edda; border-color: #c3e6cb; color: #155724; }
        .feedback-error { background-color: #f8d7da; border-color: #f5c6cb; color: #721c24; }
        .header-bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; }
        .header-bar > div { display: flex; align-items: center; }
        .logout-btn { background-color: #DC3623; color: #FFF; text-decoration: none; padding: 8px 12px; font-size: 12px; }
        .info-link { color: #FF0000; font-weight: bold; text-decoration: none; cursor: pointer; }
        .collapsible-section > .form-section-title { cursor: pointer; position: relative; padding-right: 25px; }
        .collapsible-section > .form-section-title::after { content: '+'; position: absolute; right: 5px; top: 50%; transform: translateY(-50%); font-size: 20px; font-weight: 600; }
        .collapsible-section.active > .form-section-title::after { content: '\2212'; }
        .collapsible-content { display: none; padding-top: 15px; }
        .collapsible-section.active .collapsible-content { display: block; }
        .file-list { list-style-type: none; padding: 0; }
        .file-list li { display: flex; justify-content: space-between; align-items: center; padding: 5px; border-bottom: 1px solid #eee; }
        .delete-font-btn { background: none; border: none; color: #FF0000; font-weight: bold; cursor: pointer; text-decoration: none; padding: 5px; }

        <?php echo $webfont_css; ?>
    </style>
</head>
<body>
    <?php if (!$is_logged_in): ?>
        <div class="login-wrapper">
            <p style="font-size: 16px; font-weight: 600;">Wechselnde Spr&uuml;che</p>
            <form method="POST" action="">
                <div class="form-group">
                    <label for="password">Passwort</label>
                    <input type="password" id="password" name="password" required>
                </div>
                <?php if (isset($login_error)): ?>
                    <p style="color: #DC3623; font-weight: 600;"><?php echo $login_error; ?></p>
                <?php endif; ?>
                <button type="submit" class="btn btn-login">Login</button>
            </form>
        </div>
    <?php else: ?>
    <div class="container">
        <div class="form-wrapper">
            <div class="header-bar">
                <p style="font-size: 16px; font-weight: 600; margin: 0;">Spruch-Code-Generator</p>
                <div>
                    <a href="readme.html" id="info-link" class="info-link" style="margin-right: 15px;">Wichtige Information</a>
                    <a href="?logout=true" class="btn logout-btn">Logout</a>
                </div>
            </div>
            <p>Konfigurieren Sie hier Ihre zeitabh&auml;ngige Begr&uuml;&szlig;ung mit Spr&uuml;chen, speichern und laden Sie Ihre Konfigurationen.</p>

            <form method="POST" action="" enctype="multipart/form-data">
                <input type="hidden" name="current_filename" value="<?php echo htmlspecialchars($current_file_basename); ?>">

                <div class="form-section" id="file-management">
                    <p class="form-section-title">Konfigurationen verwalten</p>
                    <p style="font-size: 12px;">Hier k&ouml;nnen Sie eine neue Spruchsammlung erstellen oder eine bereits vorhandene Konfiguration aus der Liste ausw&auml;hlen, um sie zu laden, zu bearbeiten oder zu l&ouml;schen.</p>
                    <div class="form-group">
                        <label for="file_selection">Gespeicherte Konfiguration ausw&auml;hlen (Laden / Aktivieren / L&ouml;schen)</label>
                        <div class="file-management-grid">
                            <select name="file_selection" id="file_selection">
                                <?php
                                $json_files = glob($sprueche_ordner . '/*' . $json_suffix);
                                if (empty($json_files)) {
                                    echo '<option value="">-- Keine Konfigurationen gefunden --</option>';
                                } else {
                                    foreach ($json_files as $file) {
                                        $filename = basename($file);
                                        $selected = ($filename == $current_file_basename) ? 'selected' : '';
                                        echo '<option value="' . htmlspecialchars($filename) . '" ' . $selected . '>' . htmlspecialchars($filename) . '</option>';
                                    }
                                }
                                ?>
                            </select>
                            <div class="button-group">
                                <button type="submit" name="load_settings" class="btn btn-load">Laden</button>
                                <button type="submit" name="set_as_current" class="btn btn-save">Als Aktuell festlegen</button>
                                <button type="submit" name="delete_settings" class="btn btn-delete" onclick="return confirm('Sind Sie sicher, dass Sie diese Datei l&ouml;schen wollen?');">L&ouml;schen</button>
                            </div>
                        </div>
                        <?php display_feedback('file-management', $feedback); ?>
                    </div>
                </div>
                             <?php
                             $style_sections = array(
                                 'begruessung' => array('title' => 'Begr&uuml;&szlig;ungstext', 'size' => 14, 'weight' => 500, 'color' => '#333333'),
                                 'spruch' => array('title' => 'wechselnde Spr&uuml;che', 'size' => 14, 'weight' => 500, 'color' => '#555555'),
                                 'autor' => array('title' => 'Quelle / Autor', 'size' => 12, 'weight' => 400, 'color' => '#999999'),
                                 'nachwort' => array('title' => 'Nachwort', 'size' => 14, 'weight' => 500, 'color' => '#777777')
                             );
                             $fonts = array('Arial, sans-serif', 'Verdana, sans-serif', 'Tahoma, sans-serif', 'Courier, monospace', "'Courier New', monospace");
                             $first_style_section = true;
                             ?>

                             <?php foreach ($style_sections as $key => $details): ?>
                             <div class="form-section collapsible-section" <?php if ($first_style_section) { echo 'id="styles-start"'; $first_style_section = false; } ?>>
                                 <p class="form-section-title">Einstellungen f&uuml;r "<?php echo $details['title']; ?>"</p>
                                 <div class="collapsible-content">
                                     <div class="form-grid">
                                         <div class="form-group">
                                             <label>Schriftart</label>
                                             <select name="font_family_<?php echo $key; ?>">
                                                 <?php $selected_font = getFormValue($form_data, "styles.$key.font_family", $fonts[0]); ?>
                                                 <optgroup label="Standard Schriftarten">
                                                     <?php foreach ($fonts as $font): ?>
                                                     <option value="<?php echo htmlspecialchars($font, ENT_QUOTES, 'UTF-8'); ?>" <?php if ($selected_font == $font) echo 'selected'; ?> style="font-family: <?php echo htmlspecialchars($font, ENT_QUOTES, 'UTF-8'); ?>;"><?php echo strtok($font, ','); ?></option>
                                                     <?php endforeach; ?>
                                                 </optgroup>
                                                 <?php if (!empty($webfont_families)): ?>
                                                 <optgroup label="Webfonts">
                                                     <?php foreach ($webfont_families as $font_family): ?>
                                                         <?php $font_value = "'" . str_replace("'", "\'", $font_family) . "'"; ?>
                                                         <option value="<?php echo htmlspecialchars($font_value, ENT_QUOTES, 'UTF-8'); ?>" <?php if ($selected_font == $font_value) echo 'selected'; ?> style="font-family: <?php echo htmlspecialchars($font_value, ENT_QUOTES, 'UTF-8'); ?>;">
                                                             <?php echo htmlspecialchars($font_family); ?>
                                                         </option>
                                                     <?php endforeach; ?>
                                                 </optgroup>
                                                 <?php endif; ?>
                                             </select>
                                         </div>
                                         <div class="form-group">
                                             <label>Schriftgr&ouml;&szlig;e (px)</label>
                                             <input type="number" name="font_size_<?php echo $key; ?>" value="<?php echo getFormValue($form_data, "styles.$key.font_size", $details['size']); ?>" min="8">
                                         </div>
                                         <div class="form-group">
                                             <label>Schriftst&auml;rke</label>
                                             <input type="number" name="font_weight_<?php echo $key; ?>" value="<?php echo getFormValue($form_data, "styles.$key.font_weight", $details['weight']); ?>" step="100" min="100" max="900">
                                         </div>
                                         <div class="form-group">
                                             <label>Farbe</label>
                                             <input type="color" name="color_<?php echo $key; ?>" value="<?php echo getFormValue($form_data, "styles.$key.color", $details['color']); ?>">
                                         </div>
                                         <div class="form-group form-group-checkbox">
                                             <input type="checkbox" id="font_italic_<?php echo $key; ?>" name="font_italic_<?php echo $key; ?>" <?php if (isChecked($form_data, "styles.$key.font_style")) echo 'checked'; ?>>
                                             <label for="font_italic_<?php echo $key; ?>" style="margin-bottom:0;">Kursiv</label>
                                         </div>
                                     </div>
                                 </div>
                             </div>
                             <?php endforeach; ?>

                             <div class="form-section collapsible-section">
                                 <p class="form-section-title">Sammlung der Spr&uuml;che</p>
                                 <div class="collapsible-content">
                                     <div id="sprueche-container">
                                         <?php
                                         $sprueche = getFormValue($form_data, 'sprueche', array(array('text' => '', 'autor' => '')));
                                         foreach ($sprueche as $index => $spruch):
                                         ?>
                                         <div class="spruch-block">
                                             <div class="block-header"><span class="block-title">Spruch #<?php echo $index + 1; ?></span><button type="button" class="btn btn-remove">Entfernen</button></div>
                                             <div class="form-group" style="margin-top: 10px;"><label>Spruch-Text</label><input type="text" name="spruch_text[]" placeholder="Der fr&uuml;he Vogel f&auml;ngt den Wurm" value="<?php echo htmlspecialchars($spruch['text'], ENT_QUOTES, 'UTF-8'); ?>"></div>
                                             <div class="form-group" style="margin-top: 10px;"><label>Quelle / Autor (optional)</label><input type="text" name="spruch_autor[]" placeholder="Deutsches Sprichwort" value="<?php echo htmlspecialchars($spruch['autor'], ENT_QUOTES, 'UTF-8'); ?>"></div>
                                         </div>
                                         <?php endforeach; ?>
                                     </div>
                                     <button type="button" id="add-spruch" class="btn btn-add">Neuen Spruch hinzuf&uuml;gen</button>
                                 </div>
                             </div>

                             <div class="form-section collapsible-section">
                                 <p class="form-section-title">Zeitr&auml;ume und zugeh&ouml;rige Texte</p>
                                 <div class="collapsible-content">
                                     <div id="zeitraeume-container">
                                         <?php
                                         $zeitraeume = getFormValue($form_data, 'zeitraeume', array(array('von' => 0, 'bis' => 23, 'begruessung' => '', 'nachwort' => '')));
                                         foreach ($zeitraeume as $index => $zeitraum):
                                         ?>
                                         <div class="zeitraum-block">
                                             <div class="block-header"><span class="block-title">Zeitraum #<?php echo $index + 1; ?></span><button type="button" class="btn btn-remove">Entfernen</button></div>
                                             <div class="form-grid" style="grid-template-columns: 1fr 1fr;">
                                                 <div class="form-group"><label>Von Stunde (0-23)</label><input type="number" name="von_stunde[]" min="0" max="23" required value="<?php echo $zeitraum['von']; ?>"></div>
                                                 <div class="form-group"><label>Bis Stunde (0-23)</label><input type="number" name="bis_stunde[]" min="0" max="23" required value="<?php echo $zeitraum['bis']; ?>"></div>
                                             </div>
                                             <div class="form-group" style="margin-top: 10px;"><label>Begr&uuml;&szlig;ungstext</label><input type="text" name="begruessung[]" placeholder="z.B. Guten Morgen" value="<?php echo htmlspecialchars($zeitraum['begruessung'], ENT_QUOTES, 'UTF-8'); ?>"></div>
                                             <div class="form-group" style="margin-top: 10px;"><label>Nachwort</label><input type="text" name="nachwort[]" placeholder="z.B. Wir w&uuml;nschen einen sch&ouml;nen Tag" value="<?php echo htmlspecialchars($zeitraum['nachwort'], ENT_QUOTES, 'UTF-8'); ?>"></div>
                                         </div>
                                         <?php endforeach; ?>
                                     </div>
                                     <button type="button" id="add-zeitraum" class="btn btn-add">Neuen Zeitraum hinzuf&uuml;gen</button>
                                 </div>
                             </div>

                             <div class="form-section collapsible-section" id="webfonts-management">
                                 <p class="form-section-title">Webfonts verwalten</p>
                                 <div class="collapsible-content">
                                     <p style="font-size: 12px;">Laden Sie hier Ihre Webfont-Dateien hoch (.eot, .otf, .woff, .woff2, .svg, .ttf). Die Schriftarten werden automatisch nach Familiennamen gruppiert und stehen oben in den Style-Einstellungen zur Verf&uuml;gung.</p>
                                     <div class="form-group">
                                         <label for="webfont_upload">Neue Webfont-Datei hochladen</label>
                                         <div class="file-management-grid">
                                             <input type="file" name="webfont" id="webfont_upload" style="border: 2px solid #000; padding: 5px;">
                                             <button type="submit" name="upload_font" class="btn btn-add">Hochladen</button>
                                         </div>
                                         <?php display_feedback('webfonts-management', $feedback); ?>
                                     </div>
                                     <hr style="margin: 20px 0;">
                                     <p style="font-weight: 600;">Hochgeladene Fonts:</p>
                                     <?php
                                     $uploaded_fonts = glob($webfonts_ordner . '/*');
                                     if (is_array($uploaded_fonts) && !empty($uploaded_fonts)) {
                                         echo '<ul class="file-list">';
                                         foreach ($uploaded_fonts as $font) {
                                             echo '<li>';
                                             echo '<span>' . htmlspecialchars(basename($font)) . '</span>';
                                             echo '<button type="submit" name="delete_font" value="' . htmlspecialchars(basename($font)) . '" class="delete-font-btn" title="Font-Datei l&ouml;schen" onclick="return confirm(\'Sind Sie sicher, dass Sie diese Font-Datei l&ouml;schen wollen?\');">L&ouml;schen</button>';
                                             echo '</li>';
                                         }
                                         echo '</ul>';
                                     } else {
                                         echo '<p style="font-size:12px;">Noch keine Webfonts hochgeladen.</p>';
                                     }
                                     ?>
                                 </div>
                             </div>

                             <div class="form-section">
                                 <p class="form-section-title">Aktuelle Konfiguration speichern</p>
                                 <div class="form-group" id="save-changes">
                                      <label>&Auml;nderungen in der geladenen Datei '<?php echo htmlspecialchars($current_file_basename); ?>' speichern</label>
                                      <button type="submit" name="save_changes" class="btn btn-save" <?php if(empty($current_file_basename)) echo 'disabled'; ?>>&Auml;nderungen speichern</button>
                                      <?php display_feedback('save-changes', $feedback); ?>
                                 </div>
                                 <div class="form-group" style="margin-top: 20px;">
                                     <label>Neue, leere Konfiguration beginnen</label>
                                     <a href="<?php echo basename(__FILE__); ?>#styles-start" class="btn btn-add" style="text-align: center;">Neue Spr&uuml;chesammlung erstellen</a>
                                 </div>
                                 <div class="form-group" style="margin-top: 20px;" id="save-as-new">
                                     <label for="filename">Als neue Konfiguration /Spruchsammlung speichern <span style="font-size:12px; font-weight:500;"><br>(Eine als <strong>AKTUELL</strong> festgelegte Datei wird live angezeigt.)</span></label>
                                     <div class="file-management-grid">
                                         <input type="text" name="filename" id="filename" placeholder="Neuer Dateiname...">
                                         <button type="submit" name="save_as_new" class="btn btn-save">Speichern (Server)</button>
                                     </div>
                                     <small style="font-size: 12px;">Nur Buchstaben, Zahlen, - und _ sind erlaubt. Der Suffix '<?php echo $json_suffix; ?>' wird automatisch angeh&auml;ngt.</small>
                                     <?php display_feedback('save-as-new', $feedback); ?>
                                 </div>
                             </div>

                             <div class="form-section">
                                 <p class="form-section-title">Gespeicherte Konfiguration herunterladen</p>
                                 <div class="form-group">
                                     <label for="file_to_download">Konfigurationsdatei ausw&auml;hlen</label>
                                     <div class="file-management-grid">
                                         <select name="file_to_download" id="file_to_download">
                                             <?php
                                             if (empty($json_files)) {
                                                 echo '<option value="">-- Keine Konfigurationen gefunden --</option>';
                                             } else {
                                                 foreach ($json_files as $file) {
                                                     $filename = basename($file);
                                                     echo '<option value="' . htmlspecialchars($filename) . '">' . htmlspecialchars($filename) . '</option>';
                                                 }
                                             }
                                             ?>
                                         </select>
                                         <div class="button-group">
                                             <button type="submit" name="download_json" class="btn btn-download">JSON-Datei herunterladen</button>
                                         </div>
                                     </div>
                                 </div>
                             </div>

                             <div class="form-section" id="generate-code">
                                 <p class="form-section-title">Code generieren &amp; herunterladen</p>
                                 <div class="button-group">
                                     <button type="submit" name="generate_code" class="btn btn-generate">Code generieren</button>
                                     <button type="button" id="preview-button" class="btn btn-preview" <?php if (empty($generated_code)) echo 'disabled'; ?>>Vorschau</button>
                                     <button type="submit" name="download_code" class="btn btn-download">Code als .txt herunterladen</button>
                                 </div>
                                 <?php display_feedback('generate-code', $feedback); ?>
                             </div>
                         </form>

                         <?php if (!empty($generated_code)): ?>
                         <div class="output-container">
                             <p class="form-section-title">Ihr generierter Code</p>
                             <p style="font-size: 12px;">F&uuml;gen Sie diesen Code an der Stelle in Ihre Webseite ein, an der die Begr&uuml;&szlig;ung erscheinen soll.</p>
                             <div class="copy-button-wrapper"><button id="copy-button" class="btn">Code in die Zwischenablage kopieren</button></div>
                             <div id="code-overlay"></div>
                             <textarea id="generated-code" readonly><?php echo htmlspecialchars($generated_code, ENT_QUOTES, 'UTF-8'); ?></textarea>
                         </div>
                         <?php endif; ?>
                     </div>
                     <p class="copyright">copyright &copy; sgs-visual.de 2025</p>
                 </div>

                 <script>
                 document.addEventListener('DOMContentLoaded', function() {

                     // --- Popup Logic ---
                     function openPopup(url, title, w, h) {
                         var left = (screen.width/2)-(w/2);
                         var top = (screen.height/2)-(h/2);
                         return window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
                     }

                     var infoLink = document.getElementById('info-link');
                     if (infoLink) {
                         infoLink.addEventListener('click', function(e) {
                             e.preventDefault();
                             openPopup(this.href, 'Rechtliche Informationen', 600, 400);
                         });
                     }

                     var previewButton = document.getElementById('preview-button');
                     if (previewButton) {
                         previewButton.addEventListener('click', function() {
                             if (this.disabled) { return; }
                             var generatedCodeEl = document.getElementById('generated-code');
                             if (generatedCodeEl && generatedCodeEl.value) {
                                 var generatedCode = generatedCodeEl.value;
                                 var previewWindow = openPopup('', 'Vorschau', 360, 200);
                                 if(previewWindow) {
                                     previewWindow.document.open();
                                     previewWindow.document.write('<!DOCTYPE html><html lang="de"><head><meta charset="UTF-8"><title>Vorschau</title></head><body>' + generatedCode + '</body></html>');
                                     previewWindow.document.close();
                                 }
                             }
                         });
                     }

                     var zeitraumContainer = document.getElementById('zeitraeume-container');
                     if(zeitraumContainer) {
                         document.getElementById('add-zeitraum').addEventListener('click', function() {
                             var index = zeitraumContainer.children.length;
                             var block = document.createElement('div');
                             block.className = 'zeitraum-block';
                             block.innerHTML = `<div class="block-header"><span class="block-title">Zeitraum #${index + 1}</span><button type="button" class="btn btn-remove">Entfernen</button></div><div class="form-grid" style="grid-template-columns: 1fr 1fr;"><div class="form-group"><label>Von Stunde (0-23)</label><input type="number" name="von_stunde[]" min="0" max="23" required></div><div class="form-group"><label>Bis Stunde (0-23)</label><input type="number" name="bis_stunde[]" min="0" max="23" required></div></div><div class="form-group" style="margin-top: 10px;"><label>Begr&uuml;&szlig;ungstext</label><input type="text" name="begruessung[]" placeholder="z.B. Guten Morgen"></div><div class="form-group" style="margin-top: 10px;"><label>Nachwort</label><input type="text" name="nachwort[]" placeholder="z.B. Wir w&uuml;nschen einen sch&ouml;nen Tag"></div>`;
                             zeitraumContainer.appendChild(block);
                         });
                         zeitraumContainer.addEventListener('click', function(e) { if (e.target.classList.contains('btn-remove')) { e.target.closest('.zeitraum-block').remove(); } });
                     }

                     var spruchContainer = document.getElementById('sprueche-container');
                     if(spruchContainer) {
                         document.getElementById('add-spruch').addEventListener('click', function() {
                             var index = spruchContainer.children.length;
                             var block = document.createElement('div');
                             block.className = 'spruch-block';
                             block.innerHTML = `<div class="block-header"><span class="block-title">Spruch #${index + 1}</span><button type="button" class="btn btn-remove">Entfernen</button></div><div class="form-group" style="margin-top: 10px;"><label>Spruch-Text</label><input type="text" name="spruch_text[]" placeholder="Der fr&uuml;he Vogel f&auml;ngt den Wurm"></div><div class="form-group" style="margin-top: 10px;"><label>Quelle / Autor (optional)</label><input type="text" name="spruch_autor[]" placeholder="Deutsches Sprichwort"></div>`;
                             spruchContainer.appendChild(block);
                         });
                         spruchContainer.addEventListener('click', function(e) { if (e.target.classList.contains('btn-remove')) { e.target.closest('.spruch-block').remove(); } });
                     }

                     var accordionSections = document.querySelectorAll('.collapsible-section');
                     accordionSections.forEach(function(section) {
                         var title = section.querySelector('.form-section-title');
                         if (title) {
                             title.addEventListener('click', function() {
                                 section.classList.toggle('active');
                             });
                         }
                     });

                     var copyButton = document.getElementById('copy-button');
                     if (copyButton) {
                         copyButton.addEventListener('click', function() {
                             var codeTextarea = document.getElementById('generated-code');
                             navigator.clipboard.writeText(codeTextarea.value).then(function() {
                                 copyButton.textContent = 'Erfolgreich kopiert!';
                                 setTimeout(function() {
                                     copyButton.textContent = 'Code in die Zwischenablage kopieren';
                                 }, 2000);
                             }, function(err) {
                                 copyButton.textContent = 'Kopieren fehlgeschlagen!';
                             });
                         });
                     }

                     var feedbackData = <?php echo json_encode($feedback); ?>;
                     if (feedbackData && feedbackData.context) {
                         var feedbackElement = document.getElementById('feedback-' + feedbackData.context);
                         if (feedbackElement) {
                             var collapsibleParent = feedbackElement.closest('.collapsible-section');
                             if (collapsibleParent && !collapsibleParent.classList.contains('active')) {
                                 collapsibleParent.classList.add('active');
                             }
                             feedbackElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
                         }
                     }

                     var loginSuccess = <?php echo $login_success ? 'true' : 'false'; ?>;
                     if (loginSuccess) {
                         window.scrollTo(0, 0);
                     }

                     <?php if (!empty($generated_code) && isset($feedback['context']) && $feedback['context'] === 'generate-code'): ?>
                     document.querySelector('.output-container').scrollIntoView({ behavior: 'smooth' });
                     <?php endif; ?>
                 });
                 </script>
                 <?php endif; ?>
             </body>
             </html>
