<?php if ( !defined( 'ABSPATH' ) ) exit;//PHPの宣言と直接アクセスの拒否
/*** 設定を追加したらサニタイズ関数の条件も追加すること ***/

/* セクションID haumenu_define_section_id_02_optimize() */
/* タブのスラグ haumenu_define_tab_slug_02_optimize() */
/* $option_name 設定名 haumenu_define_option_name_02_optimize() */
/* get_option GetOP02_optimize() */

/***** 親設定の有効／無効に合わせて子設定の表示方法を変更する *****/
/* 関数名・設定名は画面ごとに変えること（関数重複を防ぐ） */
/* add_action('admin_notices', 'current_pagehook');を追加してページ名を取得し、$page_fooksuffixの値を変える */
/* 連動マップ（ID => セレクター）の項目を編集する */

function haup_child_setting_view_control_02_optimize( $hook_suffix ) {
	//ページフックにより出力を判断
	$page_fooksuffix = 'ha-utilitiy_page_haumenu_page_optimize';

	if ( $page_fooksuffix !== $hook_suffix ) {
		return;
	}

	//メインスクリプトのハンドル
	$handle = 'haup-child-setting-control-js';

	// メインスクリプトが登録されていなければ終了(スクリプトの読み込みはmain-menu.phpで記述)
	if ( ! wp_script_is( $handle, 'registered' ) ) {
		return;
	}

	//設定名
	$set_name = haumenu_define_option_name_02_optimize();

	// 連動マップ（ID => セレクター）
	// 1つのIDに対して複数のCSSクラスを指定する（1つなら1行）
	$dependency_map = array(
		//$set_name . 'enable-set-revisions' => array(
			//'.set-revisions-num-wrapper', // リビジョン数
			//'.set-revisions-posttype-wrapper', // 指定する投稿タイプ
		//),

	);

	$inner_js = "";
	foreach ( $dependency_map as $id => $selectors ) {
		foreach ( (array) $selectors as $selector ) {
			// translators: %s stands for the CSS Class & ID.
			$inner_js .= sprintf(
				"haup_apply_dependency('%s', '%s');\n",
				esc_js( $id ),
				esc_js( $selector )
			);
		}
	}

	if ( $inner_js ) {
		$js_code = "if (window.haup_apply_dependency) {\n" . $inner_js . "}";
		// 第3引数を 'after' にすることで、本体JSの直後に出力
		wp_add_inline_script( $handle, $js_code, 'after' );
	}
}
add_action( 'admin_enqueue_scripts', 'haup_child_setting_view_control_02_optimize', 20 );

/*** スクリプトの遅延読み込み ***/
/* 項目の追加とデータの更新 */
function haumenu_init_field_is_use_defer_script(){
//項目の追加
	add_settings_field(
		'use-defer-script',  // $id フィールドを識別するスラッグ名（一意）
		__('Lazy loading of scripts','hima-art-utility'), // 設定タイトル
		'haumenu_is_use_defer_script', // 設定項目のHTMLを出力する関数名
		haumenu_define_tab_slug_02_optimize(), //表示させるタブのスラグ
		haumenu_define_section_id_02_optimize(), //セクションID
		array( 'class' => 'ha-settings-separate' )
	);

}

add_action( 'admin_init', 'haumenu_init_field_is_use_defer_script' );

/* 入力フォーム */
function haumenu_is_use_defer_script() {
	$set_name = haumenu_define_option_name_02_optimize();// 設定名
	$options = get_option( $set_name );
	$option_name = 'use-defer-script'; //個別配列名

	//テーブルに値がなかった場合の措置（PHP8.x以降への対応）
	if(isset($options[$option_name])){
		$checked = $options[$option_name];
	}else{
		$checked = '';
	}
?>
<label>
	<input type="checkbox" id="<?php echo esc_html($set_name . $option_name ); ?>" name="<?php echo esc_html($set_name . '[' .$option_name. ']'); ?>" class="wppd-ui-toggle" <?php checked( $checked , 1 ); ?> value="1">
	<p><?php esc_html_e('Add the defer attribute to the output script tag to delay load, prevent rendering blocking, and ensure smooth page rendering.','hima-art-utility'); ?></p>
</label>
	<p class="haup-admin-bk"><?php esc_html_e('Note: Although it is effective for improving the display speed, it may not work properly depending on the plugin or custom code.','hima-art-utility'); ?></p>
<?php
}

/*** .htaccessへの追記 ***/
/* 項目の追加とデータの更新 */
function haumenu_init_field_add_htaccess_su_code(){
//項目の追加
	add_settings_field(
		'add-htaccess-su-code',  // $id フィールドを識別するスラッグ名（一意）
		__('Add acceleration code to .htaccess file','hima-art-utility'), // 設定タイトル
		'haumenu_add_htaccess_su_code', // 設定項目のHTMLを出力する関数名
		haumenu_define_tab_slug_02_optimize(), //表示させるタブのスラグ
		haumenu_define_section_id_02_optimize(), //セクションID
		array( 'class' => 'ha-settings-separate' )
	);

}

add_action( 'admin_init', 'haumenu_init_field_add_htaccess_su_code' );

/* 入力フォーム */
function haumenu_add_htaccess_su_code() {
	$set_name = haumenu_define_option_name_02_optimize();// 設定名
	$options = get_option( $set_name );
	$option_name = 'add-htaccess-su-code'; //個別配列名

	//テーブルに値がなかった場合の措置（PHP8.x以降への対応）
	if(isset($options[$option_name])){
		$checked = $options[$option_name];
	}else{
		$checked = '';
	}

	//機能が使えるかどうかの判定
	$htaccess_file = ABSPATH . '.htaccess';
	$is_writable = ( file_exists( $htaccess_file ) && is_writable( $htaccess_file ) );
	if ( $is_writable ) {
		$enabled_message_text = __('This feature is available on this site.','hima-art-utility');
		$enabled_message = '<p style="color:green;font-weight:700;">'.$enabled_message_text.'</p>';
	} else {
		$enabled_message_text = __('You are either using a server where the .htaccess file does not exist, or you do not have write permissions to the .htaccess file, so you cannot use this feature.','hima-art-utility');
		$enabled_message = '<p style="color:red;font-weight:700;">'.$enabled_message_text.'</p>';
	}

	//機能が使えない場合には選択できないようにする
	$disabled_attr = ! $is_writable ? 'disabled' : '';
?>
<label>
	<input type="checkbox" id="<?php echo esc_html($set_name . $option_name ); ?>" name="<?php echo esc_html($set_name . '[' .$option_name. ']'); ?>" class="wppd-ui-toggle" <?php checked( $checked , 1 ); ?> value="1" <?php echo esc_html( $disabled_attr ); ?>>
	<?php esc_html_e('Mainly review the cache settings on the browser side and add setting code to the .htaccess file to help display the site at high speed.','hima-art-utility'); ?>
	<?php echo wp_kses_post( $enabled_message ); ?>
</label>
<p class="haup-admin-bk"><?php esc_html_e('After enabling this setting, open "Settings" → "Permalinks" on the management screen and click "Save changes" without doing anything.','hima-art-utility'); ?></p>
<details class="accordion"  style="margin: 5px 0px 0px 0px;overflow: hidden;">
<summary class="accordion__title" style="cursor: pointer;"><?php esc_html_e('View detailed description','hima-art-utility'); ?></summary>
<div class="accordion__content">
<p><?php esc_html_e('It is a speed-up countermeasure code that comes out when searching with the keyword ".htaccess speedup" for a long time.','hima-art-utility'); ?></p>
<p><?php esc_html_e('However, although I have been adding this code for many years and running it, I do not know if I can get a sensible speed-up effect.','hima-art-utility'); ?></p>
<p><?php esc_html_e('By enabling this function, the following code will be added to the .htaccess file, but if you are not dissatisfied with the current display state, you may not need to use it.','hima-art-utility'); ?></p>
<pre>
<code># ETags(Configure entity tags) を無視する設定
&lt;ifModule mod_headers.c&gt;
Header unset ETag
&lt;/ifModule&gt;
FileETag None

# Enable Keep-Alive を設定
&lt;IfModule mod_headers.c&gt;
Header set Connection keep-alive
&lt;/IfModule&gt;

# MIME Type 追加
&lt;IfModule mime_module&gt;
AddType text/cache-manifest .appcache
AddType image/x-icon .ico
AddType image/svg+xml .svg
AddType application/x-font-ttf .ttf
AddType application/x-font-woff .woff
AddType application/x-font-woff2 .woff2
AddType application/x-font-opentype .otf
AddType application/vnd.ms-fontobject .eot
&lt;/IfModule&gt;

# プロクシキャッシュの設定（画像とフォントをキャッシュ）
&lt;IfModule mod_headers.c&gt;
&lt;FilesMatch "\.(ico|jpe?g|png|gif|svg|swf|pdf|ttf|woff|woff2|otf|eot)$"&gt;
Header set Cache-Control "max-age=604800, public"
&lt;/FilesMatch&gt;
# プロキシサーバーが間違ったコンテンツを配布しないようにする
Header append Vary Accept-Encoding env=!dont-vary
&lt;/IfModule&gt;

# ブラウザキャッシュの設定
&lt;IfModule mod_headers.c&gt;
&lt;ifModule mod_expires.c&gt;
ExpiresActive On

# キャッシュ初期化（1秒に設定）
ExpiresDefault "access plus 1 seconds"

# MIME Type ごとの設定
ExpiresByType text/css "access plus  1 year"
ExpiresByType text/js "access plus  1 year"
ExpiresByType text/javascript "access plus  1 year"
ExpiresByType image/gif "access plus  1 year"
ExpiresByType image/jpeg "access plus  1 year"
ExpiresByType image/png "access plus  1 year"
ExpiresByType image/svg+xml "access plus 1 year"
ExpiresByType image/webp "access plus  1 year"
ExpiresByType application/pdf "access plus  1 year"
ExpiresByType application/javascript "access plus  1 year"
ExpiresByType application/x-javascript "access plus  1 year"
ExpiresByType application/x-shockwave-flash "access plus 1 year"
ExpiresByType application/x-font-ttf "access plus 1 year"
ExpiresByType application/x-font-woff "access plus 1 year"
ExpiresByType application/x-font-woff2 "access plus 1 year"
ExpiresByType application/x-font-opentype "access plus 1 year"
ExpiresByType application/vnd.ms-fontobject "access plus 1 year"
&lt;/IfModule&gt;
&lt;/IfModule&gt;

# Gzip圧縮の設定
&lt;IfModule mod_deflate.c&gt;
SetOutputFilter DEFLATE

# 古いブラウザでは無効
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch \bMSIE\s(7|8) !no-gzip !gzip-only-text/html

# 画像など圧縮済みのコンテンツは再圧縮しない
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png|webp|ico|eot|woff|woff2)$ no-gzip dont-vary

AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/js
AddOutputFilterByType DEFLATE image/svg+xml
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/atom_xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/x-httpd-php
AddOutputFilterByType DEFLATE application/x-font-ttf
AddOutputFilterByType DEFLATE application/x-font-opentype
&lt;/IfModule&gt;</code>
</pre>
<p style="color:red;font-weight:bold;"><?php esc_html_e('This function adds code to the .htaccess file. Please note that it does not check whether the same code already exists.','hima-art-utility'); ?></p>
<p style="color:red;font-weight:bold;"><?php esc_html_e('This setting is valid only for WordPress sites (Apache or compatible servers) with .htaccess files. Otherwise, problems may occur.','hima-art-utility'); ?></p>
</div>
</details>


<?php
}