@charset "UTF-8";
/*
    Template: swell
    Theme Name: SWELL CHILD
    Theme URI: https://swell-theme.com/
    Description: SWELLの子テーマ
    Version: 1.0.0
    Author: LOOS WEB STUDIO
    Author URI: https://loos-web-studio.com/

    License: GNU General Public License
    License URI: http://www.gnu.org/licenses/gpl.html
*/


/**
 * ==========================================================
 * Snow Monkey Forms：ファイル項目の拡張子制限
 * ==========================================================
 */

/**
 * 許可する拡張子と MIME タイプ
 * キー＝拡張子（| 区切り）、値＝MIMEタイプ
 */
function my_smf_allowed_mimes() {
	return array(
		// 画像
		'jpg|jpeg|jpe' => 'image/jpeg',
		'gif'          => 'image/gif',
		'png'          => 'image/png',
		'webp'         => 'image/webp',
		// 文書・PDF
		'pdf'          => 'application/pdf',
		'doc'          => 'application/msword',
		'docx'         => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
		'xls'          => 'application/vnd.ms-excel',
		'xlsx'         => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
		'ppt'          => 'application/vnd.ms-powerpoint',
		'pptx'         => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
		// 音声・動画
		'mp3'          => 'audio/mpeg',
		'm4a'          => 'audio/x-m4a',
		'ogg'          => 'audio/ogg',
		'wav'          => 'audio/x-wav',
		'mp4'          => 'video/mp4',
		'm4v'          => 'video/x-m4v',
		'mov'          => 'video/quicktime',
	);
}

/**
 * サーバー側の制限：Snow Monkey Forms の送信時だけ許可リストを差し替える
 */
add_filter(
	'rest_pre_dispatch',
	function ( $result, $server, $request ) {
		if (
			'/snow-monkey-form/v1/view' === $request->get_route()
			&& 'POST' === $request->get_method()
		) {
			add_filter(
				'upload_mimes',
				function () {
					return my_smf_allowed_mimes();
				},
				9999
			);
		}
		return $result;
	},
	10,
	3
);

/**
 * 画面側の補助：ファイル選択ダイアログで対象の拡張子だけを表示する
 */
add_action(
	'wp_footer',
	function () {
		if ( ! wp_script_is( 'snow-monkey-forms', 'enqueued' ) ) {
			return;
		}
		$exts = array();
		foreach ( array_keys( my_smf_allowed_mimes() ) as $key ) {
			foreach ( explode( '|', $key ) as $ext ) {
				$exts[] = '.' . $ext;
			}
		}
		?>
		<script>
		document.addEventListener( 'click', function ( e ) {
			var input = e.target.closest ? e.target.closest( '.smf-file-control__control' ) : null;
			if ( input ) {
				input.setAttribute( 'accept', <?php echo wp_json_encode( implode( ',', $exts ) ); ?> );
			}
		}, true );
		</script>
		<?php
	}
);

/**
 * 非対応の拡張子を選んだときのエラー文言
 */
add_filter(
	'snow_monkey_forms/validator/error_message',
	function ( $message, $validation_name, $name ) {
		if ( 'uploaded' === $validation_name ) {
			return 'このファイル形式はアップロードできません。画像（jpg / png / gif / webp）、文書（pdf / Word / Excel / PowerPoint）、音声・動画（mp3 / m4a / ogg / wav / mp4 / m4v / mov）のファイルを選択してください。';
		}
		return $message;
	},
	10,
	3
);