<?php
/**
 * WP Multi – Modul: Gast-Lesezeichen
 *
 * Automatisch aus wp-multi.php ausgelagert. Wird über den Loader in
 * wp-multi.php eingebunden (nur wenn das WP Multi Toolkit aktiv ist).
 */

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

/*
 * Verbessertes Gast-Lesezeichen-Plugin mit erhöhter Sicherheit und Benutzerfreundlichkeit
 */


define('STATISTIK_MANAGER_BOOKMARK_POST_TYPE', 'bookmark');
define('STATISTIK_MANAGER_COOKIE_NAME', 'guest_token');
define('STATISTIK_MANAGER_COOKIE_DURATION', 30 * DAY_IN_SECONDS);
define('STATISTIK_MANAGER_BOOKMARKS_CACHE_KEY', 'statistik_manager_bookmarks_');

/**
 * Erstellt den benutzerdefinierten Post-Typ für Lesezeichen.
 */
function statistik_manager_create_bookmark_post_type() {
    register_post_type(STATISTIK_MANAGER_BOOKMARK_POST_TYPE, [
        'labels' => [
            'name' => __('Lesezeichen', 'statistik-manager'),
            'singular_name' => __('Lesezeichen', 'statistik-manager'),
        ],
        'public' => false,
        'show_ui' => false,
        'show_in_menu' => false,
        'supports' => ['title', 'custom-fields'],
    ]);
}
add_action('init', 'statistik_manager_create_bookmark_post_type');

/**
 * Generiert oder holt den Gast-Token.
 *
 * @return string Der Gast-Token.
 */
function statistik_manager_get_guest_token() {
    $guest_token = isset($_COOKIE[STATISTIK_MANAGER_COOKIE_NAME]) ? sanitize_text_field($_COOKIE[STATISTIK_MANAGER_COOKIE_NAME]) : null;

    if (!$guest_token) {
        $guest_token = wp_generate_uuid4();
        setcookie(
            STATISTIK_MANAGER_COOKIE_NAME,
            $guest_token,
            time() + STATISTIK_MANAGER_COOKIE_DURATION,
            COOKIEPATH,
            COOKIE_DOMAIN,
            is_ssl(), // Secure
            true // HttpOnly
        );
    }

    return $guest_token;
}

/**
 * Speichert ein Lesezeichen für einen Gast.
 *
 * @param int $post_id Post-ID des Lesezeichens.
 */
function statistik_manager_save_bookmark($post_id) {
    $guest_token = statistik_manager_get_guest_token();
    update_post_meta($post_id, '_guest_token', $guest_token);
}

/**
 * Ruft die Lesezeichen eines Gastes ab.
 *
 * @return array Liste der Lesezeichen.
 */
function statistik_manager_get_guest_bookmarks() {
    $guest_token = statistik_manager_get_guest_token();
    $cache_key = STATISTIK_MANAGER_BOOKMARKS_CACHE_KEY . md5($guest_token);
    $bookmarks = get_transient($cache_key);

    if ($bookmarks !== false) {
        return $bookmarks;
    }

    $args = [
        'post_type' => STATISTIK_MANAGER_BOOKMARK_POST_TYPE,
        'meta_query' => [
            [
                'key' => '_guest_token',
                'value' => $guest_token,
            ],
        ],
        'posts_per_page' => -1,
        'post_status' => 'publish',
        'orderby' => 'date',
        'order' => 'DESC',
    ];

    $bookmarks_query = new WP_Query($args);
    $bookmarks = $bookmarks_query->posts;

    set_transient($cache_key, $bookmarks, HOUR_IN_SECONDS);
    return $bookmarks;
}

/**
 * Löscht ein Lesezeichen via AJAX.
 */
function statistik_manager_delete_bookmark() {
    check_ajax_referer('statistik_manager_bookmark_nonce', 'nonce');

    if (!isset($_POST['bookmark_id']) || !isset($_COOKIE[STATISTIK_MANAGER_COOKIE_NAME])) {
        wp_send_json_error(['message' => __('Ungültige Anfrage.', 'statistik-manager')]);
    }

    $bookmark_id = absint($_POST['bookmark_id']);
    $guest_token = sanitize_text_field($_COOKIE[STATISTIK_MANAGER_COOKIE_NAME]);
    $stored_token = get_post_meta($bookmark_id, '_guest_token', true);

    if ($stored_token !== $guest_token) {
        wp_send_json_error(['message' => __('Du kannst nur deine eigenen Lesezeichen löschen.', 'statistik-manager')]);
    }

    wp_delete_post($bookmark_id, true);
    delete_transient(STATISTIK_MANAGER_BOOKMARKS_CACHE_KEY . md5($guest_token));
    wp_send_json_success(['message' => __('Lesezeichen erfolgreich gelöscht.', 'statistik-manager')]);
}
add_action('wp_ajax_delete_bookmark', 'statistik_manager_delete_bookmark');
add_action('wp_ajax_nopriv_delete_bookmark', 'statistik_manager_delete_bookmark');

/**
 * Fügt ein Lesezeichen via AJAX hinzu.
 */
function statistik_manager_add_bookmark_ajax() {
    check_ajax_referer('statistik_manager_bookmark_nonce', 'nonce');

    if (!isset($_POST['bookmark_url']) || !isset($_POST['bookmark_name'])) {
        wp_send_json_error(['message' => __('Bitte alle Felder ausfüllen.', 'statistik-manager')]);
    }

    $bookmark_url = esc_url_raw($_POST['bookmark_url']);
    $bookmark_name = sanitize_text_field($_POST['bookmark_name']);

    if (empty($bookmark_url) || empty($bookmark_name)) {
        wp_send_json_error(['message' => __('Ungültige URL oder Name.', 'statistik-manager')]);
    }

    // Prüfen, ob die URL bereits existiert
    $guest_token = statistik_manager_get_guest_token();
    $args = [
        'post_type' => STATISTIK_MANAGER_BOOKMARK_POST_TYPE,
        'meta_query' => [
            'relation' => 'AND',
            [
                'key' => '_guest_token',
                'value' => $guest_token,
            ],
            [
                'key' => '_bookmark_url',
                'value' => $bookmark_url,
            ],
        ],
        'posts_per_page' => 1,
    ];

    $existing = new WP_Query($args);
    if ($existing->have_posts()) {
        wp_send_json_error(['message' => __('Diese URL ist bereits ein Lesezeichen.', 'statistik-manager')]);
    }

    // Neues Lesezeichen erstellen
    $post_id = wp_insert_post([
        'post_type' => STATISTIK_MANAGER_BOOKMARK_POST_TYPE,
        'post_title' => $bookmark_name,
        'post_status' => 'publish',
        'meta_input' => [
            '_bookmark_url' => $bookmark_url,
            '_guest_token' => $guest_token,
        ],
    ]);

    if (is_wp_error($post_id)) {
        wp_send_json_error(['message' => __('Fehler beim Hinzufügen des Lesezeichens.', 'statistik-manager')]);
    }

    delete_transient(STATISTIK_MANAGER_BOOKMARKS_CACHE_KEY . md5($guest_token));
    wp_send_json_success([
        'message' => __('Lesezeichen erfolgreich hinzugefügt.', 'statistik-manager'),
        'html' => '<li><button class="delete-bookmark-btn" data-bookmark-id="' . esc_attr($post_id) . '">' . esc_html__('Löschen', 'statistik-manager') . '</button><a href="' . esc_url($bookmark_url) . '" target="_blank">' . esc_html($bookmark_name) . '</a></li>',
    ]);
}
add_action('wp_ajax_add_bookmark', 'statistik_manager_add_bookmark_ajax');
add_action('wp_ajax_nopriv_add_bookmark', 'statistik_manager_add_bookmark_ajax');

/**
 * Zeigt die Lesezeichen eines Gastes an.
 *
 * @return string HTML-Ausgabe der Lesezeichen.
 */
function statistik_manager_display_bookmarks() {
    $bookmarks = statistik_manager_get_guest_bookmarks();

    ob_start();
    ?>
    <div class="statistik-manager-bookmarks">
        <h3><?php esc_html_e('Gespeicherte Lesezeichen', 'statistik-manager'); ?></h3>
        <?php if (empty($bookmarks)) : ?>
            <p><?php esc_html_e('Keine Lesezeichen gefunden.', 'statistik-manager'); ?></p>
        <?php else : ?>
            <ul>
                <?php foreach ($bookmarks as $bookmark) : ?>
                    <li>
                        <button class="delete-bookmark-btn" data-bookmark-id="<?php echo esc_attr($bookmark->ID); ?>">
                            <?php esc_html_e('Löschen', 'statistik-manager'); ?>
                        </button>
                        <a href="<?php echo esc_url(get_post_meta($bookmark->ID, '_bookmark_url', true)); ?>" target="_blank">
                            <?php echo esc_html(get_the_title($bookmark)); ?>
                        </a>
                    </li>
                <?php endforeach; ?>
            </ul>
        <?php endif; ?>
    </div>
    <?php
    return ob_get_clean();
}

/**
 * Shortcode zum Anzeigen der Lesezeichen.
 *
 * @return string HTML-Ausgabe.
 */
function statistik_manager_bookmarks_shortcode() {
    return statistik_manager_display_bookmarks();
}
add_shortcode('display_bookmarks', 'statistik_manager_bookmarks_shortcode');

/**
 * Shortcode zum Hinzufügen eines Lesezeichens.
 *
 * @return string HTML-Ausgabe.
 */
function statistik_manager_add_bookmark_shortcode() {
    ob_start();
    ?>
    <form id="add-bookmark-form" class="statistik-manager-bookmark-form">
        <input type="hidden" name="nonce" value="<?php echo esc_attr(wp_create_nonce('statistik_manager_bookmark_nonce')); ?>">
        <div class="form-field">
            <label for="bookmark_name"><?php esc_html_e('Name des Lesezeichens:', 'statistik-manager'); ?></label>
            <input type="text" name="bookmark_name" id="bookmark_name" required>
        </div>
        <div class="form-field">
            <label for="bookmark_url"><?php esc_html_e('URL des Lesezeichens:', 'statistik-manager'); ?></label>
            <input type="url" name="bookmark_url" id="bookmark_url" required>
        </div>
        <div class="form-field">
            <button type="submit"><?php esc_html_e('Lesezeichen hinzufügen', 'statistik-manager'); ?></button>
        </div>
        <div class="form-message"></div>
    </form>
    <style>
        .statistik-manager-bookmark-form { max-width: 500px; margin: 20px 0; }
        .statistik-manager-bookmark-form .form-field { margin-bottom: 15px; }
        .statistik-manager-bookmark-form label { display: block; margin-bottom: 5px; font-weight: bold; }
        .statistik-manager-bookmark-form input { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; }
        .statistik-manager-bookmark-form button { background-color: #0073aa; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; }
        .statistik-manager-bookmark-form button:hover { background-color: #005177; }
        .statistik-manager-bookmark-form .form-message { margin-top: 10px; color: green; }
        .statistik-manager-bookmark-form .form-message.error { color: red; }
        .statistik-manager-bookmarks ul { list-style: none; padding: 0; }
        .statistik-manager-bookmarks li { margin-bottom: 10px; display: flex; align-items: center; }
        .statistik-manager-bookmarks button { margin-right: 10px; background-color: #d63638; color: white; padding: 5px 10px; border: none; border-radius: 4px; cursor: pointer; }
        .statistik-manager-bookmarks button:hover { background-color: #a12b2d; }
        @media (max-width: 600px) {
            .statistik-manager-bookmark-form input, .statistik-manager-bookmark-form button { font-size: 14px; }
            .statistik-manager-bookmarks li { flex-direction: column; align-items: flex-start; }
            .statistik-manager-bookmarks button { margin-bottom: 5px; }
        }
    </style>
    <?php
    return ob_get_clean();
}
add_shortcode('add_bookmark', 'statistik_manager_add_bookmark_shortcode');

/**
 * Fügt JavaScript für AJAX-Interaktionen hinzu.
 */
function statistik_manager_add_bookmark_script() {
    if (!is_singular() && !has_shortcode(get_the_content(), 'add_bookmark') && !has_shortcode(get_the_content(), 'display_bookmarks')) {
        return;
    }
    ?>
    <script type="text/javascript">
        jQuery(document).ready(function($) {
            $('#add-bookmark-form').on('submit', function(e) {
                e.preventDefault();

                var $form = $(this);
                var $message = $form.find('.form-message');
                var data = {
                    action: 'add_bookmark',
                    nonce: $form.find('[name="nonce"]').val(),
                    bookmark_url: $form.find('#bookmark_url').val(),
                    bookmark_name: $form.find('#bookmark_name').val(),
                };

                $.post('<?php echo esc_url(admin_url('admin-ajax.php')); ?>', data, function(response) {
                    $message.removeClass('error');
                    if (response.success) {
                        $message.addClass('success').text(response.data.message);
                        $('.statistik-manager-bookmarks ul').append(response.data.html);
                        $form.find('#bookmark_url, #bookmark_name').val('');
                    } else {
                        $message.addClass('error').text(response.data.message);
                    }
                });
            });

            $('body').on('click', '.delete-bookmark-btn', function() {
                var $button = $(this);
                var bookmarkId = $button.data('bookmark-id');
                var data = {
                    action: 'delete_bookmark',
                    nonce: $('#add-bookmark-form [name="nonce"]').val(),
                    bookmark_id: bookmarkId,
                };

                $.post('<?php echo esc_url(admin_url('admin-ajax.php')); ?>', data, function(response) {
                    var $message = $('.statistik-manager-bookmark-form .form-message');
                    $message.removeClass('error success');
                    if (response.success) {
                        $message.addClass('success').text(response.data.message);
                        $button.closest('li').remove();
                    } else {
                        $message.addClass('error').text(response.data.message);
                    }
                });
            });
        });
    </script>
    <?php
}
add_action('wp_footer', 'statistik_manager_add_bookmark_script');


