<?php

namespace ZenCommunity\Addons\Email;

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

use ZenCommunity\Exceptions\ZencommunityException;
use ZenCommunity\Addons\Email\Database\Models\Template as TmpModel;
class Template {
	public string $event;
	public ?string $email;
	public array $template;
	public array $event_data;
	public array $settings;
	public function __construct( string $event, array $event_data, ?string $mock_email = null ) {
		$this->event = $event;
		$this->event_data = $event_data;
		$this->settings = get_option( 'zenc_email_settings', [
				'from' => [
					'name' => '',
					'email' => get_option( 'admin_email' ),
				],
				'footer_text' => 'Thank you'
			] );
			
		$this->template = TmpModel::by_event( $event, empty( $mock_email ) ? true : null );
		$this->email    = empty( $mock_email ) ? ( get_userdata( absint( $this->event_data['to_user_id'] ) )->user_email ?? null ) : $mock_email;
		if ( empty( $this->email ) ) 
			throw new ZencommunityException( esc_html( __( 'email not found.', 'zencommunity' ) ), 404 );

	}

	public function send() : void {
		$site_name   = $this->settings['from']['name'] ?? get_bloginfo( 'name' );
		$admin_email = $this->settings['from']['email'] ?? get_option( 'admin_email' );
		add_filter( 'wp_mail_content_type', [ $this, 'set_html_mail_content_type' ] );

		wp_mail(
			$this->email, 
			apply_filters( 
				'zencommunity/email/subject', 
				$this->template['subject'] ?? '',
				$this
			), 
			apply_filters( 
				'zencommunity/email/body', 
				$this->message(),
				$this
			), 
			apply_filters( 
				'zencommunity/email/headers', 
				[
					'Content-Type: text/html; charset=UTF-8',
					"From: {$site_name} <{$admin_email}>",
				],
				$this
			)
		);
		remove_filter( 'wp_mail_content_type', [ $this, 'set_html_mail_content_type' ] );
	}

	public function set_html_mail_content_type() : string {
		return 'text/html';
	}

	public function template() : string {
		$template = $this->template['template'] ?? '';
		$tmpvars = apply_filters( 
			"zencommunity/email/template/{$this->event}", 
			$this->conv_template(), 
			$this->event_data 
		);
		
		foreach ( $tmpvars as $search => $replace ) {
			$template = str_replace( "{{" . $search . "}}", $replace, $template );
		}
		return $this->parse_mention( $template );
	}

	protected function parse_mention( string $content ) : string {
		$pattern = '/<Mention\s+id=(\d+)\s+username="[^"]*"\s*\/?>/i';

		$content = preg_replace_callback( $pattern, function( ?array $matches ) : ?string {
			$user_id = intval( $matches[1] );
			$user = get_userdata( $user_id );

			if ( $user ) {
				$display_name = $user->display_name;
				return esc_html( $display_name );
			} else {
				return 'UnknownUser';
			}
		}, $content );

		return $content;
	}

	private function conv_template(): array {
		$author = get_userdata( absint( $this->event_data['from_user_id'] ?? 0 ) );
		$result = [
			'author_name' => ( $author->display_name ?? '' )
		];

		foreach ( $this->event_data['meta']['route'] ?? [] as $key => $sub_arr ) {
			if ( is_array( $sub_arr ) ) {
				foreach ( $sub_arr as $sub_key => $value ) {
					if ( 
						is_null( $value ) || 
						is_array( $value ) ||
						is_object( $value ) 
					)  continue;
					$result["{$key}_{$sub_key}"] = $value;
				}
			} else {
				$result[$key] = $sub_arr;
			}
		}

		return $result;
	}

	public function message() : string {
		ob_start();
		?>
		<!DOCTYPE html>
		<html>
		<head>
		<meta charset="UTF-8">
		<title>Email template</title>
		<style>
			body {
				font-family: Arial, sans-serif;
				background-color: #f6f6f6;
				margin: 10;
				padding: 10;
			}
			.footer {
				background-color: #f1f1f1;
				padding: 15px 30px;
				text-align: center;
				font-size: 13px;
				color: #777777;
			}
		</style>
		</head>
		<body>
		<div class="container">
			<div class="header">
			<h1><?php echo esc_html( $this->template['heading'] ?? ucfirst( str_replace( ['_', '-', ], ' ', $this->event ) ) ); ?></h1>
			</div>
			<div class="content">
				<?php echo wp_kses_post( $this->template() ); ?>
			</div>
			<div class="footer">
				<?php echo wp_kses_post( $this->settings['footer_text'] ); ?>
			</div>

		</div>
		</body>
		</html>
		<?php
		return ob_get_clean();
	}
}