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

/*** ファイルエディター変更時にメール通知 ***/
function haup_change_code_send_mail() {
	// actionが一致する場合のみ実行（念のためのガード）
	if (isset($_POST['action']) && $_POST['action'] === 'edit-theme-plugin-file') {

		// 1. 権限確認
		if (!current_user_can('edit_themes') && !current_user_can('edit_plugins')) {
			return;
		}

		// 2. 許可IPアドレスの判定
		$options = get_option('hautility-option-01-security');
		$ip_string = $options['setting-restrict-access-ip'] ?? '';
		$current_ip = $_SERVER['REMOTE_ADDR'];

		if (!empty($ip_string)) {
			// コンマ区切りの文字列を配列に変換し、各値の余計な空白を削除
			$allowed_ips = array_map('trim', explode(',', $ip_string));
            
			// 現在のIPが許可リストに含まれていれば通知しない
			// 「テストモード」が有効になっている場合は通知する
			$testmode_options =  get_option('hautility-option-02-security');
			$testmode_string =  $testmode_options['theme-plugin-file-change-notice-testmode'] ?? '';
			if( empty($testmode_string)){
				if (in_array($current_ip, $allowed_ips, true)) {
					return;
				}
			}
		}

		// 3. 編集対象（テーマ or プラグイン）の特定
		$file_path = isset($_POST['file']) ? sanitize_text_field($_POST['file']) : '不明なファイル';
		$theme = isset($_POST['theme']) ? sanitize_text_field($_POST['theme']) : '';
		$plugin = isset($_POST['plugin']) ? sanitize_text_field($_POST['plugin']) : '';

		if ($theme) {//テーマの場合
			$theme_text = __('Theme:','hima-art-utility');
			$target_info = $theme_text. $theme;
			$display_file = $file_path; // テーマの場合は元々フォルダ名が含まれないのでそのまま
		} elseif ($plugin) {//プラグインの場合
			// pluginの値が 'my-plugin/my-plugin.php' のようになっている場合、フォルダ名だけ抽出
			$plugin_dir = dirname($plugin); 
			// ファイルパスの先頭からプラグインフォルダ名を取り除く
			// 例: 'my-plugin/inc/settings.php' -> 'inc/settings.php'
			if ($plugin_dir !== '.' && strpos($file_path, $plugin_dir . '/') === 0) {
				$display_file = ltrim(substr($file_path, strlen($plugin_dir)), '/');
			} else {
				$display_file = $file_path;
			}
            
			// ターゲット情報にはプラグイン名（スラッグ）を表示
			$plugin_text = __('Plugin: ','hima-art-utility');
			$target_info = $plugin_text. ($plugin_dir !== '.' ? $plugin_dir : $plugin);
		} else {
			$target_info = __('Unknown','hima-art-utility');
			$display_file = $file_path;
		}

		// 3. 通知メールの作成と送信
		$to = get_option('admin_email');
		$site_title = get_bloginfo( 'name' );
		$home_url = home_url();
		$site_url = admin_url();
		$user = wp_get_current_user();
		$file = isset($_POST['file']) ? sanitize_text_field($_POST['file']) : '不明';

		// 3-1 テキストの変数化（翻訳対象）
		$subject_text_before = __('【notification】','hima-art-utility');
		$subject_text_after = __('The file was edited in','hima-art-utility');
		$info_text = __('The code in the following files has been changed and updated in the admin panel:','hima-art-utility');
		$info_text2 = __('=== Summary of Updated Files ===','hima-art-utility');
		$user_text = __('user:','hima-art-utility');
		$ip_text = __('Login IP address:','hima-art-utility');
		$spec_text = __('kinds:','hima-art-utility');
		$filename_text = __('File name:','hima-art-utility');
		$date_text = __('Updated date and time:','hima-art-utility');
		$site_url_text = __('Website URL:','hima-art-utility');
		$admin_url_text = __('Dashboard URL:','hima-art-utility');
		$info_text3 = __('If you have no recollection of this, we recommend logging into the site to check if it has been tampered with or otherwise compromised.','hima-art-utility');
		$info_text4 = __('If it is clear that you edited it yourself, you can ignore this email.','hima-art-utility');
		$info_text5 = __('*This email will be sent if you have enabled the "File Edit Notification" feature in the security menu of the Hima Art Utility plugin. Please check the settings page for an overview of the feature.','hima-art-utility');

		$locale = get_locale();
		switch_to_locale($locale);

		$subject = sanitize_text_field($subject_text_before . $site_title . $subject_text_after );
		$body = $info_text ;
		$body .= "\n\n";
		$body .= $info_text2 ;
		$body .= "\n";
		$body .=  $user_text . $user->display_name;
		$body .= "\n";
		$body .= $ip_text . $_SERVER['REMOTE_ADDR'];
		$body .= "\n\n";
		$body .= $spec_text. $target_info;
		$body .= "\n";
		$body .= $filename_text  . $display_file;
		$body .= "\n";
		$body .= $date_text . date_i18n('Y-m-d H:i:s');
		$body .= "\n\n";
		$body .= $info_text3 ;
		$body .= "\n";
		$body .= $site_url_text . esc_url(home_url());
		$body .= "\n";
		$body .= $admin_url_text  . esc_url(admin_url());
		$body .= "\n\n";
		$body .= $info_text4 ;
		$body .= "\n\n";
		$body .= $info_text5 ;

		wp_mail($to, $subject, $body);

		restore_previous_locale();
	}
}
add_action('wp_ajax_edit-theme-plugin-file', 'haup_change_code_send_mail', 0);