/*
Theme Name: DMM Auto Theme Child
Theme URI: https://wp-plugin.net/
Author: WP-Plugins
Author URI: https://wp-plugin.net/
Template: dmm-auto-theme
Description: dmm-auto-theme のカスタマイズ用子テーマ
Version: 1.0.0
Text Domain: dmm-auto-theme-child
*/

/* 子テーマのカスタム CSS */

<?php
// =======================================================
// 子テーマ functions.php
// =======================================================

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

// -------------------------------------------------------
// 1. テーマセットアップ（スタイル読み込み等）
// -------------------------------------------------------
add_action( 'wp_enqueue_scripts', 'dmmt_child_enqueue_styles' );
function dmmt_child_enqueue_styles() {
    $parent_handle = 'dmmt-style';
    wp_enqueue_style(
        'dmmt-child-style',
        get_stylesheet_directory_uri() . '/style.css',
        array( $parent_handle ),
        wp_get_theme()->get( 'Version' )
    );
}

// -------------------------------------------------------
// 2. SEO対策（SEO SIMPLE PACK連携・インデックス制御）
// -------------------------------------------------------

// ページ分割時等のcanonical調整
add_filter( 'ssp_canonical_url', function( $url ) {
    if ( is_paged() || is_404() ) return null; 
    return $url;
} );

// 記事数が5件以下のカテゴリー・女優（actress）ページを自動noindex
add_filter( 'ssp_meta_robots', function( $robots ) {
    if ( is_category() || is_tax( 'actress' ) ) {
        $term = get_queried_object();
        if ( $term && isset( $term->count ) && $term->count <= 5 ) {
            return 'noindex, follow';
        }
    }
    return $robots;
});

// -------------------------------------------------------
// 3. 画像最適化（アイキャッチのalt自動設定）
// -------------------------------------------------------
function auto_set_thumbnail_alt( $meta_id, $post_id, $meta_key, $meta_value ) {
    if ( '_thumbnail_id' !== $meta_key ) return;
    if ( empty( $meta_value ) ) return;
    
    $post_title = get_the_title( $post_id );
    if ( $post_title ) {
        update_post_meta( $meta_value, '_wp_attachment_image_alt', $post_title );
    }
}
add_action( 'added_post_meta', 'auto_set_thumbnail_alt', 10, 4 );
add_action( 'updated_post_meta', 'auto_set_thumbnail_alt', 10, 4 );

// -------------------------------------------------------
// 4. ショートコード（女優の関連記事 出力）
// -------------------------------------------------------
function dmm_related_posts_shortcode_final( $atts = array() ) {
    if ( ! is_singular() ) return ''; 

    $atts = shortcode_atts( array( 'count' => 4 ), $atts );

    $taxonomy_slug = 'actress'; 
    $current_post_id = get_the_ID();
    $terms = get_the_terms( $current_post_id, $taxonomy_slug );

    if ( ! $terms || is_wp_error( $terms ) ) return '';

    // 1人目の女優を取得
    $term = $terms[0];
    $term_name = esc_html( $term->name );
    $term_link = get_term_link( $term ); 
    $button_text = $term_name . 'さんの動画をもっと探す';

    $args = array(
        'post_type'      => get_post_type( $current_post_id ),
        'posts_per_page' => intval( $atts['count'] ),
        'post__not_in'   => array( $current_post_id ),
        'orderby'        => 'date',
        'order'          => 'DESC',
        'tax_query'      => array(
            array(
                'taxonomy' => $taxonomy_slug,
                'field'    => 'term_id',
                'terms'    => array( $term->term_id )
            )
        ),
    );

    $related_query = new WP_Query( $args );

    if ( $related_query->have_posts() ) {
        ob_start();
        ?>
        <div id="ux-actress-wrap" style="margin: 2.5rem 0; clear: both;">
            <style>
                #ux-actress-wrap .ux-grid {
                    display: grid !important;
                    grid-template-columns: repeat(2, 1fr) !important;
                    gap: 12px !important;
                    margin: 0 !important;
                    padding: 0 !important;
                }
                #ux-actress-wrap .ux-card {
                    display: flex !important;
                    flex-direction: column !important;
                    background: transparent !important;
                    border: none !important;
                    box-shadow: none !important;
                    padding: 0 !important;
                    margin: 0 !important;
                }
                #ux-actress-wrap .ux-card:nth-child(n+3) {
                    display: none !important;
                }
                @media(min-width: 768px) {
                    #ux-actress-wrap .ux-grid {
                        grid-template-columns: repeat(4, 1fr) !important;
                        gap: 16px !important;
                    }
                    #ux-actress-wrap .ux-card:nth-child(n+3) {
                        display: flex !important;
                    }
                }
                #ux-actress-wrap .ux-thumb {
                    aspect-ratio: 90/122 !important;
                    overflow: hidden !important;
                    border-radius: 6px !important;
                    display: block !important;
                    background: #f1f5f9 !important;
                    box-shadow: none !important;
                    border: none !important;
                }
                #ux-actress-wrap .ux-thumb img {
                    width: 100% !important;
                    height: 100% !important;
                    object-fit: cover !important;
                    object-position: 94% center !important;
                    transition: opacity 0.2s !important;
                    border: none !important;
                    margin: 0 !important;
                    padding: 0 !important;
                }
                #ux-actress-wrap .ux-thumb:hover img {
                    opacity: 0.8 !important;
                }
                #ux-actress-wrap .ux-title {
                    font-size: 13px !important;
                    font-weight: 600 !important;
                    line-height: 1.4 !important;
                    margin: 8px 0 0 0 !important;
                    display: -webkit-box !important;
                    -webkit-line-clamp: 2 !important;
                    -webkit-box-orient: vertical !important;
                    overflow: hidden !important;
                }
                #ux-actress-wrap .ux-title a {
                    text-decoration: none !important;
                    color: #0f172a !important; 
                    box-shadow: none !important;
                }
                #ux-actress-wrap .ux-title a:hover {
                    color: #db2777 !important; 
                    text-decoration: underline !important;
                }
            </style>

            <h3 style="font-size: 1.1rem !important; font-weight: 700 !important; border-left: 4px solid #db2777 !important; padding-left: 8px !important; margin: 0 0 16px 0 !important; color: #0f172a !important; line-height: 1.3 !important;">
                <?php echo $term_name; ?>さんの別作品
            </h3>

            <div class="ux-grid">
                <?php
                while ( $related_query->have_posts() ) {
                    $related_query->the_post();
                    $img = has_post_thumbnail() ? get_the_post_thumbnail( get_the_ID(), 'full' ) : '<div style="width:100%;height:100%;display:flex;align-items:center;justify-content:center;color:#94a3b8;font-size:0.8rem;">No Image</div>';
                    ?>
                    <article class="ux-card">
                        <a href="<?php echo get_permalink(); ?>" class="ux-thumb"><?php echo $img; ?></a>
                        <h4 class="ux-title"><a href="<?php echo get_permalink(); ?>"><?php echo get_the_title(); ?></a></h4>
                    </article>
                    <?php
                }
                ?>
            </div>

            <div style="text-align: right; margin-top: 20px;">
                <a href="<?php echo esc_url( $term_link ); ?>" style="display: inline-block; background: #db2777; color: #fff; padding: 6px 16px; border-radius: 9999px; font-size: 0.85rem; font-weight: bold; text-decoration: none;">
                    <?php echo esc_html( $button_text ); ?>
                </a>
            </div>
        </div>
        <?php
        $output = ob_get_clean();
        wp_reset_postdata();

        return str_replace( array( "\r", "\n", "\t" ), '', $output );
    }

    return '';
}

// プラグインに負けないように一番最後に強制登録
add_action( 'wp_loaded', function() {
    remove_shortcode( 'dmm_related' );
    add_shortcode( 'dmm_related', 'dmm_related_posts_shortcode_final' );
}, 999 );


// -------------------------------------------------------
// 5. ページネーション（前後記事リンクを同カテゴリ限定に）
// -------------------------------------------------------
add_action( 'wp_footer', function() {
    // dmm_item の詳細ページ以外では実行しない
    if ( ! is_singular( 'dmm_item' ) ) return;

    // 同一カテゴリーの前後の記事を取得
    $prev_post = get_previous_post( true, '', 'category' );
    $next_post = get_next_post( true, '', 'category' );

    // どちらもない場合は処理を終了
    if ( ! $prev_post && ! $next_post ) return;

    // 新しいHTMLをバッファリングして生成
    ob_start();
    ?>
    <nav class="dmm-item-prev-next custom-prev-next mt-10 pt-4 border-t border-slate-200">
        <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
            <?php if ( $prev_post ) : ?>
                <a href="<?php echo esc_url( get_permalink( $prev_post ) ); ?>" class="group flex items-start gap-3 p-3 rounded-lg border border-slate-200 bg-white hover:bg-slate-50 transition">
                    <span class="text-xl text-slate-400 group-hover:text-slate-600 shrink-0">‹</span>
                    <div class="min-w-0 flex-1">
                        <p class="text-xs text-slate-500 mb-0.5">前の記事</p>
                        <p class="text-sm font-semibold text-slate-900 line-clamp-2"><?php echo esc_html( get_the_title( $prev_post ) ); ?></p>
                    </div>
                </a>
            <?php endif; ?>

            <?php if ( $next_post ) : ?>
                <a href="<?php echo esc_url( get_permalink( $next_post ) ); ?>" class="group flex items-start gap-3 p-3 rounded-lg border border-slate-200 bg-white hover:bg-slate-50 transition justify-end text-right">
                    <div class="min-w-0 flex-1">
                        <p class="text-xs text-slate-500 mb-0.5">次の記事</p>
                        <p class="text-sm font-semibold text-slate-900 line-clamp-2"><?php echo esc_html( get_the_title( $next_post ) ); ?></p>
                    </div>
                    <span class="text-xl text-slate-400 group-hover:text-slate-600 shrink-0">›</span>
                </a>
            <?php endif; ?>
        </div>
    </nav>
    <?php
    $html = ob_get_clean();
    ?>

    <style>
        .dmm-item-prev-next:not(.custom-prev-next) { display: none !important; }
    </style>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            var oldNav = document.querySelector('.dmm-item-prev-next:not(.custom-prev-next)');
            if (oldNav) {
                var newHtml = <?php echo json_encode( $html ); ?>;
                oldNav.insertAdjacentHTML('afterend', newHtml);
                oldNav.remove(); // 不要なDOMを削除
            }
        });
    </script>
    <?php
}, 100 );


// -------------------------------------------------------
// 6. 【最終兵器】actress一覧のH1タイトルをHTML出力直前に強制書き換え
// -------------------------------------------------------
add_action('template_redirect', function() {
    // actressタクソノミーの一覧ページのみ実行
    if ( is_tax('actress') ) {
        
        // ページ全体のHTML出力を一旦ストップして監視（バッファリング）する
        ob_start(function($buffer) {
            $term = get_queried_object();
            
            if ( $term ) {
                // ▼ 表示したいタイトルをここで設定 ▼
                $title = esc_html($term->name) . 'のエロ動画まとめ';
                
                // ページ内の一番最初にある <h1>〜</h1> タグを探し出し、
                // その中身が空っぽでも何でも、問答無用でタイトルにすり替える！
                $buffer = preg_replace(
                    '/(<h1[^>]*>)(.*?)(<\/h1>)/is', 
                    '$1' . $title . '$3', 
                    $buffer, 
                    1 // 最初の1個目だけを書き換え
                );
            }
            return $buffer;
        });
    }
});