<?php
/**
 * Shared TutorHelper email administration.
 *
 * @package TutorHelper_Bookings
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Handles Core email template editing.
 */
final class TutorHelper_Email_Admin {

	/**
	 * Save-template action.
	 *
	 * @var string
	 */
	const SAVE_ACTION =
		'tutorhelper_save_email_template';

	/**
	 * Restore-template action.
	 *
	 * @var string
	 */
	const RESTORE_ACTION =
		'tutorhelper_restore_email_template';


	

	/**
	 * Initialise admin actions.
	 *
	 * @return void
	 */
	public static function init() {
		add_action(
			'admin_post_' . self::SAVE_ACTION,
			array(
				__CLASS__,
				'handle_save',
			)
		);

		add_action(
			'admin_post_' . self::RESTORE_ACTION,
			array(
				__CLASS__,
				'handle_restore',
			)
		);


	}

	/**
	 * Render templates belonging to one module.
	 *
	 * @param string $module Module identifier.
	 *
	 * @return void
	 */
	public static function render_module_templates(
		$module
	) {
		if (
			! current_user_can(
				'manage_options'
			)
		) {
			return;
		}

		$module =
			sanitize_key(
				$module
			);

		$templates =
			TutorHelper_Email_Templates::
				get_by_module(
					$module
				);

		self::render_notice();
		

		?>
		<section
			class="tutorhelper-email-settings"
		>
			<header
				class="tutorhelper-email-settings__header"
			>
				<h2>
					<?php
					esc_html_e(
						'Email templates',
						'tutorhelper-bookings'
					);
					?>
				</h2>

				<p>
					<?php
					esc_html_e(
						'Choose which automatic emails are sent and customise their subject and message text.',
						'tutorhelper-bookings'
					);
					?>
				</p>
			</header>

			<?php if ( empty( $templates ) ) : ?>
				<div
					class="notice notice-info inline"
				>
					<p>
						<?php
						esc_html_e(
							'No email templates are currently registered for this module.',
							'tutorhelper-bookings'
						);
						?>
					</p>
				</div>
			<?php else : ?>
				<div
					class="tutorhelper-email-settings__templates"
				>
					<?php
					foreach (
						$templates
						as $template
					) {
						self::render_template(
							$template
						);
					}
					?>
				</div>
			<?php endif; ?>
		</section>
		<?php
	}





	/**
	 * Render one editable Core email template.
	 *
	 * @param array $template Template definition.
	 *
	 * @return void
	 */
	private static function render_template(
		$template
	) {
		if (
			empty( $template['key'] )
			|| empty( $template['label'] )
		) {
			return;
		}

		$template_key =
			sanitize_key(
				$template['key']
			);

		$subject =
			isset( $template['subject'] )
				? $template['subject']
				: '';

		$body =
			isset( $template['body'] )
				? $template['body']
				: '';

		$placeholders =
			isset(
				$template['placeholders']
			)
			&& is_array(
				$template['placeholders']
			)
				? $template['placeholders']
				: array();

		?>
		<article
			class="tutorhelper-email-template"
		>
			<header
				class="tutorhelper-email-template__header"
			>
				<div>
					<h3>
						<?php
						echo esc_html(
							$template['label']
						);
						?>
					</h3>

					<?php if (
						! empty(
							$template[
								'description'
							]
						)
					) : ?>
						<p>
							<?php
							echo esc_html(
								$template[
									'description'
								]
							);
							?>
						</p>
					<?php endif; ?>
				</div>

				<span
					class="tutorhelper-email-template__recipient"
				>
					<?php
					printf(
						/* translators: %s: email recipient type. */
						esc_html__(
							'To: %s',
							'tutorhelper-bookings'
						),
						esc_html(
							ucfirst(
								isset(
									$template[
										'recipient'
									]
								)
									? $template[
										'recipient'
									]
									: ''
							)
						)
					);
					?>
				</span>
			</header>

			<form
				method="post"
				action="<?php echo esc_url(
					admin_url(
						'admin-post.php'
					)
				); ?>"
				class="tutorhelper-email-template__form"
			>
				<input
					type="hidden"
					name="action"
					value="<?php echo esc_attr(
						self::SAVE_ACTION
					); ?>"
				/>

				<input
					type="hidden"
					name="template_key"
					value="<?php echo esc_attr(
						$template_key
					); ?>"
				/>

				<?php
				wp_nonce_field(
					self::SAVE_ACTION
						. '_'
						. $template_key
				);
				?>

				<label
					class="tutorhelper-email-template__enabled"
				>
					<input
						type="checkbox"
						name="enabled"
						value="1"
						<?php
						checked(
							! empty(
								$template[
									'enabled'
								]
							)
						);
						?>
					/>

					<span>
						<?php
						esc_html_e(
							'Send this email',
							'tutorhelper-bookings'
						);
						?>
					</span>
				</label>

				<div
					class="tutorhelper-email-template__field"
				>
					<label
						for="tutorhelper-email-subject-<?php echo esc_attr(
							$template_key
						); ?>"
					>
						<?php
						esc_html_e(
							'Subject',
							'tutorhelper-bookings'
						);
						?>
					</label>

					<input
						type="text"
						id="tutorhelper-email-subject-<?php echo esc_attr(
							$template_key
						); ?>"
						name="subject"
						value="<?php echo esc_attr(
							$subject
						); ?>"
						class="large-text"
						required
					/>
				</div>

				<div
					class="tutorhelper-email-template__field"
				>
					<label
						for="tutorhelper-email-body-<?php echo esc_attr(
							$template_key
						); ?>"
					>
						<?php
						esc_html_e(
							'Message',
							'tutorhelper-bookings'
						);
						?>
					</label>

					<textarea
						id="tutorhelper-email-body-<?php echo esc_attr(
							$template_key
						); ?>"
						name="body"
						rows="12"
						class="large-text"
						required
					><?php echo esc_textarea(
						$body
					); ?></textarea>
				</div>

				<?php if (
					! empty(
						$placeholders
					)
				) : ?>
					<div
						class="tutorhelper-email-template__placeholders"
					>
						<strong>
							<?php
							esc_html_e(
								'Available placeholders',
								'tutorhelper-bookings'
							);
							?>
						</strong>

						<div
							class="tutorhelper-email-template__placeholder-list"
						>
							<?php
							foreach (
								$placeholders
								as $placeholder
							) :
								?>
								<code>
									<?php
									echo esc_html(
										$placeholder
									);
									?>
								</code>
							<?php endforeach; ?>
						</div>
					</div>
				<?php endif; ?>

				<div
					class="tutorhelper-email-template__actions"
				>
					<button
						type="submit"
						class="button button-primary"
					>
						<?php
						esc_html_e(
							'Save changes',
							'tutorhelper-bookings'
						);
						?>
					</button>
				</div>
			</form>

			<form
				method="post"
				action="<?php echo esc_url(
					admin_url(
						'admin-post.php'
					)
				); ?>"
				class="tutorhelper-email-template__restore-form"
			>
				<input
					type="hidden"
					name="action"
					value="<?php echo esc_attr(
						self::RESTORE_ACTION
					); ?>"
				/>

				<input
					type="hidden"
					name="template_key"
					value="<?php echo esc_attr(
						$template_key
					); ?>"
				/>

				<?php
				wp_nonce_field(
					self::RESTORE_ACTION
						. '_'
						. $template_key
				);
				?>

				<button
					type="submit"
					class="button button-secondary"
				>
					<?php
					esc_html_e(
						'Restore default',
						'tutorhelper-bookings'
					);
					?>
				</button>
			</form>
		</article>
		<?php
	}

	/**
	 * Save one email template.
	 *
	 * @return void
	 */
	public static function handle_save() {
		if (
			! current_user_can(
				'manage_options'
			)
		) {
			wp_die(
                esc_html__(
                    'You do not have permission to edit email templates.',
                    'tutorhelper-bookings'
                ),
                esc_html__(
                    'Permission denied',
                    'tutorhelper-bookings'
                ),
                array(
                    'response' => 403,
                )
            );
		}

		$template_key =
			isset( $_POST['template_key'] )
				? sanitize_key(
					wp_unslash(
						$_POST[
							'template_key'
						]
					)
				)
				: '';

		check_admin_referer(
			self::SAVE_ACTION
				. '_'
				. $template_key
		);

		$result =
			TutorHelper_Email_Templates::save(
				$template_key,
				$_POST
			);

		if ( is_wp_error( $result ) ) {
			self::redirect(
				'error',
				$result->get_error_code()
			);
		}

		self::redirect(
			'saved'
		);
	}

	/**
	 * Restore one template to its registered defaults.
	 *
	 * @return void
	 */
	public static function handle_restore() {
		if (
			! current_user_can(
				'manage_options'
			)
		) {
			wp_die(
				esc_html__(
					'You do not have permission to edit email templates.',
					'tutorhelper-bookings'
				),
				esc_html__(
					'Permission denied',
					'tutorhelper-bookings'
				),
				array(
					'response' => 403,
				)
			);
		}

		$template_key =
			isset( $_POST['template_key'] )
				? sanitize_key(
					wp_unslash(
						$_POST[
							'template_key'
						]
					)
				)
				: '';

		check_admin_referer(
			self::RESTORE_ACTION
				. '_'
				. $template_key
		);

		$result =
			TutorHelper_Email_Templates::
				restore_default(
					$template_key
				);

		if ( ! $result ) {
			self::redirect(
				'error',
				'tutorhelper_email_restore_failed'
			);
		}

		self::redirect(
			'restored'
		);
	}

	/**
	 * Redirect back to the current admin screen.
	 *
	 * @param string $status     Result status.
	 * @param string $error_code Optional error code.
	 *
	 * @return void
	 */
	private static function redirect(
		$status,
		$error_code = ''
	) {
		$url =
			wp_get_referer();

		if ( ! $url ) {
			$url =
				admin_url();
		}

		$args = array(
			'tutorhelper_email_status' =>
				sanitize_key(
					$status
				),
		);

		if ( $error_code ) {
			$args[
				'tutorhelper_email_error'
			] =
				sanitize_key(
					$error_code
				);
		}

		wp_safe_redirect(
			add_query_arg(
				$args,
				$url
			)
		);

		exit;
	}

	/**
	 * Render save/restore feedback.
	 *
	 * @return void
	 */
	private static function render_notice() {
		$status =
			isset(
				$_GET[ // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only request state used for navigation or feedback; value is sanitized and no state change occurs.
					'tutorhelper_email_status'
				]
			)
				? sanitize_key(
					wp_unslash(
						$_GET[ // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only request state used for navigation or feedback; value is sanitized and no state change occurs.
							'tutorhelper_email_status'
						]
					)
				)
				: '';

		if ( 'saved' === $status ) {
			?>
			<div
				class="notice notice-success inline"
			>
				<p>
					<?php
					esc_html_e(
						'Email template saved.',
						'tutorhelper-bookings'
					);
					?>
				</p>
			</div>
			<?php
		} elseif ( 'restored' === $status ) {
			?>
			<div
				class="notice notice-success inline"
			>
				<p>
					<?php
					esc_html_e(
						'Email template restored to its default settings.',
						'tutorhelper-bookings'
					);
					?>
				</p>
			</div>
			<?php
				} elseif ( 'error' === $status ) {
					?>
					<div
						class="notice notice-error inline"
					>
						<p>
							<?php
							esc_html_e(
								'The email template could not be saved. Please check the subject and message and try again.',
								'tutorhelper-bookings'
							);
							?>
						</p>
					</div>
					<?php
				}
				elseif (
			'settings_saved'
			=== $status
		) {
			?>
			<div
				class="notice notice-success inline"
			>
				<p>
					<?php
					esc_html_e(
						'Email sender details saved.',
						'tutorhelper-bookings'
					);
					?>
				</p>
			</div>
			<?php
		}
	}
}
