<?php
/**
 * Cemetery Prefecture Taxonomy Template
 * 都道府県別霊園一覧ページ（データ取得修正版）
 */

get_header(); 

// 現在のタームを取得
$current_term = get_queried_object();
$term_id = $current_term->term_id;
$term_name = $current_term->name;
$term_slug = $current_term->slug;

// デバッグモード
$debug_mode = isset($_GET['debug']) || current_user_can('manage_options');

// ページ番号を取得
$paged = get_query_var('paged') ? get_query_var('paged') : 1;

// 強制的にカスタムクエリを実行（メインクエリが機能していない場合の対策）
$args = array(
    'post_type'      => 'cemetery',
    'posts_per_page' => 12,
    'paged'          => $paged,
    'post_status'    => 'publish',
    'tax_query'      => array(
        array(
            'taxonomy' => 'cemetery_prefecture',
            'field'    => 'term_id',
            'terms'    => $term_id,
            'operator' => 'IN'
        ),
    ),
);

// 並び替えパラメータ
if (isset($_GET['orderby'])) {
    switch ($_GET['orderby']) {
        case 'title':
            $args['orderby'] = 'title';
            $args['order'] = 'ASC';
            break;
        case 'price':
            $args['meta_key'] = 'cemetery_price';
            $args['orderby'] = 'meta_value_num';
            $args['order'] = 'ASC';
            break;
        default:
            $args['orderby'] = 'date';
            $args['order'] = 'DESC';
    }
}

// クエリを実行
$cemetery_query = new WP_Query($args);

?>

<main id="main" class="l-main cemetery-prefecture-main">
    
    <!-- デバッグ情報（管理者のみ） -->
    <?php if ($debug_mode): ?>
        <div style="background: #ffffcc; padding: 20px; margin: 20px; border: 2px solid #ff9900;">
            <h3>🔍 デバッグ情報</h3>
            <ul>
                <li>ターム名: <?php echo $term_name; ?></li>
                <li>ターム ID: <?php echo $term_id; ?></li>
                <li>ターム スラッグ: <?php echo $term_slug; ?></li>
                <li>投稿数（ターム）: <?php echo $current_term->count; ?></li>
                <li>クエリ結果: <?php echo $cemetery_query->found_posts; ?>件</li>
                <li>現在のページ: <?php echo $paged; ?></li>
                <li>総ページ数: <?php echo $cemetery_query->max_num_pages; ?></li>
            </ul>
            
            <?php
            // SQL確認
            global $wpdb;
            $last_query = $wpdb->last_query;
            if ($last_query) {
                echo '<p><strong>最後のSQL:</strong></p>';
                echo '<pre style="background: white; padding: 10px; overflow: auto;">' . esc_html($last_query) . '</pre>';
            }
            ?>
            
            <?php
            // 直接SQLでデータ確認
            $test_sql = $wpdb->prepare(
                "SELECT p.ID, p.post_title 
                FROM {$wpdb->posts} p
                INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
                INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
                WHERE tt.term_id = %d 
                AND p.post_type = 'cemetery' 
                AND p.post_status = 'publish'
                LIMIT 5",
                $term_id
            );
            $test_results = $wpdb->get_results($test_sql);
            
            if ($test_results) {
                echo '<p><strong>直接SQL結果（最大5件）:</strong></p>';
                echo '<ul>';
                foreach ($test_results as $result) {
                    echo '<li>ID: ' . $result->ID . ' - ' . esc_html($result->post_title) . '</li>';
                }
                echo '</ul>';
            } else {
                echo '<p style="color: red;">⚠️ 直接SQLでもデータが取得できません。タクソノミーの関連付けを確認してください。</p>';
            }
            ?>
        </div>
    <?php endif; ?>
    
    <!-- パンくずリスト -->
    <div class="breadcrumb-area">
        <div class="swell-container">
            <ul class="breadcrumb">
                <li><a href="<?php echo home_url(); ?>">ホーム</a></li>
                <li><a href="<?php echo home_url('/cemetery/'); ?>">霊園・墓地</a></li>
                <li class="current"><?php echo esc_html($term_name); ?></li>
            </ul>
        </div>
    </div>
    
    <!-- ヘッダー -->
    <section class="cemetery-area-header">
        <div class="swell-container">
            <h1 class="area-title"><?php echo esc_html($term_name); ?>の霊園・墓地</h1>
            <div class="area-stats">
                <span>掲載霊園: <strong><?php echo $cemetery_query->found_posts; ?></strong>件</span>
                <?php if ($cemetery_query->found_posts > 0): ?>
                    <span class="divider">|</span>
                    <span><?php echo $paged; ?> / <?php echo $cemetery_query->max_num_pages; ?> ページ</span>
                <?php endif; ?>
            </div>
        </div>
    </section>
    
    <?php if ($cemetery_query->found_posts > 0): ?>
        <!-- ソート機能 -->
        <section class="cemetery-filter-section">
            <div class="swell-container">
                <form method="get" class="cemetery-filter-form">
                    <div class="filter-group">
                        <label for="orderby">並び替え:</label>
                        <select name="orderby" id="orderby" onchange="this.form.submit()">
                            <option value="">新着順</option>
                            <option value="title" <?php selected($_GET['orderby'] ?? '', 'title'); ?>>名前順</option>
                            <option value="price" <?php selected($_GET['orderby'] ?? '', 'price'); ?>>価格順</option>
                        </select>
                    </div>
                </form>
            </div>
        </section>
    <?php endif; ?>
    
    <!-- 霊園リスト -->
    <section class="cemetery-list-section">
        <div class="swell-container">
            
            <?php if ($cemetery_query->have_posts()): ?>
                <div class="cemetery-grid">
                    <?php while ($cemetery_query->have_posts()): $cemetery_query->the_post(); 
                        
                        $cemetery_id = get_the_ID();
                        
                        // カスタムフィールドを取得
                        $fields = array();
                        
                        // ACF優先で取得
                        if (function_exists('get_field')) {
                            $fields['image_url'] = get_field('cemetery_image_url', $cemetery_id);
                            $fields['address'] = get_field('cemetery_address', $cemetery_id);
                            $fields['price_html'] = get_field('price_html', $cemetery_id);
                            $fields['cemetery_type'] = get_field('cemetery_type', $cemetery_id);
                            $fields['cemetery_access'] = get_field('cemetery_access', $cemetery_id);
                        }
                        
                        // 値が無い場合はメタデータから取得
                        if (empty($fields['image_url'])) {
                            $fields['image_url'] = get_post_meta($cemetery_id, 'cemetery_image_url', true);
                        }
                        if (empty($fields['address'])) {
                            $fields['address'] = get_post_meta($cemetery_id, 'cemetery_address', true);
                        }
                        if (empty($fields['price_html'])) {
                            $fields['price_html'] = get_post_meta($cemetery_id, 'price_html', true);
                        }
                        if (empty($fields['cemetery_type'])) {
                            $fields['cemetery_type'] = get_post_meta($cemetery_id, 'cemetery_type', true);
                        }
                        if (empty($fields['cemetery_access'])) {
                            $fields['cemetery_access'] = get_post_meta($cemetery_id, 'cemetery_access', true);
                        }
                        
                    ?>
                        <article class="cemetery-card">
                            <a href="<?php the_permalink(); ?>" class="card-link">
                                <!-- 画像 -->
                                <div class="card-image">
                                    <?php if ($fields['image_url']): ?>
                                        <img src="<?php echo esc_url($fields['image_url']); ?>" 
                                             alt="<?php the_title_attribute(); ?>"
                                             loading="lazy">
                                    <?php elseif (has_post_thumbnail()): ?>
                                        <?php the_post_thumbnail('medium', array('loading' => 'lazy')); ?>
                                    <?php else: ?>
                                        <div class="no-image">
                                            <span class="no-image-icon">🪦</span>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <?php if ($fields['cemetery_type']): ?>
                                        <span class="type-label"><?php echo esc_html($fields['cemetery_type']); ?></span>
                                    <?php endif; ?>
                                </div>
                                
                                <!-- コンテンツ -->
                                <div class="card-content">
                                    <h3 class="card-title"><?php the_title(); ?></h3>
                                    
                                    <?php if ($fields['address']): ?>
                                        <p class="card-info">
                                            <span class="icon">📍</span>
                                            <span class="text"><?php echo esc_html($fields['address']); ?></span>
                                        </p>
                                    <?php endif; ?>
                                    
                                    <?php if ($fields['cemetery_access']): ?>
                                        <p class="card-info">
                                            <span class="icon">🚃</span>
                                            <span class="text"><?php echo esc_html($fields['cemetery_access']); ?></span>
                                        </p>
                                    <?php endif; ?>
                                    
                                    <?php if ($fields['price_html']): ?>
                                        <div class="card-price">
                                            <?php echo wp_kses_post($fields['price_html']); ?>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <div class="card-cta">
                                        詳細を見る →
                                    </div>
                                </div>
                            </a>
                        </article>
                    <?php endwhile; ?>
                </div>
                
                <!-- ページネーション -->
                <div class="cemetery-pagination">
                    <?php
                    $big = 999999999;
                    echo paginate_links(array(
                        'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
                        'format' => '?paged=%#%',
                        'current' => max(1, $paged),
                        'total' => $cemetery_query->max_num_pages,
                        'prev_text' => '← 前へ',
                        'next_text' => '次へ →',
                        'mid_size' => 2,
                        'end_size' => 1
                    ));
                    ?>
                </div>
                
            <?php else: ?>
                <!-- データがない場合 -->
                <div class="no-results">
                    <div class="no-results-inner">
                        <h2>😔 データが見つかりません</h2>
                        <p><?php echo esc_html($term_name); ?>の霊園情報が登録されていないか、<br>都道府県の関連付けが正しく設定されていません。</p>
                        
                        <div style="background: #fff; padding: 20px; border: 2px solid #667eea; border-radius: 8px; margin: 30px auto; max-width: 600px; text-align: left;">
                            <h3 style="color: #667eea; margin-bottom: 15px;">👉 解決方法</h3>
                            <ol style="margin-left: 20px;">
                                <li style="margin-bottom: 10px;">
                                    <a href="<?php echo admin_url('edit.php?post_type=cemetery&page=cemetery-location'); ?>" 
                                       style="color: #667eea; text-decoration: underline;" 
                                       target="_blank">地域設定ページ</a>を開く
                                </li>
                                <li style="margin-bottom: 10px;">「自動設定を実行」ボタンをクリック</li>
                                <li style="margin-bottom: 10px;">処理完了後、このページをリロード</li>
                            </ol>
                            
                            <?php if (current_user_can('manage_options')): ?>
                                <div style="margin-top: 20px; padding-top: 20px; border-top: 1px solid #e0e0e0;">
                                    <p style="font-size: 14px; color: #666;">
                                        ※ URLに「?debug=1」を追加すると、詳細なデバッグ情報を表示できます
                                    </p>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <!-- 他の都道府県へのリンク -->
                        <div class="alternative-section">
                            <h3>他の都道府県の霊園を探す</h3>
                            <?php
                            $other_terms = get_terms(array(
                                'taxonomy' => 'cemetery_prefecture',
                                'exclude' => array($term_id),
                                'hide_empty' => false,  // 空のタームも表示
                                'number' => 12,
                                'orderby' => 'name',
                                'order' => 'ASC'
                            ));
                            
                            if ($other_terms && !is_wp_error($other_terms)): ?>
                                <div class="prefecture-links">
                                    <?php foreach ($other_terms as $other_term): ?>
                                        <a href="<?php echo get_term_link($other_term); ?>" class="prefecture-link">
                                            <?php echo esc_html($other_term->name); ?>
                                            <?php if ($other_term->count > 0): ?>
                                                <span class="count">(<?php echo $other_term->count; ?>)</span>
                                            <?php endif; ?>
                                        </a>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="cta-section">
                            <a href="<?php echo home_url(); ?>" class="btn-primary">トップページへ戻る</a>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
            
            <?php wp_reset_postdata(); ?>
        </div>
    </section>
</main>

<?php get_footer(); ?>