<?php

use Tbm_Tagmailer_Display_Layouts as Layouts;

class Tbm_Tagmailer_Display {

	/**
	 * @var Tbm_Tagmailer_Display_Layouts
	 */
	private $layouts;
	public $common;

	function __construct() {
		$this->layouts = new Layouts();
		$this->common  = new Tbm_Tagmailer_Common();
	}

	/**
	 * Get the title from ACF and replace the date and the first title
	 *
	 * @param $type int The type of the newsletter
	 * @param $today int The number of days from today (-1 is yesterday, 0 is today, 1 is tomorrow)
	 *
	 * @return string
	 */
	private function html_get_title( $type, $today ) {
		// Get the title from ACF
		$title_in_option = get_field( "tbm_" . $type . "_nl_newsletter_title", "option" );

		if ( empty( $title_in_option ) ) {
			return 'Novità dal mondo di ' . get_bloginfo( 'name' );
		}

		// Get the date
		$date = date_i18n( 'j F Y', strtotime( $today . " days" ) );

		// Get the first title
		$first_title = get_query_var( 'first_title' );

        // Sanitize first title
		$first_title = $this->common->tbm_replace_wp_entities( $first_title );

		// Replace the date and the first title
		return str_replace( array( '%date%', '%post%' ), array( $date, $first_title ), $title_in_option );

	}

	private function html_get_excerpt( $type = "1" ): string {
		$excerpt = get_field( "tbm_" . $type . "_nl_newsletter_excerpt", "option" );

		if ( $excerpt ) {
			return "<span class='preheader'>{$excerpt}</span>";
		}

		return '';
	}

	private function html_newsletter_code( $type = "1", $today = 0, $print_spot = true ) {
		// Default options
		$defaults = $this->html_get_nl_defaults( $type, $today );

		// get ACF options
		$blocks              = get_field( "tbm_" . $type . "_nl_blocchi_newsletter", "option" );
		$logo_newsletter     = get_field( "tbm_" . $type . "_nl_newsletter_logo", "option" );
		$url_logo_newsletter = get_field( "tbm_" . $type . "_nl_newsletter_logo_url", "option" );
		$subtitle            = get_field( "tbm_" . $type . "_nl_newsletter_subtitle", "option" ) ? get_field( "tbm_" . $type . "_nl_newsletter_subtitle", "option" ) : date_i18n( 'j F Y', $defaults['tbm_nl_today'] );
		$subtitle            = apply_filters( 'newsletter_subtitle', $subtitle );
		$css                 = file_exists( TBM_TAGMAILER_PLUGIN_DIR . 'public/css/tbm-tagmailer-newsletter.min.css' ) ? file_get_contents( TBM_TAGMAILER_PLUGIN_DIR . 'public/css/tbm-tagmailer-newsletter.min.css' ) : '';
		//@formatter:off

        //save code in
		?>

		<!doctype html>
		<html lang="<?php get_bloginfo( 'language' ); ?>">
		<head>
			<meta name="viewport" content="width=device-width">
			<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
			<title>%%nl_title%%</title>
			<link href="<?php echo $defaults['tbm_nl_web_font']; ?>" rel="stylesheet">
			<style type="text/css">
				<?php echo $css; ?>
			</style>
		</head>
		<body style="margin: 0; padding: 0;">
		<!-- Pre-header -->
		%%nl_excerpt%%

		<!-- Analytics -->
		<table cellpadding="0" cellspacing="0" border="0" width="100%" style="background: #f5f8fa; min-width: 300px; font-size: 1px; line-height: normal;">
			<tr>
				<td align="center" valign="top">
					<!--[if (gte mso 9)|(IE)]>
					<table border="0" cellspacing="0" cellpadding="0">
						<tr>
							<td align="center" valign="top" width="630"><![endif]-->
					<table cellpadding="0" cellspacing="0" border="0" width="630" class="table630"
					       style="width: 100%; max-width: 630px; min-width: 300px; background: #f5f8fa;">
						<tr>
							<td class="mob_pad" width="25" style="width: 25px; max-width: 25px; min-width: 25px;">&nbsp;
							</td>
							<td align="center" valign="top" style="background: #ffffff;">
								<!-- Spot -->
								<?php echo ( $print_spot  ) ? $this->html_print_spot( $type, "{PRINT_SPOT}" ) : "{PRINT_SPOT}"; ?>

								<!-- Logo -->
								<table cellpadding="0" cellspacing="0" border="0" width="88%"
								       style="width: 88% !important; min-width: 88%; max-width: 88%;">
									<tr>
										<td align="left" valign="top">
											<div style="height: 30px; line-height: 30px; font-size: 28px;">&nbsp;</div>
											<!--[if (gte mso 9)|(IE)]>
											<table border="0" cellspacing="0" cellpadding="0">
												<tr>
													<td align="center" valign="top" width="460"><![endif]-->
											<div style="display: inline-block; vertical-align: top; width: 59%; min-width: 130px;">
												<table cellpadding="0" cellspacing="0" border="0" width="100%"
												       style="width: 100% !important; min-width: 100%; max-width: 100%;">
													<tr>
														<td align="left" valign="top">
															<div style="height: 10px; line-height: 10px; font-size: 8px;">
																&nbsp;
															</div>
															<a href="<?php echo $url_logo_newsletter; ?>" target="_blank">
																<img src="<?php echo $logo_newsletter["url"]; ?>" alt="img"
																     width="200" border="0"
																     style="display: block; width: 170px;"/>
															</a>
														</td>
													</tr>
												</table>
											</div>
											<!--[if (gte mso 9)|(IE)]></td>
											<td align="center" valign="top" width="150"><![endif]-->
											<div style="display: inline-block; vertical-align: top;width: 39%;">
												<table cellpadding="0" cellspacing="0" border="0" width="100%"
												       style="width: 100% !important; min-width: 100%; max-width: 100%;">
													<tr>
														<td class="mob_left" align="right" valign="top">
															<div style="height: 15px; line-height: 15px; font-size: 13px;">
																&nbsp;
															</div>
															<font face="<?php echo $defaults['tbm_nl_font_family']; ?>" color="#949494"
															      style="font-size: 14px; line-height: 18px; mso-line-height-rule:exactly;font-weight: 700;">
																<span style="font-family: <?php echo $defaults['tbm_nl_font_family']; ?>; color: #949494; font-size: 14px; line-height: 18px; mso-line-height-rule:exactly;font-weight: 700;"><?php echo $subtitle; ?></span>
															</font>
														</td>
													</tr>
												</table>
											</div>
											<!--[if (gte mso 9)|(IE)]>
											</td></tr>
											</table><![endif]-->
											<div class="top_pad2" style="height: 40px; line-height: 40px; font-size: 38px;">
												&nbsp;
											</div>
										</td>
									</tr>
								</table>

								<!-- Blocchi -->
								<?php
								//@formatter:on
								foreach ( $blocks as $block ) {

									$args          = wp_parse_args( $block, $defaults );
									$args          = (object) $args;
									$acf_fc_layout = $block["acf_fc_layout"] ?? null;

									switch ( $acf_fc_layout ) {
										case "tbm_nl_title":
											$this->layouts->html_newsletter_display_title( $args );
											break;

										case "tbm_nl_button":
											$this->layouts->html_newsletter_display_button( $args );
											break;

										/**
										 * ! Post: singular
										 */
										case "tbm_nl_post":
											$this->layouts->html_newsletter_display_post( $args );
											break;

										/**
										 * ! Posts: plural
										 */
										case "tbm_nl_posts":
											$this->layouts->html_newsletter_display_posts( $args );
											break;

										case "tbm_nl_categories":
											$this->layouts->html_newsletter_display_posts_from_categories( $args );
											break;

										case "tbm_nl_tags":
											$this->layouts->html_newsletter_display_posts_from_tags( $args );
											break;

										case "tbm_nl_posttypes":
											$this->layouts->html_newsletter_display_posts_from_post_type( $args );
											break;

										case "tbm_nl_html_code_group":
											$this->layouts->html_newsletter_display_html_code( $args );
											break;

										case "tbm_nl_banner":
											$this->layouts->html_newsletter_display_banner( $args );
											break;
									}

								}
								//@formatter:off
								?>

								<!-- Disclaimer -->
								<table cellpadding="0" cellspacing="0" border="0" width="88%"
								       style="width: 88% !important; min-width: 88%; max-width: 88%;">
									<tr>
										<td class="mob_left" align="center" valign="top">
											<div style="height: 25px; line-height: 25px; font-size: 23px;">&nbsp;</div>
											<font face="<?php echo $defaults['tbm_nl_font_family']; ?>" color="#767676"
											      style="font-size: 10px; line-height: 17px;mso-line-height-rule:exactly;">
												<span style="font-family: <?php echo $defaults['tbm_nl_font_family']; ?>; color: #767676; font-size: 12px; line-height: 17px;mso-line-height-rule:exactly;"><?php echo $args->tbm_nl_newsletter_disclaimer; ?></span>
												<span style="font-family: <?php echo $defaults['tbm_nl_font_family']; ?>; color: #767676; font-size: 12px; line-height: 17px;mso-line-height-rule:exactly;">Se non vuoi più ricevere questa newsletter, puoi <a
														href="{url:cancellazione}">annullare l'iscrizione</a>.</span>
											</font>
											<div style="height: 28px; line-height: 28px; font-size: 26px;">&nbsp;</div>
										</td>
									</tr>
								</table>

							</td>
							<td class="mob_pad" width="25" style="width: 25px; max-width: 25px; min-width: 25px;">&nbsp;
							</td>
						</tr>
					</table>
					<!--[if (gte mso 9)|(IE)]>
					</td></tr>
					</table><![endif]-->
				</td>
			</tr>
		</table>
		</body>
		</html>

		<?php
		//@formatter:on
	}

	private function html_get_nl_defaults( $type, $today ) {

		$defaults = array(
			'tbm_nl_today'                 => strtotime( date( 'Y-m-d', strtotime( $today . " days" ) ) ),
			'tbm_nl_ignore_post_date'      => false,
			'tbm_nl_random_content'        => false,
			'tbm_nl_last_number'           => 0,
			'tbm_nl_last_date'             => 0,
			'tbm_nl_title'                 => '',
			'tbm_nl_use_featured_img'      => '',
			'tbm_nl_layout'                => '',
			'tbm_nl_numbers'               => '',
			'tbm_nl_html_code'             => '',
			'tbm_nl_block_title'           => '',
			'tbm_nl_last_post'             => '',
			'tbm_nl_post'                  => '',
			'tbm_nl_posts'                 => '',
			'tbm_nl_category'              => '',
			'tbm_nl_tag'                   => '',
			'tbm_nl_post_type'             => '',
			'tbm_nl_posttypes_site'        => '',
			'tbm_nl_post_not_in'           => array(),
			'tbm_nl_post_type_label'       => get_field( "tbm_" . $type . "_nl_post_type_label", "option" ) ?: 'category',
			'tbm_nl_pilot_post_type'       => get_field( "tbm_" . $type . "_nl_pilot_post_type", "option" ) ?: 'post',
			'tbm_nl_newsletter_days_ago'   => (int) get_field( "tbm_" . $type . "_nl_newsletter_days_ago", "option" ),
			'tbm_nl_newsletter_disclaimer' => get_field( "tbm_" . $type . "_nl_newsletter_disclaimer", "option" ),
			'tbl_nl_primary_color'         => get_field( "tbm_" . $type . "_nl_primary_color_newsletter", "option" ) ?: '#e8081b',
			'tbl_nl_label_color'           => get_field( "tbm_" . $type . "_nl_label_color_newsletter", "option" ) ?: '#e8081b',
			'tbl_nl_heading_color'         => get_field( "tbm_" . $type . "_nl_heading_color_newsletter", "option" ) ?: '#fff',
			'tbm_nl_web_font'              => get_field( "tbm_" . $type . "_nl_web_font", "option" ) ?: 'https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700',
			'tbm_nl_font_family'           => get_field( "tbm_" . $type . "_nl_font_family", "option" ) ?: "'Source Sans Pro', sans-serif",
			'tbm_nl_utm_source'            => get_field( "tbm_" . $type . "_nl_utm_source", "option" ) ?: 'newsletter',
			'tbm_nl_utm_medium'            => get_field( "tbm_" . $type . "_nl_utm_medium", "option" ) ?: 'email',
			'tbm_nl_utm_campaign'          => get_field( "tbm_" . $type . "_nl_utm_campaign", "option" ) ?: 'Newsletter: ' . get_bloginfo( 'name' ),
			'tbm_nl_font_title_multiplier' => get_field( "tbm_" . $type . "_nl_font_title_multiplier", "option" ) ?: 1,
			'tbl_nl_type'                  => $type
		);

		/**
		 * Filter the whole array
		 */
		return apply_filters( 'html_get_nl_defaults', $defaults, $type );

	}

	private function html_print_spot( $type = "1", $content = null ) {
		if ( ! ( strpos( $content, '{PRINT_SPOT}' ) !== false ) ) {
			return $content;
		}

		$this_spot = get_field( "tbm_" . $type . "_nl_spot", "option" );
		$__spot    = ( ! empty( $this_spot ) ) ? $this_spot : "{txt:spot}";
		ob_start(); ?>
        <table cellpadding="0" cellspacing="0" border="0" width="88%"
               style="width: 88% !important; min-width: 88%; max-width: 88%;">
            <tr>
                <td style="font-weight:400;vertical-align:top;color:#222;font-size:14px;margin:0;line-height:19px;border:0;text-align:center;border-collapse:collapse">
					<?php echo $__spot; ?>
                </td>
            </tr>
        </table>
		<?php
		$print_spot = ob_get_contents();
		ob_end_clean();

		return str_replace( "{PRINT_SPOT}", $print_spot, $content );
	}

	public function html_newsletter_html( int $type, int $today ) {
		/**
		 * Get the code
		 */
		ob_start();
		$this->html_newsletter_code( $type, $today, false );
		$html_uncompressed = ob_get_contents();
		ob_end_clean();

        // Get the excerpt and the title
		$tbm_nl_excerpt = $this->html_get_excerpt( $type );
		$tbm_nl_title   = $this->html_get_title( $type, $today );

		$html = str_replace( '%%nl_excerpt%%', $tbm_nl_excerpt, $html_uncompressed );
		$html = str_replace( '%%nl_title%%', $tbm_nl_title, $html );

		echo $html;

	}

	public function html_newsletter_xml( int $type, int $today ) {

		$tbm_nl_suspend = get_field( "tbl_nl_suspend", "option" ) ? 'true' : 'false';


		header( "Content-type: text/xml", true );

		/**
		 * Get the code.
		 */
		ob_start();
		$this->html_newsletter_code( $type, $today, false );
		$html = ob_get_contents();
		ob_end_clean();

        //  Get the excerpt and the title
		$tbm_nl_excerpt = $this->html_get_excerpt( $type );
		$tbm_nl_title   = $this->html_get_title( $type, $today );

		/**
		 * Escape the title.
		 */
		$tbm_nl_title = htmlspecialchars( $tbm_nl_title, ENT_XML1 );

		$html = str_replace( '%%nl_excerpt%%', $tbm_nl_excerpt, $html );
		$html = str_replace( '%%nl_title%%', $tbm_nl_title, $html );

		$cleanedHtml = preg_replace( '/\s+/', ' ', $html );
		$cleanedHtml = str_replace( "\n", '', $cleanedHtml );

		//@formatter:off
		echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
		?>
        <Messaggi>
        <xs:schema id="Messaggi" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema"
                   xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
            <xs:element name="Messaggi" msdata:IsDataSet="true" msdata:Locale="it-IT">
                <xs:complexType>
                    <xs:choice maxOccurs="unbounded">
                        <xs:element name="Messaggio">
                            <xs:complexType>
                                <xs:sequence>
                                    <xs:element name="DataControllo" type="xs:string"/>
                                    <xs:element name="Oggetto" type="xs:string"/>
                                    <xs:element name="Testo" type="xs:string"/>
                                    <xs:element name="Html" type="xs:string"/>
                                </xs:sequence>
                            </xs:complexType>
                        </xs:element>
                    </xs:choice>
                </xs:complexType>
            </xs:element>
        </xs:schema>
        <Messaggio>
            <NonInviare><?php echo $tbm_nl_suspend; ?></NonInviare>
            <DataControllo><?php echo date( "d/m/Y", strtotime( $today . " days" ) ); ?></DataControllo>
            <Oggetto><?php echo $tbm_nl_title; ?></Oggetto>
            <Testo></Testo>
            <Html><![CDATA[<?php echo  $this->html_print_spot( $type, $cleanedHtml ); ?>
            ]]>
            </Html>
        </Messaggio>
        </Messaggi><?php
		//@formatter:on
	}

}
