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

/* ログイン後に「管理者メールアドレス」へ通知 */
/* 以下はロケールによる翻訳の変更の参考にした */
/* https://stackoverflow.com/questions/66554542/how-to-change-the-language-of-the-email-dynamically-according-to-users-language */
function haup_send_login_notification_to_admin($user_login, $user) {
	$locale = get_locale();
	switch_to_locale($locale);

	// サイト名とURLを変数化
	$site_title = get_bloginfo('name');
	$site_url = get_home_url();

	// 宛先
	$admin_email = sanitize_email(get_option('admin_email'));

	// 件名
	$text_a = __('Login Notification', 'hima-art-utility');
	$subject = wp_strip_all_tags($text_a . '「' . $site_title . '」');

	// 本文
	$text_b = __('User Name', 'hima-art-utility');
	$text_c = __('is', 'hima-art-utility');
	$text_d = __('logged in to the site.', 'hima-art-utility');
	$text_e = __('Login From:', 'hima-art-utility');
	$text_f = __('This email is sent to confirm whether the email address registered in the "Administrator Email Address" field on the settings screen can be delivered:', 'hima-art-utility');
    $text_g = __('If there is little possibility of unauthorized login, you can delete this email.', 'hima-art-utility');

	// メッセージ作成

	$remote_addr = '';
	$user_agent = '';

	if(isset( $_SERVER['REMOTE_ADDR'] )){
		$remote_addr = sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR']));
	}

	if(isset( $_SERVER['HTTP_USER_AGENT'] )){
		$user_agent = sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT']));
	}

	$message = wp_strip_all_tags($text_b . '「' . $user_login . '」' . $text_c . '「' . $site_title . '(' . $site_url . ')」' . $text_d . "\n\n");
	$message .= $text_e . "\n\n" . sanitize_text_field(wp_unslash( $remote_addr ) ). "\n\n" . '-' . wp_strip_all_tags(wp_unslash( $user_agent )) . '-' . "\n\n";
	$message .= $text_f . "\n\n" . $text_g;

	// メール送信
	$error_log_message = __('Login notification to administrator failed','hima-art-utility');
	if ( ! wp_mail($admin_email, $subject, $message) ) {
		//error_log( esc_html( $error_log_message ) . $subject);
		return ;
	}

	restore_previous_locale();
}

add_action('wp_login', 'haup_send_login_notification_to_admin', 10, 2);

/*** 自動ログイン時にも発火するようにする（テスト） 20250224 ***/
add_action('wp_authenticate', function($user) {
	if (isset($user->user_login)) {
		haup_send_login_notification_to_admin($user->user_login, $user);
	}
}, 10, 1);