<?php
/**
 * Admin Menu and UI
 */

function gti_forms_admin_menu() {
	$count = gti_forms_get_unread_count();
	$badge = '';
	if ( $count > 0 ) {
		$badge = sprintf( ' <span class="update-plugins count-%1$d"><span class="plugin-count">%1$d</span></span>', $count );
	}

	// Get custom label from settings
	$label = get_option('gti_forms_inquiry_label', '受信メール');

	// 1. Move Inquiry List back to TOP LEVEL (to keep the badge visible)
	add_menu_page(
		$label . __( '一覧', 'gti-forms' ),
		$label . $badge,
		'manage_options',
		'edit.php?post_type=gti-inquiry',
		'',
		'dashicons-email-alt',
		24 // Position just above GTI Forms
	);

	// 2. Settings (Keep it under GTI Forms for configuration grouping)
	add_submenu_page(
		'edit.php?post_type=gti-form',
		__( '設定', 'gti-forms' ),
		__( '設定', 'gti-forms' ),
		'manage_options',
		'gti-forms-settings',
		'gti_forms_render_settings_page'
	);
}
add_action( 'admin_menu', 'gti_forms_admin_menu' );

/**
 * Add Dashboard Widget
 */
function gti_forms_add_dashboard_widgets() {
	wp_add_dashboard_widget(
		'gti_forms_unread_inquiries',
		__( 'GTI Forms: 未読の受信メール', 'gti-forms' ),
		'gti_forms_render_dashboard_widget'
	);
}
add_action( 'wp_dashboard_setup', 'gti_forms_add_dashboard_widgets' );

function gti_forms_render_dashboard_widget() {
	$query = new WP_Query( array(
		'post_type'      => 'gti-inquiry',
		'posts_per_page' => 5,
		'meta_query'     => array(
			'relation' => 'OR',
			array(
				'key'     => '_gti_read',
				'compare' => 'NOT EXISTS',
			),
			array(
				'key'     => '_gti_read',
				'value'   => '0',
				'compare' => '=',
			),
		),
	) );

	if ( $query->have_posts() ) {
		echo '<ul style="margin:0; padding:0; list-style:none;">';
		while ( $query->have_posts() ) {
			$query->the_post();
			$form_id = get_post_meta( get_the_ID(), '_gti_form_id', true );
			$form_title = $form_id ? get_the_title( $form_id ) : __( '不明なフォーム', 'gti-forms' );
			?>
			<li style="padding: 10px 0; border-bottom: 1px solid #eee; display: flex; justify-content: space-between; align-items: center;">
				<div>
					<a href="<?php echo get_edit_post_link(); ?>" style="font-weight: bold; text-decoration: none;">
						<?php the_title(); ?>
					</a>
					<div style="font-size: 0.85em; color: #666; margin-top: 3px;">
						<span class="dashicons dashicons-forms" style="font-size: 14px; width: 14px; height: 14px; vertical-align: middle;"></span> <?php echo esc_html( $form_title ); ?>
					</div>
				</div>
				<div style="font-size: 0.85em; color: #999; text-align: right;">
					<?php echo get_the_date('Y/m/d H:i'); ?>
				</div>
			</li>
			<?php
		}
		echo '</ul>';
		echo '<p style="margin-top: 15px; text-align: right;"><a href="' . admin_url('edit.php?post_type=gti-inquiry') . '" class="button">' . __( 'すべての受信メールを見る', 'gti-forms' ) . '</a></p>';
	} else {
		echo '<p>' . __( '現在未読のメールはありません。', 'gti-forms' ) . '</p>';
	}
	wp_reset_postdata();
}

function gti_forms_render_settings_page() {
	if ( isset($_POST['gti_save_settings']) ) {
		// Check nonce
		if ( ! isset( $_POST['gti_settings_nonce'] ) || ! wp_verify_nonce( $_POST['gti_settings_nonce'], 'gti_save_settings_action' ) ) {
			wp_die( __( 'Security check failed.', 'gti-forms' ) );
		}

		update_option('gti_forms_stripe_pub_key', sanitize_text_field($_POST['pub_key']));
		update_option('gti_forms_stripe_secret_key', sanitize_text_field($_POST['secret_key']));
		update_option('gti_forms_inquiry_label', sanitize_text_field($_POST['inquiry_label']));
		update_option('gti_forms_from_name', sanitize_text_field($_POST['from_name']));
		update_option('gti_forms_from_email', sanitize_email($_POST['from_email']));
		echo '<div class="updated"><p>' . __( '設定を保存しました。', 'gti-forms' ) . '</p></div>';
	}

	if ( isset($_POST['gti_send_test_email']) ) {
		// Check nonce (using the same nonce for simplicity as they are in the same page view)
		if ( ! isset( $_POST['gti_settings_nonce'] ) || ! wp_verify_nonce( $_POST['gti_settings_nonce'], 'gti_save_settings_action' ) ) {
			wp_die( __( 'Security check failed.', 'gti-forms' ) );
		}

		$to = sanitize_email($_POST['test_email']);
		if ( $to ) {
			// Get current settings for the test mail
			$t_from_name = get_option( 'gti_forms_from_name', get_bloginfo('name') );
			$t_from_email = get_option( 'gti_forms_from_email', get_option( 'admin_email' ) );
			$t_headers = array(
				'Content-Type: text/plain; charset=UTF-8',
				'From: ' . $t_from_name . ' <' . $t_from_email . '>'
			);

			$res = wp_mail($to, __( '【GTI Forms】テストメール送信', 'gti-forms' ), __( 'これはGTI Formsからのテストメールです。これが見えていればwp_mailは正常に動作しています。', 'gti-forms' ), $t_headers);
			if ($res) {
				echo '<div class="updated"><p>' . sprintf( __( '%s 宛にテストメールを送信しました。受信トレイを確認してください。', 'gti-forms' ), esc_html($to) ) . '</p></div>';
			} else {
				echo '<div class="error"><p>' . __( '送信に失敗しました。サーバーのメール送信機能(PHP mail)が無効か、SMTPの設定が必要です。Windows環境の場合は「WP Mail SMTP」プラグインなどの導入を検討してください。', 'gti-forms' ) . '</p></div>';
			}
		}
	}

	$pub = get_option('gti_forms_stripe_pub_key');
	$sec = get_option('gti_forms_stripe_secret_key');
	$label = get_option('gti_forms_inquiry_label', '問い合わせ');
	$from_name = get_option('gti_forms_from_name', get_bloginfo('name'));
	$from_email = get_option('gti_forms_from_email', get_option('admin_email'));
	?>
	<div class="wrap gti-settings-wrap">
		<h1><?php _e( 'GTI Forms 設定', 'gti-forms' ); ?></h1>
\t\t
		<div class="notice notice-info" style="margin: 20px 0; border-left-color: #72aee6; padding: 15px;">
			<h2 style="margin-top: 0; color: #1d2327;"><span class="dashicons dashicons-info" style="color: #72aee6; vertical-align: middle; margin-right: 5px;"></span> <?php _e( '初めにお読みください', 'gti-forms' ); ?></h2>
			<p><?php printf( __( 'GTI Formsへようこそ！このプラグインはブロックエディタを使用して自由自在にフォームを作成できます。受信したメッセージは「%s」メニューから確認・管理が可能です。', 'gti-forms' ), esc_html($label) ); ?></p>
		</div>
		
		<form method="post">
			<?php wp_nonce_field( 'gti_save_settings_action', 'gti_settings_nonce' ); ?>
			<div class="card" style="max-width: 100%; margin-top: 20px; padding: 20px;">
				<h2 class="title" style="border-bottom: 1px solid #eee; padding-bottom: 10px; margin-top: 0;"><?php _e( '一般設定', 'gti-forms' ); ?></h2>
				<table class="form-table">
					<tr>
						<th><?php _e( '問い合わせメニューの名称', 'gti-forms' ); ?></th>
						<td>
							<input type="text" name="inquiry_label" value="<?php echo esc_attr($label); ?>" class="regular-text">
							<p class="description"><?php _e( '管理画面のメニュー名を変更できます（例：予約一覧、申し込み一覧）。', 'gti-forms' ); ?></p>
						</td>
					</tr>
					<tr>
						<th><?php _e( '送信者名 (From Name)', 'gti-forms' ); ?></th>
						<td>
							<input type="text" name="from_name" value="<?php echo esc_attr($from_name); ?>" class="regular-text">
							<p class="description"><?php _e( '受信者のメールソフトで「誰から」として表示される名前です。', 'gti-forms' ); ?></p>
						</td>
					</tr>
					<tr>
						<th><?php _e( '送信元メールアドレス (From Email)', 'gti-forms' ); ?></th>
						<td>
							<input type="email" name="from_email" value="<?php echo esc_attr($from_email); ?>" class="regular-text">
							<div style="background: #fcf9e8; border: 1px solid #e6db55; padding: 10px; margin-top: 10px; border-radius: 4px;">
								<strong style="color: #d63638;"><span class="dashicons dashicons-warning" style="vertical-align: middle;"></span> <?php _e( '【重要】DMARCポリシーと不達について', 'gti-forms' ); ?></strong>
								<p style="margin: 5px 0;"><?php _e( 'お使いのドメイン（例：gti.co.jp）によっては、サーバーの標準機能で送ると「なりすまし」と判断され、Google等に拒否される場合があります（エラー 550 5.7.26 等）。', 'gti-forms' ); ?></p>
								<p style="margin: 5px 0;"><strong><?php _e( '解決策：', 'gti-forms' ); ?></strong><?php _e( '「WP Mail SMTP」プラグインを導入し、本物のメールサーバー（SMTP）経由で送信する設定にしてください。これにより到達率が100%に近づきます。', 'gti-forms' ); ?></p>
							</div>
						</td>
					</tr>
				</table>
			</div>

			<div class="card" style="max-width: 100%; margin-top: 20px; padding: 20px;">
				<h2 class="title" style="border-bottom: 1px solid #eee; padding-bottom: 10px; margin-top: 0;"><?php _e( 'Stripe API 設定', 'gti-forms' ); ?></h2>
				<p class="description"><?php _e( '決済機能（GTI: Stripe決済ブロック）を使用する場合に必要です。', 'gti-forms' ); ?></p>
				<table class="form-table">
					<tr>
						<th><?php _e( 'Stripe 公開可能キー', 'gti-forms' ); ?></th>
						<td><input type="text" name="pub_key" value="<?php echo esc_attr($pub); ?>" class="regular-text"></td>
					</tr>
					<tr>
						<th><?php _e( 'Stripe シークレットキー', 'gti-forms' ); ?></th>
						<td><input type="text" name="secret_key" value="<?php echo esc_attr($sec); ?>" class="regular-text"></td>
					</tr>
				</table>
			</div>
			
			<p class="submit">
				<input type="submit" name="gti_save_settings" class="button-primary button-large" value="<?php esc_attr_e( '設定を保存', 'gti-forms' ); ?>">
			</p>
		</form>

		<div class="card" style="max-width: 100%; margin-top: 40px; padding: 20px; background: #fafafa;">
			<h2 class="title" style="margin-top: 0;"><?php _e( 'メール送信テスト', 'gti-forms' ); ?></h2>
			<p><?php _e( '設定した送信者名・アドレスで実際にメールが届くかテストできます。', 'gti-forms' ); ?></p>
			<form method="post" style="display: flex; align-items: center; gap: 10px;">
				<?php wp_nonce_field( 'gti_save_settings_action', 'gti_settings_nonce' ); ?>
				<input type="email" name="test_email" value="<?php echo esc_attr(get_option('admin_email')); ?>" class="regular-text">
				<input type="submit" name="gti_send_test_email" class="button" value="<?php esc_attr_e( 'テストメールを送信', 'gti-forms' ); ?>">
			</form>
		</div>
	</div>
	<?php
}

add_action( 'wp_mail_failed', function( $error ) {
	error_log( 'GTI Forms Mail Failure: ' . print_r( $error, true ) );
});

/**
 * Force From Email and Name to prevent WordPress default (wordpress@...)
 */
add_filter( 'wp_mail_from', function( $original_email ) {
	$from_email = get_option( 'gti_forms_from_email' );
	if ( $from_email ) {
		return $from_email;
	}
	return $original_email;
});

add_filter( 'wp_mail_from_name', function( $original_name ) {
	$from_name = get_option( 'gti_forms_from_name' );
	if ( $from_name ) {
		return $from_name;
	}
	return $original_name;
});


/**
 * Get unread inquiries count
 */
function gti_forms_get_unread_count() {
	$query = new WP_Query( array(
		'post_type'      => 'gti-inquiry',
		'posts_per_page' => -1,
		'meta_query'     => array(
			'relation' => 'OR',
			array(
				'key'     => '_gti_read',
				'compare' => 'NOT EXISTS',
			),
			array(
				'key'     => '_gti_read',
				'value'   => '0',
				'compare' => '=',
			),
		),
	) );
	return $query->found_posts;
}

/**
 * Rich Preview for Inquiries
 */
function gti_forms_inquiry_columns( $columns ) {
	$new_columns = array(
		'cb'      => $columns['cb'],
		'status'  => __( '状態', 'gti-forms' ),
		'title'   => __( '送信者', 'gti-forms' ),
		'form'    => __( 'フォーム名', 'gti-forms' ),
		'content' => __( '内容（抜粋）', 'gti-forms' ),
		'date'    => __( '受信日時', 'gti-forms' ),
	);
	return $new_columns;
}
add_filter( 'manage_gti-inquiry_posts_columns', 'gti_forms_inquiry_columns' );

function gti_forms_inquiry_column_content( $column, $post_id ) {
	switch ( $column ) {
		case 'status':
			$read = get_post_meta( $post_id, '_gti_read', true );
			$edit_url = get_edit_post_link( $post_id );
			echo '<a href="' . esc_url( $edit_url ) . '" style="text-decoration:none; display:inline-block; min-width:60px;">';
			if ( $read && $read !== '0' ) {
				echo '<span class="dashicons dashicons-email-alt" style="color:#999;" title="' . esc_attr__( '既読', 'gti-forms' ) . '"></span> <small style="color:#999;">' . __( '既読', 'gti-forms' ) . '</small>';
			} else {
				echo '<span class="dashicons dashicons-email-alt2" style="color:#d63638;" title="' . esc_attr__( '未読', 'gti-forms' ) . '"></span> <strong style="color:#d63638;">' . __( '未読', 'gti-forms' ) . '</strong>';
			}
			echo '</a>';
			break;
		case 'form':
			$form_id = get_post_meta( $post_id, '_gti_form_id', true );
			if ( $form_id ) {
				echo esc_html( get_the_title( $form_id ) );
			}
			break;
		case 'content':
			echo wp_trim_words( get_the_content( null, false, $post_id ), 10 );
			break;
	}
}
add_action( 'manage_gti-inquiry_posts_custom_column', 'gti_forms_inquiry_column_content', 10, 2 );

/**
 * Mark as read only when viewing the single inquiry in the admin
 */
function gti_forms_mark_as_read() {
	$screen = get_current_screen();
	// Only run on the single inquiry view, and not when saving (POST)
	if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && $screen && $screen->id === 'gti-inquiry' && isset($_GET['post']) ) {
		$post_id = intval($_GET['post']);
		
		// Get the raw meta value. get_post_meta returns '' if it doesn't exist.
		$read = get_post_meta( $post_id, '_gti_read', true );
		
		// If it has NEVER been set (newly arrived inquiry), mark it as read.
		// If it's '0' (manually unread), we don't touch it.
		if ( $read === '' ) {
			update_post_meta( $post_id, '_gti_read', '1' );
		}
	}
}
add_action( 'admin_head', 'gti_forms_mark_as_read' );

/**
 * Rich design for the inquiry detail screen
 */
function gti_forms_inquiry_metabox() {
	add_meta_box(
		'gti_inquiry_status',
		__( 'ステータス管理', 'gti-forms' ),
		'gti_forms_render_inquiry_status',
		'gti-inquiry',
		'side',
		'high'
	);
	add_meta_box(
		'gti_inquiry_details',
		__( 'お問い合わせ詳細', 'gti-forms' ),
		'gti_forms_render_inquiry_details',
		'gti-inquiry',
		'normal',
		'high'
	);
	add_meta_box(
		'gti_inquiry_memo', 
		__( '対応メモ・自由記入欄', 'gti-forms' ),
		'gti_forms_render_inquiry_memo',
		'gti-inquiry',
		'normal',
		'default'
	);
}
add_action( 'add_meta_boxes', 'gti_forms_inquiry_metabox' );

function gti_forms_render_inquiry_status( $post ) {
	$read = get_post_meta( $post->ID, '_gti_read', true );
	$is_read = ( $read && $read !== '0' );
	wp_nonce_field( 'gti_inquiry_status_nonce', 'gti_inquiry_status_nonce_field' );
	?>
	<div class="gti-status-toggle">
		<label style="display:flex; align-items:center; cursor:pointer; font-size:1.1em; padding:5px 0;">
			<input type="checkbox" name="gti_is_read" value="1" <?php checked( $is_read ); ?> style="margin-right:10px;">
			<span><?php _e( '既読にする', 'gti-forms' ); ?></span>
		</label>
		<p class="description"><?php _e( 'チェックを外して保存すると、「未読」に戻ります。', 'gti-forms' ); ?></p>
	</div>
	<?php
}

function gti_forms_save_inquiry_status( $post_id ) {
	if ( ! isset( $_POST['gti_inquiry_status_nonce_field'] ) || ! wp_verify_nonce( $_POST['gti_inquiry_status_nonce_field'], 'gti_inquiry_status_nonce' ) ) {
		return;
	}
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;

	$is_read = isset( $_POST['gti_is_read'] ) ? '1' : '0';
	update_post_meta( $post_id, '_gti_read', $is_read );
}
add_action( 'save_post_gti-inquiry', 'gti_forms_save_inquiry_status' );

function gti_forms_render_inquiry_memo( $post ) {
	$memo = get_post_meta( $post->ID, '_gti_memo', true );
	wp_nonce_field( 'gti_inquiry_memo_nonce', 'gti_inquiry_memo_nonce_field' );
	?>
	<div class="gti-inquiry-memo-wrapper">
		<textarea name="gti_inquiry_memo" style="width:100%; min-height:150px; font-size:14px; padding:10px; border:1px solid #ddd;"><?php echo esc_textarea( $memo ); ?></textarea>
		<p class="description"><?php _e( '返信の履歴や特記事項など、自由に使用してください。この欄は送信者（顧客）には表示されません。', 'gti-forms' ); ?></p>
	</div>
	<?php
}

function gti_forms_save_inquiry_memo( $post_id ) {
	if ( ! isset( $_POST['gti_inquiry_memo_nonce_field'] ) || ! wp_verify_nonce( $_POST['gti_inquiry_memo_nonce_field'], 'gti_inquiry_memo_nonce' ) ) {
		return;
	}
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;

	if ( isset( $_POST['gti_inquiry_memo'] ) ) {
		update_post_meta( $post_id, '_gti_memo', sanitize_textarea_field( $_POST['gti_inquiry_memo'] ) );
	}
}
add_action( 'save_post_gti-inquiry', 'gti_forms_save_inquiry_memo' );

function gti_forms_render_inquiry_details( $post ) {
	$data = get_post_meta( $post->ID, '_gti_data', true );
	if ( ! is_array( $data ) ) {
		$data = array();
	}
	?>
	<div class="gti-inquiry-rich-view">
		<style>
			.gti-inquiry-rich-view { font-size: 16px; line-height: 1.6; }
			.gti-inquiry-row { display: flex; border-bottom: 1px solid #eee; padding: 15px 0; }
			.gti-inquiry-label { width: 200px; font-weight: bold; color: #555; }
			.gti-inquiry-value { flex: 1; }
			.gti-inquiry-value pre { background: #f9f9f9; padding: 10px; border-radius: 4px; overflow-x: auto; }
		</style>
		<?php foreach ( $data as $label => $value ) : ?>
			<div class="gti-inquiry-row">
				<div class="gti-inquiry-label"><?php echo esc_html( $label ); ?></div>
				<div class="gti-inquiry-value">
					<?php 
					if ( is_array( $value ) ) {
						echo esc_html( implode( ', ', $value ) );
					} else {
						echo nl2br( esc_html( $value ) );
						
						// If value looks like an email, add a mailto link
						if ( is_email( trim( $value ) ) ) {
							echo ' <a href="' . esc_url( 'mailto:' . trim( $value ) ) . '" class="button button-small" style="margin-left:10px; vertical-align:middle;"><span class="dashicons dashicons-email-alt" style="font-size:16px; width:16px; height:16px; vertical-align:text-bottom; margin-right:4px;"></span>' . __( 'メーラー起動', 'gti-forms' ) . '</a>';
						}
					}
					?>
				</div>
			</div>
		<?php endforeach; ?>
	</div>
	<?php
}

/**
 * Add some style to the admin list
 */
function gti_forms_admin_head() {
	echo '<style>
		.column-status { width: 50px; text-align: center; }
		.post-state .unread { font-weight: bold; color: #d63638; }
	</style>';
}
add_action( 'admin_head', 'gti_forms_admin_head' );
/**
 * Add Meta Boxes for Form Settings
 */
function gti_forms_register_meta_boxes() {
	add_meta_box(
		'gti_form_email_settings',
		__( 'メール通知設定', 'gti-forms' ),
		'gti_forms_render_email_settings_metabox',
		'gti-form',
		'normal',
		'high'
	);
}
add_action( 'add_meta_boxes', 'gti_forms_register_meta_boxes' );

function gti_forms_render_email_settings_metabox( $post ) {
	$admin_email = get_post_meta( $post->ID, '_gti_admin_email', true );
	$admin_cc = get_post_meta( $post->ID, '_gti_admin_cc', true );
	$admin_bcc = get_post_meta( $post->ID, '_gti_admin_bcc', true );
	$cust_subject = get_post_meta( $post->ID, '_gti_cust_subject', true );
	$cust_body = get_post_meta( $post->ID, '_gti_cust_body', true );
	$send_cust_email = get_post_meta( $post->ID, '_gti_send_cust_email', true );
	$send_admin_email = get_post_meta( $post->ID, '_gti_send_admin_email', true );
	$admin_email_type = get_post_meta( $post->ID, '_gti_admin_email_type', true );
	$thanks_message = get_post_meta( $post->ID, '_gti_thanks_message', true );
	
	// Default to checked if not set
	if ( $send_cust_email === '' ) $send_cust_email = '1';
	if ( $send_admin_email === '' ) $send_admin_email = '1';
	if ( ! $admin_email_type ) $admin_email_type = 'link'; // 'link' or 'full'

	if ( ! $cust_subject ) $cust_subject = __( 'お問い合わせありがとうございます', 'gti-forms' );
	if ( ! $cust_body ) $cust_body = sprintf( __( "%s 様\n\nお問い合わせありがとうございました。\n以下の内容で受け付けました。\n\n{all_fields}\n\n担当者より折り返しご連絡いたします。", 'gti-forms' ), '{name}' );
	if ( ! $thanks_message ) $thanks_message = __( 'お問い合わせありがとうございました。送信が完了いたしました。', 'gti-forms' );

	wp_nonce_field( 'gti_form_settings_nonce', 'gti_form_settings_nonce_field' );
	?>
	<table class="form-table">
		<tr>
			<th><label><?php _e( '管理者への通知', 'gti-forms' ); ?></label></th>
			<td>
				<label>
					<input type="checkbox" name="gti_send_admin_email" value="1" <?php checked( $send_admin_email, '1' ); ?>>
					<?php _e( '管理者へ通知メールを送信する', 'gti-forms' ); ?>
				</label>
				<div style="margin-top: 10px;">
					<?php _e( '通知内容：', 'gti-forms' ); ?><br>
					<label><input type="radio" name="gti_admin_email_type" value="link" <?php checked( $admin_email_type, 'link' ); ?>> <?php _e( '管理画面へのリンクのみ（セキュリティ・管理重視）', 'gti-forms' ); ?></label><br>
					<label><input type="radio" name="gti_admin_email_type" value="full" <?php checked( $admin_email_type, 'full' ); ?>> <?php _e( '全ての入力内容を含める', 'gti-forms' ); ?></label>
				</div>
			</td>
		</tr>
		<tr>
			<th><label><?php _e( '自動返信メール', 'gti-forms' ); ?></label></th>
			<td>
				<label>
					<input type="checkbox" name="gti_send_cust_email" value="1" <?php checked( $send_cust_email, '1' ); ?>>
					<?php _e( '送信者に自動返信メールを送る', 'gti-forms' ); ?>
				</label>
				<div style="background: #fff8e1; border-left: 4px solid #ffc107; padding: 12px; margin-top: 10px;">
					<strong><?php _e( '【重要：送信されない場合の注意点】', 'gti-forms' ); ?></strong><br>
					<ul style="margin: 5px 0 0 20px; list-style: disc;">
						<li><?php _e( 'フォーム内に「GTI: メールアドレス」ブロックが配置されている必要があります。', 'gti-forms' ); ?></li>
						<li><?php printf( __( 'ブロック設定の <strong>name属性</strong> に必ず <code>email</code> という文字を含めてください（例: <code>%s</code>, <code>%s</code> など）。これがないと送信先を特定できません。', 'gti-forms' ), 'your-email', 'customer_email' ); ?></li>
						<li><?php _e( 'サーバーの設定により、スパム扱いされている可能性があります。', 'gti-forms' ); ?></li>
					</ul>
				</div>
			</td>
		</tr>
		<tr>
			<th><label><?php _e( '通知先メールアドレス (To)', 'gti-forms' ); ?></label></th>
			<td>
				<input type="text" name="gti_admin_email" value="<?php echo esc_attr( $admin_email ); ?>" class="regular-text" placeholder="<?php echo esc_attr( get_option('admin_email') ); ?>">
				<p class="description"><?php _e( '管理用の通知を送るアドレスです。空の場合はサイト管理者のアドレスに送られます。', 'gti-forms' ); ?></p>
			</td>
		</tr>
		<tr>
			<th><label><?php _e( '通知先 CC', 'gti-forms' ); ?></label></th>
			<td>
				<input type="text" name="gti_admin_cc" value="<?php echo esc_attr( $admin_cc ); ?>" class="regular-text">
			</td>
		</tr>
		<tr>
			<th><label><?php _e( '通知先 BCC', 'gti-forms' ); ?></label></th>
			<td>
				<input type="text" name="gti_admin_bcc" value="<?php echo esc_attr( $admin_bcc ); ?>" class="regular-text">
			</td>
		</tr>
		<tr>
			<th><label><?php _e( '自動返信メール件名', 'gti-forms' ); ?></label></th>
			<td><input type="text" name="gti_cust_subject" value="<?php echo esc_attr( $cust_subject ); ?>" class="large-text"></td>
		</tr>
		<tr>
			<th><label><?php _e( '自動返信メール本文', 'gti-forms' ); ?></label></th>
			<td>
				<textarea name="gti_cust_body" rows="10" class="large-text"><?php echo esc_textarea( $cust_body ); ?></textarea>
				<p class="description">
					<?php _e( '以下の置換タグが使用できます：', 'gti-forms' ); ?><br>
					<code>{all_fields}</code><?php _e( '（全入力内容）', 'gti-forms' ); ?>, <code>{name}</code><?php _e( '（お名前）', 'gti-forms' ); ?>, <code>{email}</code><?php _e( '（メールアドレス）', 'gti-forms' ); ?><br>
					<?php printf( __( '※ <code>%s</code> や <code>%s</code> はブロックの設定で<code>name</code>属性に <code>%s</code> や <code>%s</code> と指定している場合に反応します。', 'gti-forms' ), '{name}', '{email}', 'your-name', 'your-email' ); ?>
				</p>
			</td>
		</tr>
		<tr>
			<th><label><?php _e( '完了画面メッセージ', 'gti-forms' ); ?></label></th>
			<td>
				<textarea name="gti_thanks_message" rows="3" class="large-text"><?php echo esc_textarea( $thanks_message ); ?></textarea>
				<p class="description"><?php _e( '送信完了後に画面に表示されるメッセージです。', 'gti-forms' ); ?></p>
			</td>
		</tr>
	</table>
	<?php
}

function gti_forms_save_form_settings( $post_id ) {
	if ( ! isset( $_POST['gti_form_settings_nonce_field'] ) || ! wp_verify_nonce( $_POST['gti_form_settings_nonce_field'], 'gti_form_settings_nonce' ) ) {
		return;
	}
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;

	update_post_meta( $post_id, '_gti_admin_email', sanitize_text_field( $_POST['gti_admin_email'] ) );
	update_post_meta( $post_id, '_gti_admin_cc', sanitize_text_field( $_POST['gti_admin_cc'] ) );
	update_post_meta( $post_id, '_gti_admin_bcc', sanitize_text_field( $_POST['gti_admin_bcc'] ) );
	update_post_meta( $post_id, '_gti_cust_subject', sanitize_text_field( $_POST['gti_cust_subject'] ) );
	update_post_meta( $post_id, '_gti_cust_body', sanitize_textarea_field( $_POST['gti_cust_body'] ) );
	update_post_meta( $post_id, '_gti_send_cust_email', isset( $_POST['gti_send_cust_email'] ) ? '1' : '0' );
	update_post_meta( $post_id, '_gti_send_admin_email', isset( $_POST['gti_send_admin_email'] ) ? '1' : '0' );
	update_post_meta( $post_id, '_gti_admin_email_type', sanitize_text_field( $_POST['gti_admin_email_type'] ) );
	update_post_meta( $post_id, '_gti_thanks_message', sanitize_textarea_field( $_POST['gti_thanks_message'] ) );
}
add_action( 'save_post_gti-form', 'gti_forms_save_form_settings' );

/**
 * Add Shortcode column to Form List
 */
function gti_forms_form_columns( $columns ) {
	$columns['shortcode'] = __( 'ショートコード', 'gti-forms' );
	return $columns;
}
add_filter( 'manage_gti-form_posts_columns', 'gti_forms_form_columns' );

function gti_forms_form_column_content( $column, $post_id ) {
	if ( $column === 'shortcode' ) {
		echo '<code>[gti_form id="' . $post_id . '"]</code>';
	}
}
add_action( 'manage_gti-form_posts_custom_column', 'gti_forms_form_column_content', 10, 2 );
