<?php if ( !defined( 'ABSPATH' ) ) exit;//PHPの宣言と直接アクセスの拒否

function haup_init_editor_panel_js_seo_fields(){
	$script_name = 'haup-panel-js-seo-fields';

	//投稿タイプを「投稿」に指定し、haup_is_single_filterで追加できるようにする
	$posttypes = 'post,page';
	$posttypes = apply_filters('haup_is_single_filter',$posttypes);
	$posttypes = apply_filters('haup_is_single_seo_fields_filter',$posttypes);
	//20250902 explodeだけでは空文字などがあった場合に不具合が出る可能性があるので修正
	$post_types_array = array_map('trim', explode(',', $posttypes));
	$post_types_array = array_filter($post_types_array);

	wp_enqueue_script(
		$script_name,
		plugin_dir_url( __FILE__ ) .'editor-panel.js',
		[ 'wp-plugins', 'wp-edit-post', 'wp-element', 'wp-components', 'wp-data', 'wp-i18n' ],
		haup_plugin_version(),
		array( 
			'strategy'  => 'defer',
			'in_footer' => true,// Note: This is the default value.
		)
	);

	$manual_parts = [
		haup_seo_manual_seo_title(),
		haup_seo_manual_meta_description(),
		haup_seo_manual_keywords(),
		haup_seo_manual_noindex(),
		haup_seo_manual_nofollow(),
	];
	
	$manual_content =  implode("\n", $manual_parts);

	//スクリプトに渡すための文字列と翻訳可能文字列を紐づけて配列にする
	$localize_val = array(
		// Panel & Tabs
		'title' => __('SEO Settings','hima-art-utility'),
		'tab_title_setting' => __('Custom metadata settings','hima-art-utility'),
		'tab_title_manual' => __('Overview of the feature and how to set it up','hima-art-utility'),

		// Setting Panel
		'panel_title_title_text' => __('SEO Title','hima-art-utility'),
		'panel_description_title_text' => __('Explanatory text','hima-art-utility'),
		'panel_noindex_title_text' => __('Add NOINDEX meta tag','hima-art-utility'),
		'panel_nofollow_title_text' => __('Add NOFOLLOW meta tag','hima-art-utility'),
		'panel_keywords_title_text' => __('Keywords (multiple keywords separated by commas ",")','hima-art-utility'),
		'setting_button_notice' => __('*After closing this screen, be sure to save the entire content by clicking "Publish," "Update," or "Save Draft" on the editing screen.','hima-art-utility'),
		'setting_button_text' => __('Apply settings and close.','hima-art-utility'),

		//Manual Panel
		'manual_button_notice' => __('Once you have reviewed the detailed instructions, please close the SEO settings screen or open the settings tab to continue editing.','hima-art-utility'),
		'manual_button_text' => __('Close the SEO settings screen.','hima-art-utility'),
		'manual_html_content' => $manual_content,

		//Side Panel
		'side_text' => __('This sets the meta tags to be output to HTML.','hima-art-utility'),
		'side_button_text' => __('Open Settings','hima-art-utility'),
		'side_change_value_notice' => __('Your settings have been changed. Please be sure to click the "Update" or "Save Draft" button in the upper right corner to save.','hima-art-utility'),

		// Post Types
		'post_types' => $post_types_array, //適用させる投稿タイプを配列で渡す
	);

	//wp_localize_scriptを使ってスクリプトへ配列を渡す
	wp_localize_script( $script_name , 'HaupLocalizeTextSeoFields', $localize_val);
}
add_action('enqueue_block_editor_assets','haup_init_editor_panel_js_seo_fields');

function haup_seo_manual_seo_title(){
	$header_title = __('SEO Title','hima-art-utility');
	$description_text = __('If you enter a value here, it will be used preferentially in the following locations (if not entered, the normal title will be used) ','hima-art-utility');
	$detail_title = __('The meaning and reason for making this setting','hima-art-utility');
	$detail_notice = __('*This explanation is a simplified version and not 100% accurate. For more detailed information about this meta tag, please search for it yourself.','hima-art-utility');
	$detail_text_a = __('The title tag serves to inform search engines that what is written in this tag is the official title of this page.','hima-art-utility');
	$detail_text_b = __('WordPress, by default, outputs the value entered in the title field of a post or page as the title tag, and simultaneously uses it as the title for individual pages and archive pages.','hima-art-utility');
	$detail_text_c = __('For example, if a website publishes many posts about WordPress and, in an effort to optimize for search engines (SEO), includes the phrase "WordPress" in the title of every post, then all the posts displayed on the archive page will start with "WordPress," making it difficult for visitors to find relevant information.','hima-art-utility');
	$detail_text_d = __('This setting applies the entered value only to the title meta tag, allowing you to specify a user-friendly title for individual posts and a title tag optimized for SEO.','hima-art-utility');

	$seotitledetail_a = __('title tag','hima-art-utility');
	$seotitledetail_b = __('Schema Org Title','hima-art-utility');
	$seotitledetail_c = __('Title when the share button is clicked','hima-art-utility');
	$seotitledetail_d = __('The normal title is used for page title display and list title display.','hima-art-utility');

	$output = '
		<div style="padding:12px;border-bottom: 1px solid #eee;margin-bottom:8px;">
			<h3>'.esc_html( $header_title ).'</h3>
			<details class="accordion" style="margin-left:20px;">
			<summary class="accordion__title" style="cursor: pointer;">'.esc_html( $detail_title ).'</summary>
			<div class="accordion__content" style="border:1px solid #eee;border-radius:4px;padding: 0px 4px;">
				<p style="color:red;font-size:0.8rem;">'.esc_html( $detail_notice ).'</p>
				<p>'.esc_html( $detail_text_a ).'</p>
				<p>'.esc_html( $detail_text_b ).'</p>
				<p>'.esc_html( $detail_text_c ).'</p>
				<p>'.esc_html( $detail_text_d ).'</p>
			</div>
			</details>
			<p>'.esc_html( $description_text ).'</p>
			<ol>
				<li>'.esc_html($seotitledetail_a).'</li>
				<li>'.esc_html($seotitledetail_b).'</li>
				<li>'.esc_html($seotitledetail_c).'</li>
				<li>'.esc_html($seotitledetail_d).'</li>
			</ol>
		</div>
	';
	
	return $output;
}

function haup_seo_manual_meta_description(){
	$header_title = __('Explanatory text','hima-art-utility');
	$description_text = __('The value entered here will be output in the HTML header as an excerpt of the description meta tag and Schema ORG. The output priority is as follows.','hima-art-utility');
	$detail_title = __('The meaning and reason for making this setting','hima-art-utility');
	$detail_notice = __('*This explanation is a simplified version and not 100% accurate. For more detailed information about this meta tag, please search for it yourself.','hima-art-utility');
	$detail_text_a = __('The description meta tag is used to accurately convey a summary of the page to search engines.','hima-art-utility');
	$detail_text_b = __('By default, WordPress outputs the text entered in the "Excerpt" field, or the first 55 characters of the main text if no field is entered.','hima-art-utility');
	$detail_text_c = __('Depending on the theme, this value may also be output as the description on the archive page, which could lead to the same problems as those described in the title tag.','hima-art-utility');
	$detail_text_d = __('The values entered in this setting are primarily output to the description meta tag, allowing you to communicate text different from the site on-screen description to search engines.','hima-art-utility');

	$seodescridetail_a = __('description Meta tag: input value → input value to excerpt → opening text of text','hima-art-utility');
	$seodescridetail_b = __('Schema Org excerpt: input value → first 120 characters of text','hima-art-utility');
	$seodescridetail_c = __('The value of this item is ignored in the character strings output to the list of posts, list of archives, and OGP tags, and the input value to the excerpt → the opening sentence of the main text.','hima-art-utility');

	$output = '
		<div style="padding:12px;border-bottom: 1px solid #eee;margin-bottom:8px;">
			<h3>'.esc_html( $header_title ).'</h3>
			<details class="accordion" style="margin-left:20px;">
			<summary class="accordion__title" style="cursor: pointer;">'.esc_html( $detail_title ).'</summary>
			<div class="accordion__content" style="border:1px solid #eee;border-radius:4px;padding: 0px 4px;">
				<p style="color:red;font-size:0.8rem;">'.esc_html( $detail_notice ).'</p>
				<p>'.esc_html( $detail_text_a ).'</p>
				<p>'.esc_html( $detail_text_b ).'</p>
				<p>'.esc_html( $detail_text_c ).'</p>
				<p>'.esc_html( $detail_text_d ).'</p>
			</div>
			</details>
			<p>'.esc_html( $description_text ).'</p>
			<ol>
				<li>'.esc_html($seodescridetail_a).'</li>
				<li>'.esc_html($seodescridetail_b).'</li>
			</ol>
			<p>'.esc_html($seodescridetail_c).'</p>
		</div>
	';
	
	return $output;
}

function haup_seo_manual_keywords(){
	$header_title = __('Keywords (multiple keywords separated by commas ",")','hima-art-utility');
	$description_text = __('The value entered here will be output in the HTML header as keywords meta tag','hima-art-utility');
	$detail_title = __('The meaning and reason for making this setting','hima-art-utility');
	$detail_notice = __('*This explanation is a simplified version and not 100% accurate. For more detailed information about this meta tag, please search for it yourself.','hima-art-utility');
	$detail_text_a = __('The keywords meta tag is output to inform search engines about the keywords contained on a page, but for various reasons, major search engines now ignore this value.','hima-art-utility');
	$detail_text_b = __('However, due to changes in search engine specifications, some search engines may start reading keywords, and some may even use keywords as a reference. Therefore, it is a good idea to set several keywords that are relevant to the page content.','hima-art-utility');

	$output = '
		<div style="padding:12px;border-bottom: 1px solid #eee;margin-bottom:8px;">
			<h3>'.esc_html( $header_title ).'</h3>
			<details class="accordion" style="margin-left:20px;">
			<summary class="accordion__title" style="cursor: pointer;">'.esc_html( $detail_title ).'</summary>
			<div class="accordion__content" style="border:1px solid #eee;border-radius:4px;padding: 0px 4px;">
				<p style="color:red;font-size:0.8rem;">'.esc_html( $detail_notice ).'</p>
				<p>'.esc_html( $detail_text_a ).'</p>
				<p>'.esc_html( $detail_text_b ).'</p>
			</div>
			</details>
			<p>'.esc_html( $description_text ).'</p>
		</div>
	';
	
	return $output;
}

function haup_seo_manual_noindex(){
	$header_title = __('Add NOINDEX meta tag','hima-art-utility');
	$description_text = __('Output a noindex tag in the HTML header<br>The noindex tag tells search engines not to search for your page, but it is up to the search engine to decide whether or not it will be indexed. Please be careful.','hima-art-utility');
	$detail_title = __('The meaning and reason for making this setting','hima-art-utility');
	$detail_notice = __('*This explanation is a simplified version and not 100% accurate. For more detailed information about this meta tag, please search for it yourself.','hima-art-utility');
	$detail_text_a = __('Checking this setting will output a noindex meta tag, informing search engines not to include this page in their search results.','hima-art-utility');
	$detail_text_b = __('For example, if you have pages that you only want to be viewable via internal links on your site, or if you are publishing similar content such as update information in multiple versions or at different times, you can output this meta tag on previously published pages to prevent search engines from mistakenly identifying multiple pages as duplicates.','hima-art-utility');
	$detail_text_c = __('However, whether or not a page is included in search results is at the discretion of each search engine, so outputting this tag does not necessarily mean that it will not appear in search results. Also, outputting this tag on a page that has already been included in search results does not necessarily mean that it will be excluded from the results.','hima-art-utility');

	$output = '
		<div style="padding:12px;border-bottom: 1px solid #eee;margin-bottom:8px;">
			<h3>'.esc_html( $header_title ).'</h3>
			<details class="accordion" style="margin-left:20px;">
			<summary class="accordion__title" style="cursor: pointer;">'.esc_html( $detail_title ).'</summary>
			<div class="accordion__content" style="border:1px solid #eee;border-radius:4px;padding: 0px 4px;">
				<p style="color:red;font-size:0.8rem;">'.esc_html( $detail_notice ).'</p>
				<p>'.esc_html( $detail_text_a ).'</p>
				<p>'.esc_html( $detail_text_b ).'</p>
				<p>'.esc_html( $detail_text_c ).'</p>
			</div>
			</details>
			<p>'.esc_html( $description_text ).'</p>
		</div>
	';
	
	return $output;
}

function haup_seo_manual_nofollow(){
	$header_title = __('Add NOFOLLOW meta tag','hima-art-utility');
	$description_text = __('Outputs a nofollow tag to the HTML header. Prevent search engines from following links from this page.','hima-art-utility');
	$detail_title = __('The meaning and reason for making this setting','hima-art-utility');
	$detail_notice = __('*This explanation is a simplified version and not 100% accurate. For more detailed information about this meta tag, please search for it yourself.','hima-art-utility');
	$detail_text_a = __('Checking this setting will output a nofollow meta tag, informing search engines not to follow any links on this page.','hima-art-utility');
	$detail_text_b = __('For example, this feature is used when a page contains multiple links unrelated to the main text, and you want to prevent users from following all of them at once.','hima-art-utility');
$detail_text_c = __('However, WordPress often displays related information or lists of content in the same category, so setting all links to nofollow can actually lower your ranking. Therefore, it is recommended not to enable this setting and instead add the nofollow attribute to individual links.','hima-art-utility');
	$output = '
		<div style="padding:12px;border-bottom: 1px solid #eee;margin-bottom:8px;">
			<h3>'.esc_html( $header_title ).'</h3>
			<details class="accordion" style="margin-left:20px;">
			<summary class="accordion__title" style="cursor: pointer;">'.esc_html( $detail_title ).'</summary>
			<div class="accordion__content" style="border:1px solid #eee;border-radius:4px;padding: 0px 4px;">
				<p style="color:red;font-size:0.8rem;">'.esc_html( $detail_notice ).'</p>
				<p>'.esc_html( $detail_text_a ).'</p>
				<p>'.esc_html( $detail_text_b ).'</p>
				<p>'.esc_html( $detail_text_c ).'</p>
			</div>
			</details>
			<p>'.esc_html( $description_text ).'</p>
		</div>
	';
	
	return $output;
}

/***** 個別ページのメタタグとして出力するhaup_custom_seo_meta()関数の生成 *****/
/*** ディスクリプションとして出力する値を決定する ***/
/* カスタムフィールドで設定したディスクリプション値を取得 */
function haup_custom_description() {
	$description = get_post_meta(get_the_ID(), 'meta_description', true);
		$description = wp_strip_all_tags(str_replace(array("\r\n", "\r", "\n"), '', $description));//HTMLタグと改行を削除
	return mb_strimwidth($description, 0, 240, "...", "utf-8");//多すぎても意味がないので先頭の120文字を取得
	}

/* 先頭の120文字をディスクリプションとして自動で取得 */
function haup_auto_description() {
	$post_content = get_post(get_the_ID())->post_content;
	$post_content = esc_html(wp_strip_all_tags(str_replace(array("\r\n", "\r", "\n"), '', $post_content)));//HTMLタグと改行を削除
	return mb_strimwidth($post_content, 0, 240, "...", "utf-8");
	}

/* 条件によって読み込むディスクリプションを切り替えてセットする */
function haup_description_switch() {
	if ( haup_custom_description() ) {
		$description = haup_custom_description();
	} else {
		$description = haup_auto_description();
	}
		return $description;
	}

/* サイト内のページに応じて出力するディスクリプション値を出し分ける */
function haup_description() {
	if ( haup_is_single_without_front() ) { // 記事ページ
		$get_description = haup_description_switch();
	} elseif (is_category()) { // カテゴリーページ
	if (term_description()) { //カテゴリーの説明を入力している場合
		$get_description = term_description();
	} else { //カテゴリーの説明がない場合
		$get_description = single_cat_title('', false)."の記事一覧";
	}
	} elseif (is_tag()) { // タグページ
	if (term_description()) { //タグの説明を入力している場合
		$get_description = term_description();
	} else { //タグの説明がない場合
		$get_description = single_tag_title('', false)."の記事一覧";
	}
	} else { // その他ページ
		$get_description = get_bloginfo('meta_description');
	}
	return $get_description;
	}

/***** noindex nofollowを出力するかどうかを決定し、個別ページへ出力するメタタグを関数化 *****/
function haup_custom_seo_meta() {
$noindex = "";
$nofollow = "";
// カスタムフィールドの設定値の読み込み
		$custom = get_post_custom();
	if(!empty( $custom['meta_keywords'][0])) {
		$keywords = $custom['meta_keywords'][0];
	}
	if(!empty( $custom['is_noindex'][0])) {
		$noindex = $custom['is_noindex'][0];
	}
	if(!empty( $custom['is_nofollow'][0])) {
		$nofollow = $custom['is_nofollow'][0];
	}

//noindexとnofollowの設定によって出力するタグを出し分ける
	//出力タグを変数化してエスケープ
	$noindex_nofollow_data = esc_html('noindex,nofollow');
	$noindex_data = esc_html('noindex,follow');
	$nofollow_data = esc_html('nofollow');

if ( $noindex && $nofollow ) { // 両方チェックしている場合
		echo "\n";
		echo '<meta name="robots" content="';
		echo esc_html($noindex_nofollow_data);
		echo '">';
		echo "\n";
	} elseif ( $noindex && !$nofollow) { // noindexだけチェックしている場合
		echo "\n";
		echo '<meta name="robots" content="';
		echo esc_html($noindex_data);
		echo '>';
		echo "\n";
	} elseif ( $nofollow && !$noindex ) { // nofollowだけチェックしている場合
		echo "\n";
		echo '<meta name="robots" content="';
		echo esc_html($nofollow_data);
		echo '">';
		echo "\n";
	}

/*** キーワード値の決定 ***/
	//値を変数化してエスケープ
	if(isset($keywords)){
	$escd_keywords = esc_html($keywords);
	}

if ( haup_is_single_without_front() ) { // 記事ページ
	if (!empty($keywords)){
		echo "\n";
		echo '<meta name="keywords" content="';
		echo esc_html($escd_keywords);
		echo '">';
		echo "\n";
}
}
	echo "\n";
	echo '<meta name="description" content="';
	echo esc_html(haup_description());
	echo '">';
	echo "\n";
}

/*** titleタグの書き換え ***/
/* titleタグはWordPress標準で出力されるため、haup_custom_seo_meta()とは別に処理 */
function haup_overwrite_seo_title( $title ){
	$home_title = get_bloginfo('name');

	//SEOタイトルに入力があるかで判断
	$custom = get_post_custom();
	if(!empty( $custom['seo_title'][0])) {
		$page_title = $custom['seo_title'][0];
	}else{
		$page_title = wp_strip_all_tags(get_the_title());
	}

	//個別ページのタイトルに続く文字列の指定
	//区切り文字の種類を取得して設定
	$sepatate_text = '';

	if(isset( GetOP01_optimize()['after-title-separate-text'] )){
		if(GetOP01_optimize()['after-title-separate-text'] =='1'){
			$separate_text = '|';
		}else if(GetOP01_optimize()['after-title-separate-text'] =='2'){
			$separate_text = '-';
		}else if(GetOP01_optimize()['after-title-separate-text'] =='3'){
			$separate_text = '/';
		}else{
			$separate_text = '|';
		}
	}else{
		$separate_text = '|';
	}

	//任意の文字列に入力されている値を取得
	$any_strings = '';

	if(isset( GetOP01_optimize()['after-title-any-string'] )){
	$any_strings = GetOP01_optimize()['after-title-any-string'];
	}

	//任意の文字列に入力がなかったらサイトタイトルをセット
	if( empty( $any_strings )){
		$after_title_text = $home_title;
	}else{
		$after_title_text = $any_strings;
	}

	//タイトル後に出力する文字列を設定
	$after_text = '';

	if(isset( GetOP01_optimize()['select-after-title-text'] )){
		if(GetOP01_optimize()['select-after-title-text'] == '1'){//サイトタイトルを選択
			$after_text = $separate_text.$home_title;
		}else if(GetOP01_optimize()['select-after-title-text'] == '2'){//キャッチフレーズを選択
			$after_text = $separate_text.'キャッチフレーズ';
		}else if(GetOP01_optimize()['select-after-title-text'] == '3'){//任意の文字列を選択
			//$after_text = $separate_text.$after_title_text;
			$after_text = $separate_text.$after_title_text;
		}else{
			$after_text =  $separate_text.$home_title;
		}
	}else{
		$after_text =  $separate_text.$home_title;
	}

	//タイトルの後に文字列を出力するかで切り分け
	$single_title = $page_title;

	if( isset( GetOP01_optimize()['output-after-title-text'] ) && GetOP01_optimize()['output-after-title-text'] == 1){
		$single_title = $page_title.$after_text;
	}else{
		$single_title = $page_title;
	}

	//アーカイブの場合はアーカイブタイトルを取得
	//アーカイブタイトルからspanタグを除く
	add_filter( 'get_the_archive_title_prefix', '__return_false' );

	$archive_title = esc_html(get_the_archive_title());

	// タームのIDを取得
	$term_id = get_queried_object_id(); // 現在のタームのIDを取得
	$term = get_term($term_id); // タームオブジェクトを取得

	// タームが存在するか確認
	if ($term && !is_wp_error($term)) {
		// タクソノミーの表示名を取得
		$taxonomy = get_taxonomy($term->taxonomy);

		if ($taxonomy) { // タクソノミーが存在するか確認
			$taxonomy_name = esc_html($taxonomy->labels->name); // タクソノミーの表示名を出力
		} else {
			// タクソノミーが存在しない場合の処理
			$taxonomy_name = '';
		}
	} else {
		// タームが存在しない場合の処理
		$taxonomy_name = '';
	}

	//ページの条件に応じて出力する内容を指定
	if(is_archive()){//タクソノミーの表示名-ターム名
		$title = $taxonomy_name.'-'.$archive_title.$separate_text.$home_title;
	}else  if(is_front_page() || is_home()){
		$title = $home_title;
	}elseif(haup_is_single_without_front()){//個別ページ
		$title = $single_title;
	}else{//上記の条件に当てはまらない場合
		$title = $home_title;
	}

	return esc_html($title);
}
add_filter( 'pre_get_document_title', 'haup_overwrite_seo_title' );

/********** SEOフィールドの値をカラムへ表示＆クイック編集で編集可能にする **********/
/*** 一覧へSEOフィールドのカラムを表示 ***/
/* 一覧へカラムを作成 */
function haup_manage_posts_seo_field_columns($columns) {

	if(haup_is_single()){
		$columns['seo_title'] = __('Title','hima-art-utility');
		$columns['meta_description'] = __('Description','hima-art-utility');
		$columns['meta_keywords'] = __('Keyword','hima-art-utility');
		$columns['is_noindex'] = __('Noindex','hima-art-utility');
		$columns['is_nofollow'] = __('Nofollow','hima-art-utility');
	}

	return $columns;
}
add_filter( 'manage_posts_columns', 'haup_manage_posts_seo_field_columns' );

function haup_manage_pages_seo_field_columns($columns) {

	$columns['seo_title'] = __('Title','hima-art-utility');
	$columns['meta_description'] = __('Description','hima-art-utility');
	$columns['meta_keywords'] = __('Keyword','hima-art-utility');
	$columns['is_noindex'] = __('Noindex','hima-art-utility');
	$columns['is_nofollow'] = __('Nofollow','hima-art-utility');

	return $columns;
}
add_filter( 'manage_pages_columns', 'haup_manage_pages_seo_field_columns' );

/* データの呼び出し */
function haup_add_seo_field_column($column_name, $post_id) {
	/*ディスクリプション呼び出し*/
	if( $column_name == 'meta_description' ) {
		$stitle = get_post_meta($post_id, 'meta_description', true);
	}
	/*キーワード呼び出し*/
	if( $column_name == 'meta_keywords' ) {
		$stitle = get_post_meta($post_id, 'meta_keywords', true);
	}
	/* SEOタイトル呼び出し */
	if( $column_name == 'seo_title' ) {
		$stitle = get_post_meta($post_id, 'seo_title', true);
	}

	/* Noindex呼び出し */
	if( $column_name == 'is_noindex' ) {
		$cf_data = get_post_meta( $post_id, 'is_noindex', true );
		if($cf_data == '1'){
			$stitle = __('〇','hima-art-utility');
		}else{
			$stitle = '';
		}
	}

	/* Nofollow呼び出し */
	if( $column_name == 'is_nofollow' ) {
		$cf_data = get_post_meta( $post_id, 'is_nofollow', true );
		if($cf_data == '1'){
			$stitle = __('〇','hima-art-utility');
		}else{
			$stitle = '';
		}
	}

	if ( isset($stitle) && $stitle ) {
		echo esc_attr($stitle);
	} else {
		echo '';
	}
}
add_action( 'manage_posts_custom_column', 'haup_add_seo_field_column', 10, 2 );
add_action( 'manage_pages_custom_column', 'haup_add_seo_field_column', 10, 2 );

/*** 一覧へ「抜粋（作業用）」のカラムを表示 ***/
/* 一覧へカラム作成 */
function haup_add_temp_excerpt_column_to_post_list($columns) {
	$new_columns = array();

	foreach ($columns as $key => $value) {
		$new_columns[$key] = $value;
		if ($key === 'meta_description') {
			$new_columns['temp_excerpt'] = esc_html__('Post Excerpt', 'hima-art-utility');
		}
	}

	return $new_columns;
}
add_filter('manage_posts_columns', 'haup_add_temp_excerpt_column_to_post_list');

/* データの呼び出し */
function haup_display_combined_excerpt_value($column_name, $post_id) {
	if ($column_name === 'temp_excerpt') {
		$temp_excerpt = get_post_meta($post_id, 'temp_excerpt', true);
		$post_excerpt = get_the_excerpt($post_id);

		if(!empty($temp_excerpt)){
			echo esc_html($temp_excerpt);
		}else if(has_excerpt($post_id)) {
			echo esc_html($post_excerpt);
		}else{
			echo '';
		}
	}
}
add_action('manage_posts_custom_column', 'haup_display_combined_excerpt_value', 10, 2);


/*** meta descriptionへ出力されるデータのカラムを表示 ***/
/* カラムを追加 */
function haup_add_output_meta_description_column($columns) {

	$column_text = __('Meta Description','hima-art-utility');

	$new_columns = array();
	foreach ($columns as $key => $value) {
		$new_columns[$key] = $value;
		if ($key === 'temp_excerpt') {
			$new_columns['output_description_column'] = esc_html( $column_text );
		}
	}
	return $new_columns;
}

add_filter('manage_posts_columns', 'haup_add_output_meta_description_column');

/* データを表示 */
function haup_output_meta_description_text($column_name, $post_id) {

	if ($column_name === 'output_description_column') {

		//HAUPのSEOにある説明文に入力した値
		$custom_meta = get_post_meta($post_id, 'meta_description', true);
		//編集画面の「抜粋」に入力があればその値、なければ先頭55文字
		$excerpt = get_the_excerpt($post_id);

		if(!empty( $custom_meta )){//HAUPのSEOにある説明文に入力したデータ
			echo '<span style="color:blue;font-weight:700;">[HAUP Meta]</span><br>' .esc_html($custom_meta);
		}else if( has_excerpt($post_id) ){//編集画面の「抜粋」に入力したデータ
			echo '<span style="font-weight:700;">[Post Excerpt]</span><br>' .esc_html($excerpt);
		}else{//どちらにも入力がない場合
			echo '<span style="color:red;font-weight:700;">[WP Create]</span><br>' .esc_html($excerpt);
		}
	}
}
add_action('manage_posts_custom_column', 'haup_output_meta_description_text', 10, 2);

/***** クイック編集で変更可能にする *****/
/*** SEOフィールド ***/
/* クイック編集にフィールド表示 */
function haup_display_seo_custom_field_quickedit( $column_name, $post_type ) {
	static $print_nonce = TRUE;
		if ( $print_nonce ) {
			$print_nonce = FALSE;
			wp_nonce_field( 'quick_edit_action', $post_type . '_edit_nonce' ); //CSRF対策
		}

?>
<fieldset class="inline-edit-col-right inline-custom-meta">
	<div class="inline-edit-col column-custom-meta">
	<label class="inline-edit-group">
	<?php
	switch ( $column_name ) {
		//SEOタイトルの表示
		case 'seo_title':
	?>
		<span class="title"><?php esc_html_e('Title','hima-art-utility'); ?></span><textarea name="seo_title" cols="50" rows="1"></textarea><?php
	break;
		//ディスクリプションの表示
		case 'meta_description':
	?>
		<span class="title"><?php esc_html_e('Description','hima-art-utility'); ?></span><textarea name="meta_description" cols="50" rows="5"></textarea><?php
	break;
		//キーワードの表示
		case 'meta_keywords':
	?>
		<span class="title"><?php esc_html_e('Keyword','hima-art-utility'); ?></span><textarea name="meta_keywords" cols="50" rows="1"></textarea><?php
	break;

		//noindexの表示
		case 'is_noindex':
		?>
		<span class="title"><?php esc_html_e('Noindex','hima-art-utility'); ?></span>
		<input type="checkbox" name="is_noindex" value="1">
		<?php
		break;

		//nofollowの表示
		case 'is_nofollow':
		?>
		<span class="title"><?php esc_html_e('Nofollow','hima-art-utility'); ?></span>
		<input type="checkbox" name="is_nofollow" value="1">
		<?php
		break;
	}
	?>
	</label>
	</div>
</fieldset>
<?php
}
add_action( 'quick_edit_custom_box', 'haup_display_seo_custom_field_quickedit', 10, 2 );

/* 既に入力済のカスタムフィールド値を表示 */
/* これはSEOフィールドと抜粋の両方に作用 */
function haup_seo_field_admin_edit_foot($post_id , $post_type='' ) {
	global $post_type;
if ( is_null( $post_type ) ) {return;}//PHP8.0の空判定

	$slug = get_post_type( $post_id ); //他の一覧ページで動作しないように投稿タイプの指定をする

	if ( $post_type == $slug ) {
	// phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript
	echo '<script type="text/javascript" src="' .esc_html(plugin_dir_url( __FILE__ )).'seo-quick-edit.js', '"></script>';
	}
}
add_action('admin_footer-edit.php', 'haup_seo_field_admin_edit_foot');

/* 新たに入力した値へ更新 */
function haup_seo_data_quick_save( $post_id ) {
	$slug = get_post_type( $post_id ); 

	if ( $slug !== get_post_type( $post_id ) ) {
		return;
	}
	if ( !current_user_can( 'edit_post', $post_id ) ) {
		return;
	}

	//nonce検証
	$_POST += array("{$slug}_edit_nonce" => '');

	//nonceフィールドがなければ無視する
	if ( !isset( $_POST["{$slug}_edit_nonce"] ) ){
		return;
	}

	//nonce検証に失敗したら無視する
		if ( !wp_verify_nonce( sanitize_text_field(wp_unslash($_POST["{$slug}_edit_nonce"])), 'quick_edit_action' ) ) {
			return;
		}

	//SEOタイトル
	if ( isset( $_REQUEST['seo_title'] ) ) {
			update_post_meta( $post_id, 'seo_title', sanitize_text_field(wp_unslash($_REQUEST['seo_title'])) );
		}
	//説明文
		if ( isset( $_REQUEST['meta_description'] ) ) {
			update_post_meta( $post_id, 'meta_description', sanitize_text_field(wp_unslash($_REQUEST['meta_description'])) );
		}
	//キーワード
		if ( isset( $_REQUEST['meta_keywords'] ) ) {
			update_post_meta( $post_id, 'meta_keywords', sanitize_text_field(wp_unslash($_REQUEST['meta_keywords'])) );
		}

	// is_noindex
	// チェックが入っていれば '1'、入っていなければ '0' (または空)
	$noindex_value = ( isset( $_REQUEST['is_noindex'] ) && $_REQUEST['is_noindex'] === '1' ) ? '1' : '0';
	update_post_meta( $post_id, 'is_noindex', $noindex_value );

	// is_nofollow
	$nofollow_value = ( isset( $_REQUEST['is_nofollow'] ) && $_REQUEST['is_nofollow'] === '1' ) ? '1' : '0';
	update_post_meta( $post_id, 'is_nofollow', $nofollow_value );

}
add_action( 'save_post', 'haup_seo_data_quick_save' );


/*** 抜粋 ***/
/* クイック編集にフィールド表示 */
function haup_add_temp_excerpt_field_to_quickedit($column_name, $post_type) {
if ($column_name === 'temp_excerpt') {

?>
	<fieldset class="inline-edit-col-right inline-custom-meta">
		<div class="inline-edit-col column-custom-meta">
			<label class="inline-edit-group">
				<span class="title"><?php esc_html_e('Post Excerpt', 'hima-art-utility'); ?></span>
				<textarea name="temp_excerpt" cols="50" rows="1"></textarea>
			</label>
		</div>
	</fieldset>
<?php

}
}
add_action('quick_edit_custom_box', 'haup_add_temp_excerpt_field_to_quickedit', 10, 2);


/* 新たに入力した値へ更新 */
function haup_save_temp_excerpt_from_quickedit($post_id) {
	if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
		return;
	}

	if (!current_user_can('edit_post', $post_id)) {
		return;
	}

	// ノンス（nonce）検証
	$slug = get_post_type($post_id);
	if (!isset($_POST["{$slug}_edit_nonce"]) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST["{$slug}_edit_nonce"])), 'quick_edit_action')) {
		return;
	}

	if (isset($_POST['temp_excerpt'])) {
		update_post_meta($post_id, 'temp_excerpt', sanitize_text_field(wp_unslash($_POST['temp_excerpt'])));
	}
}
add_action('save_post', 'haup_save_temp_excerpt_from_quickedit');

/* 保存したデータを同期させる */
function haup_sync_excerpt_on_save($post_id) {
	if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
		return;
	}

	if (wp_is_post_revision($post_id)) {
		return;
	}

	if (!current_user_can('edit_post', $post_id)) {
		return;
	}

	// 無限ループを防ぐためのフラグ
	if (did_action('save_post') > 1) {
		return;
	}

	// クイック編集のAjaxリクエストか確認
	if (defined('DOING_AJAX') && DOING_AJAX && isset($_POST['action']) && $_POST['action'] === 'inline-save') {
		// ノンス（nonce）検証
		$slug = get_post_type($post_id);
		if (!isset($_POST["{$slug}_edit_nonce"]) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST["{$slug}_edit_nonce"])), 'quick_edit_action')) {
			return;
		}

		// temp_excerptが送信された場合
		if (isset($_POST['temp_excerpt'])) {
			$temp_excerpt = sanitize_text_field(wp_unslash($_POST['temp_excerpt']));

			// save_postフックを一時的に削除し、無限ループを回避
			remove_action('save_post', 'haup_sync_excerpt_on_save');

			// 空文字を明示的に更新
			wp_update_post(array(
				'ID' => $post_id,
				'post_excerpt' => $temp_excerpt,
			));

			// save_postフックを再度追加
			add_action('save_post', 'haup_sync_excerpt_on_save');
		}
	}
}
add_action('save_post', 'haup_sync_excerpt_on_save');


/***** 管理画面上のスタイル *****/
function haup_admin_seo_data_column_style_init(){
$custom_css_pre = '
/* HAUP Seo Data Column Width */
body.edit-php #meta_description {width:20%;}
body.edit-php #meta_keywords {width: 15%;}
body.edit-php #seo_title {width: 10%;}
body.edit-php #is_noindex {width: 10%;}
body.edit-php #is_nofollow {width: 10%;}
.inline-edit-col .column-meta_description {width: 100%;}
.inline-edit-col .column-meta_keywords {width: 100%;}
.inline-edit-col .column-seo_title {width: 100%;}
.inline-edit-col .column-is_noindex {width: 100%;}
.inline-edit-col .column-is_nofollow {width: 100%;}
body.edit-php #output_description_column{width: 20%;}
body.edit-php #temp_excerpt{width: 20%;}
';

	//スタイルコードを改行なしで整形する
	$custom_css = str_replace(PHP_EOL, '', $custom_css_pre);

	wp_add_inline_style('haup-only-admin-style', $custom_css );
}
add_action('admin_enqueue_scripts','haup_admin_seo_data_column_style_init');