<?php
/**
 * WP Multi – Modul: Login-Design
 *
 * Ermöglicht die eigene Gestaltung der WordPress-Login-Seite:
 * Logo, Hintergrund (Farbe/Bild), Formular-Farbe, Button- und Linkfarbe
 * sowie eigenes CSS. Wird über den Loader in wp-multi.php eingebunden.
 */

if (!defined('ABSPATH')) { exit; }

/*
 * Einstellungen registrieren
 */
function wp_multi_login_design_register() {
    $group = 'wp_multi_login_design_group';
    register_setting($group, 'wp_multi_login_form_text',  ['sanitize_callback' => 'sanitize_hex_color', 'default' => '']);
    register_setting($group, 'wp_multi_login_logo',       ['sanitize_callback' => 'esc_url_raw', 'default' => '']);
    register_setting($group, 'wp_multi_login_logo_home',  ['sanitize_callback' => 'absint', 'default' => 1]);
    register_setting($group, 'wp_multi_login_bg_color',   ['sanitize_callback' => 'sanitize_hex_color', 'default' => '']);
    register_setting($group, 'wp_multi_login_bg_image',   ['sanitize_callback' => 'esc_url_raw', 'default' => '']);
    register_setting($group, 'wp_multi_login_bg_size',    ['sanitize_callback' => 'wp_multi_login_design_sanitize_bg_size', 'default' => 'cover']);
    register_setting($group, 'wp_multi_login_form_bg',    ['sanitize_callback' => 'sanitize_hex_color', 'default' => '']);
    register_setting($group, 'wp_multi_login_button',     ['sanitize_callback' => 'sanitize_hex_color', 'default' => '']);
    register_setting($group, 'wp_multi_login_link',       ['sanitize_callback' => 'sanitize_hex_color', 'default' => '']);
    register_setting($group, 'wp_multi_login_custom_css', ['sanitize_callback' => 'wp_multi_login_design_sanitize_css', 'default' => '']);
}
add_action('admin_init', 'wp_multi_login_design_register');

// Eigenes CSS grob absichern (kein </style>-Ausbruch, keine Tags)
function wp_multi_login_design_sanitize_css($css) {
    $css = (string) $css;
    $css = wp_strip_all_tags($css);
    return trim($css);
}

// Anzeige-Art des Hintergrundbilds (Whitelist)
function wp_multi_login_design_sanitize_bg_size($value) {
    $allowed = array('cover', 'contain', 'stretch', 'tile', 'center');
    return in_array($value, $allowed, true) ? $value : 'cover';
}

// Liefert die CSS-Regeln für die gewählte Hintergrund-Anzeigeart
function wp_multi_login_design_bg_rules($mode) {
    switch ($mode) {
        case 'contain':
            return 'background-size:contain !important; background-repeat:no-repeat !important; background-position:center !important;';
        case 'stretch':
            return 'background-size:100% 100% !important; background-repeat:no-repeat !important; background-position:center !important;';
        case 'tile':
            return 'background-size:auto !important; background-repeat:repeat !important;';
        case 'center':
            return 'background-size:auto !important; background-repeat:no-repeat !important; background-position:center !important;';
        case 'cover':
        default:
            return 'background-size:cover !important; background-repeat:no-repeat !important; background-position:center !important;';
    }
}

/*
 * Ausgabe auf der Login-Seite
 */
function wp_multi_login_design_styles() {
    $form_text = get_option('wp_multi_login_form_text', '');
    $logo      = get_option('wp_multi_login_logo', '');
    $bg_color  = get_option('wp_multi_login_bg_color', '');
    $bg_image  = get_option('wp_multi_login_bg_image', '');
    $form_bg   = get_option('wp_multi_login_form_bg', '');
    $button    = get_option('wp_multi_login_button', '');
    $link      = get_option('wp_multi_login_link', '');
    $css       = get_option('wp_multi_login_custom_css', '');

    // Nur ausgeben, wenn überhaupt etwas konfiguriert ist
    if (!$logo && !$bg_color && !$bg_image && !$form_bg && !$button && !$link && !$css && !$form_text) {
        return;
    }

    echo "<style id=\"wp-multi-login-design\">\n";

    if ($logo) {
        printf(
            "#login h1 a, .login h1 a { background-image:url(%s) !important; background-size:contain !important; background-position:center !important; width:auto !important; height:90px !important; }\n",
            esc_url($logo)
        );
    }
    if ($bg_color) {
        printf("body.login { background-color:%s !important; }\n", esc_attr($bg_color));
    }
    if ($bg_image) {
        $bg_size = get_option('wp_multi_login_bg_size', 'cover');
        printf(
            "body.login { background-image:url(%s) !important; %s }\n",
            esc_url($bg_image),
            wp_multi_login_design_bg_rules($bg_size)
        );
    }
    if ($form_bg) {
        printf(".login form { background:%s !important; border-radius:8px !important; }\n", esc_attr($form_bg));
    }
    if ($button) {
        printf(".login .button-primary { background:%1\$s !important; border-color:%1\$s !important; box-shadow:none !important; text-shadow:none !important; }\n", esc_attr($button));
    }
    if ($link) {
        printf(".login #nav a, .login #backtoblog a, .login .wp-login-lost-password a { color:%s !important; }\n", esc_attr($link));
    }
    if ($form_text) {
        printf(".login form label, .login form .forgetmenot label { color:%s !important; }\n", esc_attr($form_text));
    }

    if ($css) {
        // bereits beim Speichern von Tags befreit
        echo $css . "\n";
    }

    echo "</style>\n";
}
add_action('login_enqueue_scripts', 'wp_multi_login_design_styles');

// Logo-Link auf die eigene Startseite statt wordpress.org
function wp_multi_login_design_headerurl($url) {
    return get_option('wp_multi_login_logo_home', 1) ? home_url('/') : $url;
}
add_filter('login_headerurl', 'wp_multi_login_design_headerurl');

// Logo-Titel = Seitenname
function wp_multi_login_design_headertext($text) {
    return get_option('wp_multi_login_logo_home', 1) ? get_bloginfo('name') : $text;
}
add_filter('login_headertext', 'wp_multi_login_design_headertext');

/*
 * Assets für die Einstellungsseite (Color-Picker + Medienauswahl)
 */
function wp_multi_login_design_admin_assets($hook) {
    if ($hook !== 'wp-multi_page_wp_multi_login_design' && $hook !== 'toplevel_page_wp_multi_login_design') {
        return;
    }
    wp_enqueue_style('wp-color-picker');
    wp_enqueue_script('wp-color-picker');
    wp_enqueue_media();
}
add_action('admin_enqueue_scripts', 'wp_multi_login_design_admin_assets');

/*
 * Einstellungsseite
 */
function wp_multi_login_design_page() {
    if (!current_user_can('manage_options')) {
        wp_die(__('Zugriff verweigert.', 'wp-multi'));
    }

    wpmt_admin_page_open(
        __('Login-Design', 'wp-multi'),
        __('Die WordPress-Login-Seite nach deinen Wünschen gestalten', 'wp-multi')
    );

    $logo     = get_option('wp_multi_login_logo', '');
    $bg_image = get_option('wp_multi_login_bg_image', '');

    wpmt_admin_notice('info', sprintf(
        __('Vorschau: %s (in neuem Tab öffnen – als eingeloggter Nutzer wirst du ggf. direkt weitergeleitet, dann kurz ausloggen).', 'wp-multi'),
        '<a href="' . esc_url(wp_login_url()) . '" target="_blank">' . esc_html(wp_login_url()) . '</a>'
    ));

    wpmt_admin_card_open(__('Gestaltung', 'wp-multi'));
    ?>
    <form method="post" action="options.php">
        <?php settings_fields('wp_multi_login_design_group'); ?>

        <div class="wpm-field">
            <label class="wpm-field__label"><?php esc_html_e('Logo', 'wp-multi'); ?>
                <small class="wpm-field__hint"><?php esc_html_e('Ersetzt das WordPress-Logo über dem Formular.', 'wp-multi'); ?></small>
            </label>
            <div>
                <input type="text" id="wp_multi_login_logo" name="wp_multi_login_logo" value="<?php echo esc_attr($logo); ?>" placeholder="https://…/logo.png" style="max-width:420px;">
                <button type="button" class="wpm-btn wpm-media-btn" data-target="wp_multi_login_logo"><?php esc_html_e('Medien', 'wp-multi'); ?></button>
                <div class="wpm-preview"><?php if ($logo) echo '<img src="' . esc_url($logo) . '" style="max-height:60px;margin-top:8px;">'; ?></div>
            </div>
        </div>

        <div class="wpm-field">
            <label class="wpm-field__label"><?php esc_html_e('Logo verlinkt zur Startseite', 'wp-multi'); ?></label>
            <div><label><input type="checkbox" name="wp_multi_login_logo_home" value="1" <?php checked(1, get_option('wp_multi_login_logo_home', 1)); ?>> <?php esc_html_e('Ja (statt zu wordpress.org)', 'wp-multi'); ?></label></div>
        </div>

        <div class="wpm-field">
            <label class="wpm-field__label"><?php esc_html_e('Seiten-Hintergrundfarbe', 'wp-multi'); ?></label>
            <div><input type="text" class="wpm-color" name="wp_multi_login_bg_color" value="<?php echo esc_attr(get_option('wp_multi_login_bg_color', '')); ?>" data-default-color=""></div>
        </div>

        <div class="wpm-field">
            <label class="wpm-field__label"><?php esc_html_e('Hintergrundbild', 'wp-multi'); ?>
                <small class="wpm-field__hint"><?php esc_html_e('Optional. Überlagert die Hintergrundfarbe.', 'wp-multi'); ?></small>
            </label>
            <div>
                <input type="text" id="wp_multi_login_bg_image" name="wp_multi_login_bg_image" value="<?php echo esc_attr($bg_image); ?>" placeholder="https://…/bg.jpg" style="max-width:420px;">
                <button type="button" class="wpm-btn wpm-media-btn" data-target="wp_multi_login_bg_image"><?php esc_html_e('Medien', 'wp-multi'); ?></button>
            </div>
        </div>

        <div class="wpm-field">
            <label class="wpm-field__label"><?php esc_html_e('Hintergrundbild-Anzeige', 'wp-multi'); ?>
                <small class="wpm-field__hint"><?php esc_html_e('Wie das Bild die Login-Seite füllt.', 'wp-multi'); ?></small>
            </label>
            <div>
                <?php $bg_size = get_option('wp_multi_login_bg_size', 'cover'); ?>
                <select name="wp_multi_login_bg_size" style="max-width:280px;">
                    <option value="cover" <?php selected($bg_size, 'cover'); ?>><?php esc_html_e('Ausfüllen (beschneidet ggf.)', 'wp-multi'); ?></option>
                    <option value="contain" <?php selected($bg_size, 'contain'); ?>><?php esc_html_e('Anpassen (ganz sichtbar)', 'wp-multi'); ?></option>
                    <option value="stretch" <?php selected($bg_size, 'stretch'); ?>><?php esc_html_e('Strecken (exakt füllen)', 'wp-multi'); ?></option>
                    <option value="tile" <?php selected($bg_size, 'tile'); ?>><?php esc_html_e('Kacheln (wiederholen)', 'wp-multi'); ?></option>
                    <option value="center" <?php selected($bg_size, 'center'); ?>><?php esc_html_e('Zentriert (Originalgröße)', 'wp-multi'); ?></option>
                </select>
            </div>
        </div>

        <div class="wpm-field">
            <label class="wpm-field__label"><?php esc_html_e('Formular-Hintergrund', 'wp-multi'); ?></label>
            <div><input type="text" class="wpm-color" name="wp_multi_login_form_bg" value="<?php echo esc_attr(get_option('wp_multi_login_form_bg', '')); ?>" data-default-color=""></div>
        </div>

        <div class="wpm-field">
            <label class="wpm-field__label"><?php esc_html_e('Formular-Textfarbe', 'wp-multi'); ?>
                <small class="wpm-field__hint"><?php esc_html_e('Farbe der Beschriftungen im Formular (z. B. hell auf dunklem Formular-Hintergrund).', 'wp-multi'); ?></small>
            </label>
            <div><input type="text" class="wpm-color" name="wp_multi_login_form_text" value="<?php echo esc_attr(get_option('wp_multi_login_form_text', '')); ?>" data-default-color=""></div>
        </div>

        <div class="wpm-field">
            <label class="wpm-field__label"><?php esc_html_e('Button-Farbe', 'wp-multi'); ?></label>
            <div><input type="text" class="wpm-color" name="wp_multi_login_button" value="<?php echo esc_attr(get_option('wp_multi_login_button', '')); ?>" data-default-color=""></div>
        </div>

        <div class="wpm-field">
            <label class="wpm-field__label"><?php esc_html_e('Link-Farbe', 'wp-multi'); ?></label>
            <div><input type="text" class="wpm-color" name="wp_multi_login_link" value="<?php echo esc_attr(get_option('wp_multi_login_link', '')); ?>" data-default-color=""></div>
        </div>

        <div class="wpm-field">
            <label class="wpm-field__label"><?php esc_html_e('Eigenes CSS (Profi)', 'wp-multi'); ?>
                <small class="wpm-field__hint"><?php esc_html_e('Wird zusätzlich auf der Login-Seite ausgegeben.', 'wp-multi'); ?></small>
            </label>
            <div><textarea name="wp_multi_login_custom_css" rows="6" style="width:100%;max-width:560px;font-family:monospace;"><?php echo esc_textarea(get_option('wp_multi_login_custom_css', '')); ?></textarea></div>
        </div>

        <?php submit_button(__('Speichern', 'wp-multi')); ?>
    </form>

    <script>
    jQuery(function ($) {
        // Farbwähler
        if ($.fn.wpColorPicker) { $('.wpm-color').wpColorPicker(); }
        // Medienauswahl
        $('.wpm-media-btn').on('click', function (e) {
            e.preventDefault();
            var targetId = $(this).data('target');
            var frame = wp.media({ title: '<?php echo esc_js(__('Bild auswählen', 'wp-multi')); ?>', multiple: false });
            frame.on('select', function () {
                var att = frame.state().get('selection').first().toJSON();
                $('#' + targetId).val(att.url);
                if (targetId === 'wp_multi_login_logo') {
                    $('.wpm-preview').html('<img src="' + att.url + '" style="max-height:60px;margin-top:8px;">');
                }
            });
            frame.open();
        });
    });
    </script>
    <?php
    wpmt_admin_card_close();

    wpmt_admin_page_close();
}
