<?php
/**
 * WP Multi – Modul: Gast-Autoren
 *
 * 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; }

/*
* Gast Autoren
*/

// Gast-Autor Eingabefeld in der Sidebar im Admin-Bereich hinzufügen
function wp_multi_add_guest_author_field() {
    add_meta_box(
        'guest_author_meta_box',
        __('Gast-Autor', 'wp-multi'),
        'wp_multi_guest_author_field',
        ['post', 'page', 'dein_custom_post_type'], 
        'side',
        'high'
    );
}
add_action('add_meta_boxes', 'wp_multi_add_guest_author_field');

// Callback-Funktion, die das Eingabefeld anzeigt
function wp_multi_guest_author_field($post) {
    $guest_author = get_post_meta($post->ID, '_guest_author', true);
    wp_nonce_field('wp_multi_guest_author_nonce', 'wp_multi_guest_author_nonce_field');
    ?>
    <label for="guest_author"><?php _e('Gast-Autor Name:', 'wp-multi'); ?></label>
    <input type="text" id="guest_author" name="guest_author" value="<?php echo esc_attr($guest_author); ?>" class="widefat" />
    <?php
}

// Speichern der Gast-Autor Daten
function wp_multi_save_guest_author_meta($post_id) {
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!isset($_POST['wp_multi_guest_author_nonce_field']) || !wp_verify_nonce($_POST['wp_multi_guest_author_nonce_field'], 'wp_multi_guest_author_nonce')) return;
    if (!current_user_can('edit_post', $post_id)) return;
    if (isset($_POST['guest_author'])) {
        $guest_author = sanitize_text_field(wp_unslash($_POST['guest_author']));
        update_post_meta($post_id, '_guest_author', $guest_author);
    } else {
        delete_post_meta($post_id, '_guest_author');
    }
}
add_action('save_post', 'wp_multi_save_guest_author_meta');

// Gast-Autor anzeigen anstelle des regulären Autors im Frontend
function wp_multi_display_guest_author($author_name) {
    if ((is_single() || is_archive() || is_home()) && !is_admin()) {  
        $post = get_post();
        if ($post) {
            $guest_author = get_post_meta($post->ID, '_guest_author', true);
            if (!empty($guest_author)) {
                $author_name = $guest_author;
            }
        }
    }
    return $author_name;
}
add_filter('the_author', 'wp_multi_display_guest_author');

// Anzeige des Gast-Autors in der Beitragsübersicht (Backend)
function wp_multi_add_guest_author_column($columns) {
    if (isset($columns['author'])) {
        $columns['guest_author'] = __('Gast-Autor', 'wp-multi');
    }
    return $columns;
}
add_filter('manage_posts_columns', 'wp_multi_add_guest_author_column');

function wp_multi_display_guest_author_column($column_name, $post_id) {
    if ($column_name == 'guest_author') {
        $guest_author = get_post_meta($post_id, '_guest_author', true);
        echo !empty($guest_author) ? esc_html($guest_author) : __('Kein Gast-Autor', 'wp-multi');
    }
}
add_action('manage_posts_custom_column', 'wp_multi_display_guest_author_column', 10, 2);

// Der Gast-Autoren-Menüpunkt wird zentral in wp_multi_register_admin_menus() registriert.

// Callback-Funktion für die Gast-Autor-Übersicht
function wp_multi_guest_author_overview_page() {
    // Sortierparameter aus URL lesen
    $orderby = isset($_GET['orderby']) ? sanitize_key($_GET['orderby']) : 'guest_author';
    $order = isset($_GET['order']) && in_array(strtoupper($_GET['order']), ['ASC', 'DESC']) ? strtoupper($_GET['order']) : 'ASC';

    // Gültige Sortierfelder
    $valid_orderby = ['guest_author' => 'pm.meta_value', 'posts' => 'post_count'];
    $sql_orderby = isset($valid_orderby[$orderby]) ? $valid_orderby[$orderby] : 'pm.meta_value';
    $sql_order = $order;

    // Basis-URL für Sortier-Links
    $base_url = add_query_arg(['page' => 'guest_author_overview'], admin_url('admin.php'));

    global $wpdb;
    $query = "
        SELECT pm.meta_value AS guest_author, COUNT(*) AS post_count
        FROM {$wpdb->posts} p
        INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
        WHERE pm.meta_key = '_guest_author'
        AND pm.meta_value != ''
        AND p.post_status = 'publish'
        GROUP BY pm.meta_value
        ORDER BY {$sql_orderby} {$sql_order}
    ";
    $guest_authors = $wpdb->get_results($query);

    wpmt_admin_page_open(
        __('Gast-Autoren', 'wp-multi'),
        __('Alle Gast-Autoren mit Anzahl ihrer veröffentlichten Beiträge', 'wp-multi')
    );

    wpmt_admin_card_open();
    ?>
    <div class="wpm-table-wrap">
        <table class="wpm-table">
            <thead>
                <tr>
                    <th>
                        <a href="<?php echo esc_url(add_query_arg(['orderby' => 'guest_author', 'order' => ($orderby === 'guest_author' && $order === 'ASC') ? 'DESC' : 'ASC'], $base_url)); ?>">
                            <?php _e('Gast-Autor', 'wp-multi'); ?>
                            <?php if ($orderby === 'guest_author') : ?>
                                <span><?php echo ($order === 'ASC') ? '↑' : '↓'; ?></span>
                            <?php endif; ?>
                        </a>
                    </th>
                    <th>
                        <a href="<?php echo esc_url(add_query_arg(['orderby' => 'posts', 'order' => ($orderby === 'posts' && $order === 'ASC') ? 'DESC' : 'ASC'], $base_url)); ?>">
                            <?php _e('Anzahl der Beiträge', 'wp-multi'); ?>
                            <?php if ($orderby === 'posts') : ?>
                                <span><?php echo ($order === 'ASC') ? '↑' : '↓'; ?></span>
                            <?php endif; ?>
                        </a>
                    </th>
                </tr>
            </thead>
            <tbody>
                <?php if ($guest_authors) : ?>
                    <?php foreach ($guest_authors as $author) : ?>
                        <tr>
                            <td><?php echo esc_html($author->guest_author); ?></td>
                            <td><span class="wpm-badge"><?php echo esc_html($author->post_count); ?></span></td>
                        </tr>
                    <?php endforeach; ?>
                <?php else : ?>
                    <tr><td colspan="2"><?php _e('Keine Gast-Autoren gefunden.', 'wp-multi'); ?></td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    <?php
    wpmt_admin_card_close();

    wpmt_admin_page_close();
}


// Funktion zum Erstellen der Gastautoren-Beitragsseite
function wp_multi_create_guest_author_page() {
    $page_title = __('Gastautor Beiträge', 'wp-multi');
    $page_slug = 'gastautor-beitraege';
    $page = get_page_by_path($page_slug);

    if (!$page) {
        $page_id = wp_insert_post(array(
            'post_title' => $page_title,
            'post_name' => $page_slug,
            'post_content' => '[guest_author_posts]',
            'post_status' => 'publish',
            'post_type' => 'page',
        ));

        if ($page_id && !is_wp_error($page_id)) {
            update_option('wp_multi_guest_author_page_id', $page_id);
        }
    } else {
        update_option('wp_multi_guest_author_page_id', $page->ID);
    }
}
add_action('init', 'wp_multi_create_guest_author_page');

// Shortcode für Gastautoren-Liste
function wp_multi_guest_author_shortcode() {
    ob_start();
    global $wpdb;

    // Alle Gastautoren mit Beitragsanzahl abrufen
    $query = "
        SELECT pm.meta_value AS guest_author, COUNT(*) AS post_count
        FROM {$wpdb->posts} p
        INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
        WHERE pm.meta_key = '_guest_author' 
        AND pm.meta_value != '' 
        AND p.post_status = 'publish'
        GROUP BY pm.meta_value
        ORDER BY pm.meta_value ASC
    ";
    $guest_authors = $wpdb->get_results($query);

    // URL der Gastautoren-Beitragsseite
    $guest_author_page_id = get_option('wp_multi_guest_author_page_id');
    $guest_author_page_url = $guest_author_page_id ? get_permalink($guest_author_page_id) : '#';

    ?>
    <div id="guest-author-section" class="container mx-auto px-4 py-8">
        <!-- Gastautoren-Liste -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
            <?php if ($guest_authors) : ?>
                <?php foreach ($guest_authors as $author) : ?>
                    <a href="<?php echo esc_url(add_query_arg('guest_author', urlencode($author->guest_author), $guest_author_page_url)); ?>" class="guest-author-card bg-white p-6 rounded-lg shadow-md hover:shadow-lg transition">
                        <h3 class="text-xl font-semibold text-gray-800"><?php echo esc_html($author->guest_author); ?></h3>
                        <p class="text-gray-600"><?php echo esc_html($author->post_count); ?> <?php _e('Beiträge', 'wp-multi'); ?></p>
                    </a>
                <?php endforeach; ?>
            <?php else : ?>
                <p class="col-span-2 text-center text-gray-600"><?php _e('Keine Gastautoren gefunden.', 'wp-multi'); ?></p>
            <?php endif; ?>
        </div>
    </div>

    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    <?php

    return ob_get_clean();
}
add_shortcode('guest_authors', 'wp_multi_guest_author_shortcode');

// Shortcode für Gastautoren-Beiträge
function wp_multi_guest_author_posts_shortcode() {
    ob_start();

    $guest_author = isset($_GET['guest_author']) ? sanitize_text_field(wp_unslash($_GET['guest_author'])) : '';

    ?>
    <div id="guest-author-posts" class="container mx-auto px-4 py-8">
        <h2 class="text-2xl font-semibold text-gray-800 mb-4">
            <?php
            if ($guest_author) {
                printf(__('Beiträge von %s', 'wp-multi'), esc_html($guest_author));
            } else {
                _e('Beiträge auswählen', 'wp-multi');
            }
            ?>
        </h2>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <?php
            if ($guest_author) {
                $args = array(
                    'post_type' => ['post', 'page', 'dein_custom_post_type'],
                    'post_status' => 'publish',
                    'meta_query' => array(
                        array(
                            'key' => '_guest_author',
                            'value' => $guest_author,
                            'compare' => '='
                        )
                    ),
                    'tax_query' => array(
                        array(
                            'taxonomy' => 'category',
                            'field' => 'slug',
                            'terms' => 'series',
                            'operator' => 'NOT IN'
                        )
                    ),
                    'posts_per_page' => -1
                );

                $query = new WP_Query($args);

                

                if ($query->have_posts()) {
                    while ($query->have_posts()) {
                        $query->the_post();
                        // Beitragsinhalt abrufen und kürzen
                        $content = get_the_content();
                        $content = wp_strip_all_tags($content); // HTML-Tags entfernen
                        $trimmed_content = wp_trim_words($content, 30, '...');
                        ?>
                        <div class="post-card bg-white p-6 rounded-lg shadow-md">
                            <h3 class="text-lg font-medium text-gray-800">
                                <a href="<?php the_permalink(); ?>" class="hover:text-blue-600"><?php the_title(); ?></a>
                            </h3>
                            <p class="text-gray-600 line-clamp-3"><?php echo esc_html($trimmed_content); ?></p>
                        </div>
                        <?php
                    }
                    wp_reset_postdata();
                } else {
                    ?>
                    <p class="col-span-2 text-gray-600"><?php _e('Keine Beiträge gefunden.', 'wp-multi'); ?></p>
                    <?php
                }
            } else {
                ?>
                <p class="col-span-2 text-gray-600"><?php _e('Wählen Sie einen Gastautor aus, um die Beiträge anzuzeigen.', 'wp-multi'); ?></p>
                <?php
            }
            ?>
        </div>
    </div>

    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    <?php

    return ob_get_clean();
}
add_shortcode('guest_author_posts', 'wp_multi_guest_author_posts_shortcode');

