<?php
/**
 * A class used to send emails.
 */

namespace Simple_Giveaways;

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

/**
 * Class SG_Email
 */
class SG_Email {

	/**
	 * Email ID to identify it.
	 *
	 * @var string
	 */
	public $id = 'sg_email';

	/**
	 * Has the email being sent?
	 *
	 * @var bool
	 */
	protected $sent = false;

    /**
     * Flag if we're showing the unsubscribe link & if such email can't be sent if unsubscribed
     * @var bool
     */
    protected $can_unsubscribe = false;

	/**
	 * Data that can be passed.
	 *
	 * @var array
	 */
	protected $data = array();

    protected function can_send() {
        return true;
    }

	/**
	 * Sending a Giveaway Email with filtered contents.
	 *
	 * @param string|array $to      Emails
	 * @param string       $subject Email Subject.
	 * @param string       $message Email Message.
	 * @param string|array $headers Headers.
	 * @param array        $attachments Attachments.
	 *
	 * @return boolean
	 */
	public function send( $to, $subject, $message, $headers = '', $attachments = array() ) {
		if ( $this->is_email_disabled() ) {
			return true;
		}

        if ( ! $this->can_send() ) {
            return true;
        }

		add_filter( 'wp_mail_from', array( $this, 'from_email' ), 20 );
		add_filter( 'wp_mail_from_name', array( $this, 'from_name' ), 20 );
		add_filter( 'wp_mail_content_type', array( $this, 'content_type' ), 20 );

		$this->sent = false;
		$content    = $this->get_content( $message );
		$return     = wp_mail( $to, $subject, $content, $headers, $attachments );
		$this->sent = $return;

		remove_filter( 'wp_mail_content_type', array( $this, 'content_type' ), 20 );
		remove_filter( 'wp_mail_from', array( $this, 'from_email' ), 20 );
		remove_filter( 'wp_mail_from_name', array( $this, 'from_name' ), 20 );

		return $return;
	}

	/**
	 * Is email sent?
	 *
	 * @return bool
	 */
	public function is_sent() {
		return $this->sent;
	}

	/**
	 * Get Content
	 *
	 * @param $content
	 */
	public function get_content( $content ) {
        $content .= $this->get_unsubscribe_link();

		if ( 'plain' === $this->get_content_type() ) {
			$content = preg_replace( '/\<br(\s*)?\/?\>/i', "\n\n", $content );
			$content = esc_html( wp_strip_all_tags( wptexturize( $content ) ) );
		} else {
			$content = $this->get_header() . $content . $this->get_footer();
		}
		return $content;
	}

	/**
	 * Content Type.
	 *
	 * For now, we're sending only HTML emails.
	 *
	 * @param $type
	 *
	 * @return string
	 */
	public function content_type( $type ) {
		$content_type = 'text/html';

		if ( 'plain' === $this->get_content_type() ) {
			$content_type = 'text/plain';
		}

		return $content_type;
	}

	/**
	 * Return the Content Type of the email.
	 *
	 * @return string
	 */
	public function get_content_type() {
		$settings     = giveasap_get_settings();
		$content_type = 'html';

		if ( isset( $settings['email_type'] ) && $settings['email_type'] ) {
			$content_type = $settings['email_type'];
		}

		return $content_type;
	}

	/**
	 * Return if the email is disabled.
	 *
	 * @return string
	 */
	public function is_email_disabled() {
		$settings = giveasap_get_settings();
		return isset( $settings['email_disabled'] ) ? absint( $settings['email_disabled'] ) : false;
	}

	/**
	 * From email.
	 *
	 * @param string $email
	 *
	 * @return mixed
	 */
	public function from_email( $email ) {
		$settings = giveasap_get_settings();

		if ( isset( $settings['sender_email'] ) && is_email( $settings['sender_email'] ) ) {
			$_email = $settings['sender_email'];
		} else {
			$_email = get_option( 'admin_email', '' );
		}

		if ( $_email ) {
			$email = $_email;
		}

		return apply_filters( 'sg_from_email', $email );
	}

	/**
	 * From email Name.
	 *
	 * @param string $name
	 *
	 * @return mixed
	 */
	public function from_name( $name ) {
		$settings = giveasap_get_settings();

		if ( isset( $settings['sender_name'] ) ) {
			$_name = $settings['sender_name'];
		} else {
			$_name = get_bloginfo( 'name' );
		}

		if ( $_name ) {
			$name = $_name;
		}

		return apply_filters( 'sg_from_email_name', $name );
	}


    /**
     * @return bool
     */
    public function show_unsubscribe_link() {
        if ( ! $this->can_unsubscribe ) {
            return false;
        }

        $settings = giveasap_get_settings();

        return isset( $settings['allow_email_unsubscribe'] ) ? (bool) $settings['allow_email_unsubscribe'] : false;
    }



    public function get_unsubscribe_link() {
        if ( ! $this->show_unsubscribe_link() ) {
            return '';
        }

        $subscriber = $this->get_subscriber();
        $link       = add_query_arg(
            array(
                'giveasap_unsubscribe_id' => $subscriber->get_id(),
                'subscriber_hash' => md5( $subscriber->get_id() . $subscriber->get_giveaway()->get_id() . $subscriber->get_email() )
            ),
            get_home_url()
        );
        return '<p class="text-center margin-top"><a href="' . esc_url( $link ) . '" class="link">' . __( 'Unsubscribe from Giveaway emails', 'giveasap' ) . '</a></p>';
    }

	/**
	 * Return the inline styles for the email.
	 *
	 * @return string
	 */
	public function get_inline_styles() {
		$settings = giveasap_get_settings();
		// Load colors.
		$bg              = isset( $settings['email_background'] ) ? sanitize_text_field( $settings['email_background'] ) : '#a46497';
		$body            = isset( $settings['email_body_bg'] ) ? sanitize_text_field( $settings['email_body_bg'] ) : '#ffffff';
		$text            = isset( $settings['email_text_color'] ) ? sanitize_text_field( $settings['email_text_color'] ) : '#000000';
		$link_color      = isset( $settings['email_link_color'] ) ? sanitize_text_field( $settings['email_link_color'] ) : '#61ce70';
		$button_color    = isset( $settings['email_button_color'] ) ? sanitize_text_field( $settings['email_button_color'] ) : '#ffffff';
		$button_bg_color = isset( $settings['email_button_bg_color'] ) ? sanitize_text_field( $settings['email_button_bg_color'] ) : '#61ce70';

		// !important; is a gmail hack to prevent styles being stripped if it doesn't like something.
		ob_start();
		?>
		#wrapper {
		background-color: <?php echo esc_attr( $bg ); ?>;
		margin: 0;
		padding: 70px 0 70px 0;
		-webkit-text-size-adjust: none !important;
		width: 100%;
		}

		#template_container {
		box-shadow: 0 1px 4px rgba(0,0,0,0.1) !important;
		background-color: <?php echo esc_attr( $body ); ?>;
		border: 1px solid <?php echo esc_attr( $body ); ?>;
		border-radius: 3px !important;
		}

		#template_header {
		background-color: <?php echo esc_attr( $body ); ?>;
		border-radius: 3px 3px 0 0 !important;
		color: <?php echo esc_attr( $text ); ?>;
		border-bottom: 0;
		font-weight: bold;
		line-height: 100%;
		vertical-align: middle;
		font-family: "Helvetica Neue", Helvetica, Roboto, Arial, sans-serif;
		}

		#template_header h1,
		#template_header h1 a {
		color: <?php echo esc_attr( $text ); ?>;
		}

		#template_footer td {
		padding: 0;
		-webkit-border-radius: 6px;
		}

		#template_footer #credit {
		border:0;
		color: <?php echo esc_attr( $text ); ?>;
		font-family: Arial;
		font-size:12px;
		line-height:125%;
		text-align:center;
		padding: 0 48px 48px 48px;
		}

		#body_content {
		background-color: <?php echo esc_attr( $body ); ?>;
		}

		#body_content table td {
		padding: 48px 48px;
		}

		#body_content table td td {
		padding: 12px;
		}

		#body_content table td th {
		padding: 12px;
		}

		#body_content td ul.wc-item-meta {
		font-size: small;
		margin: 1em 0 0;
		padding: 0;
		list-style: none;
		}

		#body_content td ul.wc-item-meta li {
		margin: 0.5em 0 0;
		padding: 0;
		}

		#body_content td ul.wc-item-meta li p {
		margin: 0;
		}

		#body_content p {
		margin: 0 0 16px;
		}

		#body_content_inner {
		color: <?php echo esc_attr( $text ); ?>;
		font-family: "Helvetica Neue", Helvetica, Roboto, Arial, sans-serif;
		font-size: 14px;
		line-height: 150%;
		text-align: <?php echo is_rtl() ? 'right' : 'left'; ?>;
		}

		.td {
		color: <?php echo esc_attr( $text ); ?>;
		border: 1px solid <?php echo esc_attr( $body ); ?>;
		vertical-align: middle;
		}

		.address {
            padding: 12px;
            color: <?php echo esc_attr( $text ); ?>;
            border: 1px solid <?php echo esc_attr( $body ); ?>;
		}

		.text {
		color: <?php echo esc_attr( $text ); ?>;
		font-family: "Helvetica Neue", Helvetica, Roboto, Arial, sans-serif;
		}

		.link {
		color: <?php echo esc_attr( $link_color ); ?>;
		}

		.text-center {
		    text-align: center;
		}

		#body_content .margin-top {
		    margin-top: 16px;
		}

		.sg-button {
		  background-color: <?php echo esc_attr( $button_bg_color ); ?>;
		  color: <?php echo esc_attr( $button_color ); ?>;
		  width: 100%;
		  display: block;
		  height: 40px;
		  line-height: 40px;
		  text-align:center;
		  margin-bottom: 1em;
		  text-decoration: none;
		}

		#header_wrapper {
		padding: 36px 48px;
		display: block;
		}

		h1 {
		color: <?php echo esc_attr( $text ); ?>;
		font-family: "Helvetica Neue", Helvetica, Roboto, Arial, sans-serif;
		font-size: 30px;
		font-weight: 300;
		line-height: 150%;
		margin: 0;
		text-align: <?php echo is_rtl() ? 'right' : 'left'; ?>;
		text-shadow: 0 1px 0 <?php echo esc_attr( $text ); ?>;
		}

		h2 {
		color: <?php echo esc_attr( $text ); ?>;
		display: block;
		font-family: "Helvetica Neue", Helvetica, Roboto, Arial, sans-serif;
		font-size: 18px;
		font-weight: bold;
		line-height: 130%;
		margin: 0 0 18px;
		text-align: <?php echo is_rtl() ? 'right' : 'left'; ?>;
		}

		h3 {
		color: <?php echo esc_attr( $text ); ?>;
		display: block;
		font-family: "Helvetica Neue", Helvetica, Roboto, Arial, sans-serif;
		font-size: 16px;
		font-weight: bold;
		line-height: 130%;
		margin: 16px 0 8px;
		text-align: <?php echo is_rtl() ? 'right' : 'left'; ?>;
		}

		a {
		color: <?php echo esc_attr( $link_color ); ?>;
		font-weight: normal;
		text-decoration: underline;
		}

		img {
		border: none;
		display: inline-block;
		font-size: 14px;
		font-weight: bold;
		height: auto;
		outline: none;
		text-decoration: none;
		text-transform: capitalize;
		vertical-align: middle;
		margin-<?php echo is_rtl() ? 'left' : 'right'; ?>: 10px;
		}

		#template_header_image img {margin: 0 auto;}

		.sg-email-table {
			border: 1px solid <?php echo esc_html( $text ); ?>;
			border-collapse: collapse;
		}

		.sg-email-table td,
		.sg-email-table th {
			text-align: left;
			border-bottom: 1px solid <?php echo esc_html( $text ); ?>;
		}

		.sg-email-table th {
			width: 150px;
			width: 30%;
			border-right: 1px solid <?php echo esc_html( $text ); ?>;
		}
		<?php
		return ob_get_clean();
	}

	/**
	 * This styles are for responsive emails.
	 *
	 * Since WooCommerce uses Emogrifier, all styles are set inline which won't work for responsive styles.
	 */

	public function get_responsive_style() {

		?>

	/*  Media Queries */
	@media only screen and (max-width: 767px) {

		img.logo {
		  max-width: 124px !important;
		}

		#body_content table td {
			padding: 24px;
		}

		table { table-layout: fixed; width: 100%; }
		table td, table th {word-break: break-all;}

		h1 {font-size: 30px !important;}
		h2 {font-size: 20px !important;}
		h3 {font-size: 18px !important;}
		h4 {font-size: 16px !important;}
		h5 {font-size: 14px !important;}
		h6 {font-size: 12px !important;}
		body, table.body, p, td {font-size: 15px !important;line-height:20px !important;}


		p.lead, p.lede, p.leed {
		  font-size: 17px !important;
		  line-height:21px !important;
		}

		#template_container {
			width: 480px !important;
		}

		 #template_body {
			width: 100% !important;
		 }

	}

	/*  Media Queries */
	@media only screen and (max-width: 480px) {


		#template_container {
		  width: 335px !important;
		  margin: 0 auto;
		}



	}

		/*  Media Queries */
	@media only screen and (max-width: 360px) {




		 #template_container {
			width: 315px !important;
			margin: 0 auto;
		 }



	}
		<?php

	}

	/**
	 * Get the email header
	 *
	 * @param string $email_heading
	 */
	public function get_header( $email_heading = '' ) {
		$settings = giveasap_get_settings();
		$logo     = isset( $settings['email_logo'] ) ? absint( $settings['email_logo'] ) : 0;

		if ( $logo ) {
			$image = wp_get_attachment_image_src( $logo );
			if ( is_array( $image ) ) {
				$logo = $image[0];
			} else {
				$logo = false;
			}
		}
		ob_start();
		?>
		<!DOCTYPE html>
		<html <?php language_attributes(); ?>>
		<head>
			<meta http-equiv="Content-Type" content="text/html; charset=<?php esc_attr( bloginfo( 'charset' ) ); ?>" />
			<title><?php echo esc_html( get_bloginfo( 'name', 'display' ) ); ?></title>
			<style type="text/css"><?php echo $this->get_inline_styles(); ?></style>
			<style type="text/css"><?php echo $this->get_responsive_style(); ?></style>
		</head>
		<body <?php echo is_rtl() ? 'rightmargin' : 'leftmargin'; ?>="0" marginwidth="0" topmargin="0" marginheight="0" offset="0">

		<div id="wrapper" dir="<?php echo is_rtl() ? 'rtl' : 'ltr'; ?>">
			<table border="0" cellpadding="0" cellspacing="0" height="100%" width="100%">
				<tr>
					<td align="center" valign="top">
						<div id="template_header_image">
							<?php
							if ( $logo ) {
								echo '<p style="margin-top:0;"><img src="' . esc_url( $logo ) . '" alt="' . esc_attr( get_bloginfo( 'name', 'display' ) ) . '" /></p>';
							}
							?>
						</div>
						<table border="0" cellpadding="0" cellspacing="0" width="600" id="template_container">
							<?php
							if ( $email_heading ) {
								?>
							<tr>
								<td align="center" valign="top">
									<!-- Header -->
									<table border="0" cellpadding="0" cellspacing="0" width="600" id="template_header">
										<tr>
											<td id="header_wrapper">
												<h1><?php echo esc_html( $email_heading ); ?></h1>
											</td>
										</tr>
									</table>
									<!-- End Header -->
								</td>
							</tr>
							<?php } ?>
							<tr>
								<td align="center" valign="top">
									<!-- Body -->
									<table border="0" cellpadding="0" cellspacing="0" width="600" id="template_body">
										<tr>
											<td valign="top" id="body_content">
												<!-- Content -->
												<table border="0" cellpadding="20" cellspacing="0" width="100%">
													<tr>
														<td valign="top">
															<div id="body_content_inner">
																<?php
																return ob_get_clean();

	}

	public function get_footer() {
		ob_start();
		?>
															</div>
														</td>
													</tr>
												</table>
												<!-- End Content -->
											</td>
										</tr>
									</table>
									<!-- End Body -->
								</td>
							</tr>
						</table>
					</td>
				</tr>
			</table>
		</div>
		</body>
		</html>
		<?php
		return ob_get_clean();
	}

	/**
	 * Set the data.
	 *
	 * @param array $data
	 */
	public function set_data( $data = array() ) {
		$this->data = $data;
	}

	/**
	 * Get the data.
	 *
	 * @return array
	 */
	public function get_data() {
		return $this->data;
	}

	/**
	 * Process the Email.
	 * This is method is used for custom email types to send their custom emails.
	 * This method should utilize the send() method.
	 *
	 * @since 2.18.0
	 *
	 * @return mixed
	 */
	public function process() {}
}
