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

/* ログイン後にログインしたユーザーのメールアドレスへ通知 */
function haup_send_login_notification_to_user($user_login, $user) {
	$locale = get_user_locale();
	switch_to_locale($locale);

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

	// 宛先
	$user_email = sanitize_email($user->user_email);

	// 件名
	$text_a = __('Did you log in to?', 'hima-art-utility');
	$subject = wp_strip_all_tags('「' . $site_title . '」' . $text_a);

	// 本文
	$text_b = __('logged in to the site.', 'hima-art-utility');
	$text_c = __('Login From:', 'hima-art-utility');
	$text_d = __('This email was sent for confirmation purposes so you may discard it.', 'hima-art-utility');
	$text_e = __('If you receive this email but do not remember logging in, this may indicate an unauthorized login. Please reply to this email to notify the site administrator.', 'hima-art-utility');

	// メッセージ作成
	$message = wp_strip_all_tags('「' . $site_title . '(' . $site_url . ')」' . $text_b . "\n\n");
	
	$user_agent = '';
	if(isset( $_SERVER['HTTP_USER_AGENT'] )){
		$user_agent = sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT']));
	}

	$remote_addr = '';
	if(isset( $_SERVER['REMOTE_ADDR'] )){
		$remote_addr = sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR']));
	}
	
	$message .= $text_c . "\n\n" . sanitize_text_field(wp_unslash( $remote_addr )). "\n\n" . '-' . wp_strip_all_tags(wp_unslash( $user_agent) ) . '-' . "\n\n";
	$message .= $text_d . "\n\n" . $text_e;

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

	restore_previous_locale();
}
add_action('wp_login', 'haup_send_login_notification_to_user', 10, 2);


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