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

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

/**
 * Renders registered TutorHelper email templates.
 */
final class TutorHelper_Email_Renderer {

	/**
	 * Render one registered template.
	 *
	 * Rendering does not check whether the template is enabled so that
	 * disabled templates may still be previewed in future interfaces.
	 *
	 * @param string $template_key Template identifier.
	 * @param array  $placeholders Placeholder/value map.
	 *
	 * @return array|WP_Error
	 */
	public static function render(
		$template_key,
		$placeholders = array()
	) {
		$template_key =
			sanitize_key(
				$template_key
			);

		$template =
			TutorHelper_Email_Templates::get(
				$template_key
			);

		if ( ! $template ) {
			return new WP_Error(
				'tutorhelper_email_template_missing',
				__(
					'The requested email template could not be found.',
					'tutorhelper-bookings'
				)
			);
		}

		$placeholders =
			TutorHelper_Email_Placeholders::
				add_shared_values(
					$placeholders
				);

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

		$subject =
			TutorHelper_Email_Placeholders::
				replace(
					$template['subject'],
					$placeholders,
					$allowed
				);

		$body =
			TutorHelper_Email_Placeholders::
				replace(
					$template['body'],
					$placeholders,
					$allowed
				);

		$subject =
			wp_strip_all_tags(
				$subject
			);

		/*
		* Template bodies may contain safe formatting HTML.
		*
		* Sanitize the content after placeholder replacement, then
		* add paragraphs and automatic links for plain-text sections.
		*/
		$body_html =
			wp_kses_post(
				wpautop(
					make_clickable(
						$body
					)
				)
			);

		$html =
			self::wrap_core_email(
				$body_html,
				$template,
				$placeholders
			);

		return array(
			'template_key' =>
				$template_key,

			'template' =>
				$template,

			'subject' =>
				$subject,

			'body_text' =>
				$body,

			'body_html' =>
				$body_html,

			'html' =>
				$html,
		);
	}

	/**
	 * Wrap rendered text in the fixed Core TutorHelper layout.
	 *
	 * Custom branding and layout controls are reserved for Pro.
	 *
	 * @param string $body_html    Rendered body.
	 * @param array  $template     Template definition.
	 * @param array  $placeholders Placeholder map.
	 *
	 * @return string
	 */
	private static function wrap_core_email(
		$body_html,
		$template,
		$placeholders
	) {
		$site_name =
			isset(
				$placeholders[
					'{site_name}'
				]
			)
				? sanitize_text_field(
					$placeholders[
						'{site_name}'
					]
				)
				: wp_specialchars_decode(
					get_bloginfo( 'name' ),
					ENT_QUOTES
				);
		
		$heading =
			! empty(
				$template['heading']
			)
				? sanitize_text_field(
					$template['heading']
				)
				: $site_name;

		$email_settings =
			TutorHelper_Email_Settings::get_all();

		$sender_name =
			! empty(
				$email_settings['sender_name']
			)
				? sanitize_text_field(
					$email_settings[
						'sender_name'
					]
				)
				: $site_name;

		$contact_email =
			! empty(
				$email_settings['contact_email']
			)
				? sanitize_email(
					$email_settings[
						'contact_email'
					]
				)
				: '';

		$privacy_policy_url =
			! empty(
				$email_settings[
					'privacy_policy_url'
				]
			)
				? esc_url(
					$email_settings[
						'privacy_policy_url'
					]
				)
				: '';

		$is_tutor_email =
			isset(
				$template['recipient']
			)
			&& 'tutor'
			=== sanitize_key(
				$template['recipient']
			);

		ob_start();
		?>
		<!doctype html>
		<html>
		<head>
			<meta charset="UTF-8">
			<meta
				name="viewport"
				content="width=device-width, initial-scale=1"
			>
			<title>
				<?php echo esc_html( $heading ); ?>
			</title>
		</head>

		<body
			style="margin:0;padding:0;background:#f6f7f7;font-family:Arial,Helvetica,sans-serif;color:#1d2327;"
		>
			<table
				role="presentation"
				width="100%"
				cellspacing="0"
				cellpadding="0"
				style="width:100%;background:#f6f7f7;padding:24px 12px;"
			>
				<tr>
					<td align="center">
						<table
							role="presentation"
							width="640"
							cellspacing="0"
							cellpadding="0"
							style="width:100%;max-width:640px;background:#ffffff;border:1px solid #dcdcde;border-radius:12px;overflow:hidden;"
						>
							<tr>
								<td
									style="padding:20px 28px;border-bottom:1px solid #dcdcde;font-size:20px;font-weight:700;color:#1d2327;"
								>
									<?php
									echo esc_html(
										$site_name
									);
									?>
								</td>
							</tr>

							<tr>
								<td
									style="padding:28px;font-size:16px;line-height:1.6;color:#1d2327;"
								>
									<?php
									echo wp_kses_post(
										$body_html
									);
									?>
								</td>
							</tr>

							<tr>
								<td
									style="padding:18px 28px;background:#f6f7f7;border-top:1px solid #dcdcde;font-size:12px;line-height:1.5;color:#646970;"
								>
									<?php if ( ! $is_tutor_email ) : ?>
										<p
											style="margin:0 0 12px;"
										>
											<?php
											printf(
												/* translators: %s: website name. */
												esc_html__(
													'You have received this email because you have requested a lesson with %s.',
													'tutorhelper-bookings'
												),
												esc_html(
													$site_name
												)
											);
											?>
										</p>
									<?php endif; ?>

									<p
										style="margin:0 0 6px;"
									>
										<strong>
											<?php
											echo esc_html(
												$sender_name
											);
											?>
										</strong>
									</p>

									<?php if ( $contact_email ) : ?>
										<p
											style="margin:0 0 6px;"
										>
											<?php
											esc_html_e(
												'Contact:',
												'tutorhelper-bookings'
											);
											?>

											<a
												href="mailto:<?php echo esc_attr(
													$contact_email
												); ?>"
												style="color:#2271b1;"
											>
												<?php
												echo esc_html(
													$contact_email
												);
												?>
											</a>
										</p>
									<?php endif; ?>

									<?php if ( $privacy_policy_url ) : ?>
										<p
											style="margin:0 0 12px;"
										>
											<a
												href="<?php echo esc_url(
													$privacy_policy_url
												); ?>"
												style="color:#2271b1;"
											>
												<?php
												esc_html_e(
													'Privacy Policy',
													'tutorhelper-bookings'
												);
												?>
											</a>
										</p>
									<?php endif; ?>

									<p
										style="margin:12px 0 0;color:#8c8f94;"
									>
									<?php
									esc_html_e(
										'This is an automatic message about your lesson booking. Sent using TutorHelper.',
										'tutorhelper-bookings'
									);
									?>
								</p>
								</td>
							</tr>
						</table>
					</td>
				</tr>
			</table>
		</body>
		</html>
		<?php

		$html =
			wp_kses_post(
				ob_get_clean()
			);

		/**
		 * Filters the final TutorHelper email HTML.
		 *
		 * This gives add-ons such as Pro a supported route to replace
		 * the fixed Core wrapper without changing template content.
		 *
		 * @param string $html         Final email HTML.
		 * @param string $body_html    Rendered message body.
		 * @param array  $template     Template definition.
		 * @param array  $placeholders Placeholder values.
		 */
		return apply_filters(
			'tutorhelper_email_rendered_html',
			$html,
			$body_html,
			$template,
			$placeholders
		);
	}
}
