<?php

namespace EDPW\Core\Controllers;

defined( 'ABSPATH' ) || exit;

use EDPW\Core\Helpers\EmailTemplate;
use EDPW\Core\Helpers\Input;
use EDPW\Core\Helpers\Util;
use EDPW\Core\Helpers\WC;
use EDPW\Core\Models\EmailTemplates;


class EmailManager {
	/**
	 * if email not found then reset the args array.
	 *
	 * @param array $args Email argument.
	 *
	 * @return array
	 */
	public static function preProcessArguments( $args ) {
		if ( isset( $args['email'] ) ) {
			return $args;
		}
		if ( ! isset( $args['order'] ) || ! isset( $args['email_heading'] ) ) {
			return $args;
		}
		$mailer = WC::getMailer();
		if ( ! isset( $mailer->emails ) ) {
			return $args;
		}

		foreach ( $mailer->emails as $email ) {
			if ( ! empty( $email->object ) && $args['email_heading'] == $email->heading ) {
				$args['email'] = $email;
				break;
			} else if ( ! empty( $email->settings ) && isset( $email->settings['heading'] ) && $args['email_heading'] == $email->settings['heading'] ) {
				$args['email'] = $email;
				break;
			}
		}

		return $args;
	}

	/**
	 * Override template path.
	 *
	 * @param string $located Email located path.
	 * @param string $template_name Template name.
	 * @param array $args Email argument.
	 * @param string $template_path Template path.
	 * @param string $default_path Default template path.
	 *
	 * @return string
	 */
	public static function overrideEmailTemplates( $located, $template_name, $args, $template_path, $default_path ) {
		if ( ! is_array( $args ) ) {
			return $located;
		}
		$args = apply_filters('edpw_precess_args_before_override_email',$args);
		$args = self::preProcessArguments( $args );
		if ( ! self::basicCheck( $args ) ) {
			return $located;
		}
		$template = self::hasCustomizedTemplate( $args );
		if ( ! empty( $template ) ) {

			return EDPW_PLUGIN_PATH . 'templates/email_template.php';
		}

		return $located;
	}

	/**
	 * Basic check.
	 *
	 * @param array $args Email argument.
	 *
	 * @return bool
	 */
	protected static function basicCheck( $args ) {
		if ( isset( $args['email']->id ) && ! empty( $args['email']->id ) ) {
			return true;
		}

		return false;
	}

	/**
	 * Has customized email template.
	 *
	 * @param array $args Email argument.
	 *
	 * @return false|object
	 */
	protected static function hasCustomizedTemplate( $args ) {
		if ( ! self::basicCheck( $args ) ) {
			return false;
		}
		$lang = self::getLanguageFromOrder( $args );
		$type = is_object( $args['email'] ) && ! empty( $args['email']->id ) ? $args['email']->id : '';

		if ( empty( $type ) || ! apply_filters( 'edpw_is_customize_plugin_active', false, $type, $args ) ) {
			return false;
		}

		if ( $type == 'customer_partially_refunded_order' ) {
			$type = 'customer_refunded_order';
		}
		$customizer_model = new EmailTemplates();
		$template         = $customizer_model->getActiveTemplate( $lang, $type );

		return empty( $template ) ? false : $template;
	}

	public static function isCustomizePluginActive( $status, $type, $args ) {
		if ( empty( $type ) ) {
			return $status;
		}

		if ( EmailTemplate::isWoocommerceTemplate( $type ) ) {
			return true;
		}
		if ( EmailTemplate::isWordPressTemplate( $type ) ) {
			return true;
		}

		return $status;
	}

	/**
	 * Get language from order.
	 *
	 * @param array $args Email argument.
	 *
	 * @return string
	 */
	public static function getLanguageFromOrder( $args ) {
		$selected_language                  = WC::getSiteDefaultLang();
		$load_language_from_order_for_admin = apply_filters( 'edpw_load_language_from_order_even_for_admin_emails', false, $args );
		if ( empty( $args['sent_to_admin'] ) || $load_language_from_order_for_admin ) {
			if ( ! empty( $args['order'] ) ) {
				$order    = WC::getOrder( $args['order'] );
				$language = WC::getOrderMeta( $order, 'wpml_language' );
				if ( ! empty( $language ) ) {
					$languages = WC::getWPMLLanguages();
					if ( isset( $languages[ $language ]['default_locale'] ) ) {
						$selected_language = $languages[ $language ]['default_locale'];
					}
				} else {
					//Translate Press
					$language = WC::getOrderMeta( $order, 'trp_language' );
					if ( ! empty( $language ) ) {
						$selected_language = $language;
					}
				}

			}

		}

		return $selected_language;
	}

	/**
	 * Render custom email template.
	 *
	 * @param array $args Email argument.
	 *
	 * @return string|null
	 */
	function getRenderedTemplate( $args ) {
		$args = apply_filters( 'edpw_before_render_template_args', $args );
		$args = self::preProcessArguments( $args );
		if ( ! self::basicCheck( $args ) ) {
			return null;
		}
		if ( $template = self::hasCustomizedTemplate( $args ) ) {

			if ( Input::get( 'preview_woocommerce_mail' ) === 'true' ) {
				$short_code_obj = new ShortCodes( $template->type, $template, $args, '', true );
				$html           = $short_code_obj->renderSampleTemplate( false, true );
				$html           = '<edpw>' . base64_encode( $html ) . '</edpw>';
			} else {
				$order_id = '';
				if ( isset( $args['order'] ) ) {
					$order_id = WC::getOrderId( $args['order'] );
				} elseif ( isset( $args['subscription'] ) ) {
					$subscription = $args['subscription'];
					if ( is_object( $subscription ) && WC::isMethodExists( $subscription, 'get_parent_id' ) ) {
						$order_id = $subscription->get_id();
					}
				}
				$email_heading  = isset( $args['email_heading'] ) ? $args['email_heading'] : '';
				$change_content = '<body><p style="display: none !important; visibility: hidden; opacity: 0; color: transparent; height: 0; width: 0; font-size: 0px; mso-hide: all; max-height: 0; line-height: 0;"><span>' . $email_heading . '</span></p>';
				$template->html = str_replace( '<body>', $change_content, $template->html );
				$short_code     = new ShortCodes( $args['email']->id, $template, $args, $order_id );
				$html           = $short_code->renderTemplate();
			}


			return $html;
		}

		return null;
	}

	public static function reproduceHtmlContent( $content ) {
		$regex       = '/<edpw>(.*?)<\/edpw>/';
		$new_matches = [];
		preg_match_all( $regex, $content, $new_matches, PREG_SET_ORDER );
		if ( empty( $new_matches ) || ! is_array( $new_matches ) ) {
			return $content;
		}

		if ( ! empty( $new_matches[0][1] ) ) {
			$autofix_broken_html = EmailTemplate::getSetting( 'autofix_broken_html', 1 );
			$decoded             = base64_decode( $new_matches[0][1] );

			if ( $autofix_broken_html == 1 ) {
				$content = self::wpautop( $decoded, false );
			} else {
				$content = $decoded;
			}
			$content = apply_filters( 'edpw_reproduce_html', $content );
		}


		return $content;
	}

	protected static function wpautop( $pee, $br = true ) {
		$pre_tags = array();
		if ( trim( $pee ) === '' ) {
			return '';
		}
		// Just to make things a little easier, pad the end.
		$pee = $pee . "\n";
		// Change multiple <br>s into two line breaks, which will turn into paragraphs.
		$allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary)';
		// Add a double line break above block-level opening tags.
		$pee = preg_replace( '!(<' . $allblocks . '[\s/>])!', "\n\n$1", $pee );
		// Add a double line break below block-level closing tags.
		$pee = preg_replace( '!(</' . $allblocks . '>)!', "$1\n\n", $pee );
		// Add a double line break after hr tags, which are self closing.
		$pee = preg_replace( '!(<hr\s*?/?>)!', "$1\n\n", $pee );
		// Standardize newline characters to "\n".
		$pee = str_replace( array( "\r\n", "\r" ), "\n", $pee );
		// Find newlines in all elements and add placeholders.
		$pee = wp_replace_in_html_tags( $pee, array( "\n" => ' <!-- wpnl --> ' ) );
		// Remove more than two contiguous line breaks.
		$pee = preg_replace( "/\n\n+/", "\n\n", $pee );
		// Add a closing <p> inside <div>, <address>, or <form> tag if missing.
		$pee = preg_replace( '!<p>([^<]+)</(div|address|form)>!', '<p>$1</p></$2>', $pee );
		// In some cases <li> may get wrapped in <p>, fix them.
		$pee = preg_replace( '|<p>(<li.+?)</p>|', '$1', $pee );
		// If a <blockquote> is wrapped with a <p>, move it inside the <blockquote>.
		$pee = preg_replace( '|<p><blockquote([^>]*)>|i', '<blockquote$1><p>', $pee );
		$pee = str_replace( '</blockquote></p>', '</p></blockquote>', $pee );
		// If a <br /> tag is after an opening or closing block tag, remove it.
		$pee = preg_replace( '!(</?' . $allblocks . '[^>]*>)\s*<br />!', '$1', $pee );
		// If a <br /> tag is before a subset of opening or closing block tags, remove it.
		$pee = preg_replace( '!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee );
		$pee = preg_replace( "|\n</p>$|", '</p>', $pee );
		// Replace placeholder <pre> tags with their original content.
		if ( ! empty( $pre_tags ) ) {
			$pee = str_replace( array_keys( $pre_tags ), array_values( $pre_tags ), $pee );
		}
		// Restore newlines in all elements.
		if ( false !== strpos( $pee, '<!-- wpnl -->' ) ) {
			$pee = str_replace( array( ' <!-- wpnl --> ', '<!-- wpnl -->' ), "\n", $pee );
		}
		// If an opening or closing block element tag is wrapped in a <p>, unwrap it.
		$pee = preg_replace( '!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', '$1', $pee );
		// If an opening or closing block element tag is preceded by an opening <p> tag, remove it.
		$pee = preg_replace( '!<p>\s*(</?' . $allblocks . '[^>]*>)!', '$1', $pee );
		// If an opening or closing block element tag is followed by a closing <p> tag, remove it.
		$pee = preg_replace( '!(</?' . $allblocks . '[^>]*>)\s*</p>!', '$1', $pee );
		// Under certain strange conditions it could create a P of entirely whitespace.
		$pee = preg_replace( '|<p>\s*</p>|', '', $pee );

		return str_replace( '!important', '', $pee );
	}
}