<?php
/**
 * Email Notification Handler
 *
 * @package WooCommerce Points and Rewards
 * @version 1.0.0
 */

namespace DDWCPointsAndRewards\Includes;

use DDWCPointsAndRewards\Helper\Point\DDWCPR_Point_Helper;
use DDWCPointsAndRewards\Helper\Reward\DDWCPR_Reward_Helper;

defined( 'ABSPATH' ) || exit();

if ( ! class_exists( 'DDWCPR_Email_Notification_Handler' ) ) {
	/**
	 * Email Notification Handler class.
	 */
	class DDWCPR_Email_Notification_Handler extends \WC_Email {
		/**
		 * Footer variable
		 *
		 * @var string
		 */
		protected $footer;

		/**
		 * Constructor.
		 */
		public function __construct() {
			$this->id               = 'ddwcpr_notification';
			$this->title            = esc_html__( 'LoyaltyX Notification', 'loyaltyx-points-and-rewards-for-woocommerce' );
			$this->heading          = esc_html__( 'LoyaltyX Notification', 'loyaltyx-points-and-rewards-for-woocommerce' );
			$this->subject          = '[' . get_option( 'blogname' ) . '] ' . esc_html__( 'LoyaltyX Notification', 'loyaltyx-points-and-rewards-for-woocommerce' );
			$this->description      = esc_html__( 'This email is sent to customers when their reward points balance changes, including earning, redeeming, or expiring points.', 'loyaltyx-points-and-rewards-for-woocommerce' );
			$this->template_html    = 'emails/points-and-rewards.php';
			$this->template_plain   = 'emails/plain/points-and-rewards.php';
			$this->template_base    = DDWCPR_PLUGIN_FILE . 'templates/';
			$this->footer           = esc_html__( 'Thank you for being a valued member of our rewards program!', 'loyaltyx-points-and-rewards-for-woocommerce' );

			add_action( 'ddwcpr_mail_notification', [ $this, 'trigger' ] );

			// Call parent constructor
			parent::__construct();

			// Other settings
			$this->recipient = $this->get_option( 'recipient', get_option( 'admin_email' ) );
			$this->subject   = $this->get_option( 'subject' );
			$this->heading   = $this->get_option( 'heading' );

			if ( ! $this->subject ) {
				$this->subject = '[' . get_option( 'blogname' ) . '] ' . esc_html__( 'LoyaltyX Notification', 'loyaltyx-points-and-rewards-for-woocommerce' );
			}

			if ( ! $this->heading ) {
				$this->heading = esc_html__( 'LoyaltyX Notification', 'loyaltyx-points-and-rewards-for-woocommerce' );
			}
		}

		/**
		 * Trigger.
		 *
		 * @param array $data
		 * @return void
		 */
		public function trigger( $data ) {
			if ( empty( $data ) ) {
				return;
			}

			$this->email_data   = $data;
			$this->display_name = '';
			$this->user_id      = '';

			if ( ! empty( $data['email'] ) ) {
				$this->recipient = $data['email'];
			}

			if ( ! empty( $data['display_name'] ) ) {
				$this->display_name = $data['display_name'];
			}

			if ( ! empty( $data['user_id'] ) ) {
				$this->user_id = $data['user_id'];
			}

			if ( ! empty( $data['heading'] ) ) {
				$this->settings['heading'] = $this->replace_placeholders( $data['heading'] );
			}

			if ( ! empty( $data['subject'] ) ) {
				$this->settings['subject'] = $this->replace_placeholders( $data['subject'] );
			}

			$this->email_message = is_string( $data['message'] ) ? $this->replace_placeholders( $data['message'] ) : $data['message'];

			if ( $this->is_enabled() && $this->get_recipient() ) {
				$this->send( $this->get_recipient(), $this->get_subject(), $this->get_content(), $this->get_headers(), $this->get_attachments() );
			}
		}

		/**
		 * Replace placeholder text in strings.
		 *
		 * @since  3.7.0
		 * @param  string $string Email footer text.
		 * @return string         Email footer text with any replacements done.
		 */
		public function replace_placeholders( $string ) {
			global $ddwcpr_configuration;
			$domain        = wp_parse_url( home_url(), PHP_URL_HOST );
			$point_helper  = new DDWCPR_Point_Helper( $ddwcpr_configuration );
			$reward_helper = new DDWCPR_Reward_Helper( $ddwcpr_configuration );

			return str_replace(
				[
					'[[site_title]]',
					'[[site_address]]',
					'[[site_url]]',
					'[[user_display_name]]',
					'[[user_email]]',
					'[[points_amount]]',
					'[[points_label]]',
					'[[manual_adjustment_description]]',
					'[[user_earned_points]]',
					'[[user_available_points]]',
					'[[points_reason]]',
					'[[coupon_code]]',
					'[[coupon_details]]',
				],
				[
					$this->get_blogname(),
					$domain,
					$domain,
					$this->display_name,
					$this->recipient,
					! empty( $this->email_data['points_amount'] ) ? $this->email_data['points_amount'] : '',
					ddwcpr_get_points_label( ! empty( $this->email_data['points_amount'] ) ? $this->email_data['points_amount'] : 0 ),
					! empty( $this->email_data['manual_adjustment_description'] ) ? $this->email_data['manual_adjustment_description'] : '',
					$point_helper->ddwcpr_get_user_earned_points( $this->user_id ),
					$point_helper->ddwcpr_get_user_available_points( $this->user_id ),
					! empty( $this->email_data['event'] ) && ! empty( $ddwcpr_configuration['points_reason'][ $this->email_data['event'] ] ) ? $ddwcpr_configuration['points_reason'][ $this->email_data['event'] ] : '',
					! empty( $this->email_data['related_id'] ) ? wc_get_coupon_code_by_id( $this->email_data['related_id'] ) : '',
					! empty( $this->email_data['related_id'] ) ? $reward_helper->ddwcpr_get_coupon_details_html( $this->email_data['related_id'] ) : '',
				],
				$string
			);
		}

		/**
		 * Initialise settings form fields.
		 */
		public function init_form_fields() {
			/* translators: %s: list of placeholders */
			$placeholder_text  = sprintf( esc_html__( 'Available placeholders: %s', 'loyaltyx-points-and-rewards-for-woocommerce' ), '<code>' . implode( '</code>, <code>', array_keys( $this->placeholders ) ) . '</code>' );
			$this->form_fields = [
				'enabled'            => [
					'title'   => esc_html__( 'Enable/Disable', 'loyaltyx-points-and-rewards-for-woocommerce' ),
					'type'    => 'checkbox',
					'label'   => esc_html__( 'Enable this email notification', 'loyaltyx-points-and-rewards-for-woocommerce' ),
					'default' => 'yes',
				],
				'recipient'          => [
					'title'       => esc_html__( 'Recipient(s)', 'loyaltyx-points-and-rewards-for-woocommerce' ),
					'type'        => 'text',
					/* translators: %s: WP admin email */
					'description' => sprintf( esc_html__( 'Enter recipients (comma separated) for this email. Defaults to %s.', 'loyaltyx-points-and-rewards-for-woocommerce' ), '<code>' . esc_attr( get_option( 'admin_email' ) ) . '</code>' ),
					'placeholder' => '',
					'default'     => '',
					'desc_tip'    => true,
				],
				'subject'            => [
					'title'       => esc_html__( 'Subject', 'loyaltyx-points-and-rewards-for-woocommerce' ),
					'type'        => 'text',
					'desc_tip'    => true,
					'description' => $placeholder_text,
					'placeholder' => $this->get_default_subject(),
					'default'     => '',
				],
				'heading'            => [
					'title'       => esc_html__( 'Email heading', 'loyaltyx-points-and-rewards-for-woocommerce' ),
					'type'        => 'text',
					'desc_tip'    => true,
					'description' => $placeholder_text,
					'placeholder' => $this->get_default_heading(),
					'default'     => '',
				],
				'additional_content' => [
					'title'       => esc_html__( 'Additional content', 'loyaltyx-points-and-rewards-for-woocommerce' ),
					'description' => esc_html__( 'Text to appear below the main email content.', 'loyaltyx-points-and-rewards-for-woocommerce' ) . ' ' . $placeholder_text,
					'css'         => 'width:400px; height: 75px;',
					'placeholder' => esc_html__( 'N/A', 'loyaltyx-points-and-rewards-for-woocommerce' ),
					'type'        => 'textarea',
					'default'     => $this->get_default_additional_content(),
					'desc_tip'    => true,
				],
				'email_type'         => [
					'title'       => esc_html__( 'Email type', 'loyaltyx-points-and-rewards-for-woocommerce' ),
					'type'        => 'select',
					'description' => esc_html__( 'Choose which format of email to send.', 'loyaltyx-points-and-rewards-for-woocommerce' ),
					'default'     => 'html',
					'class'       => 'email_type wc-enhanced-select',
					'options'     => $this->get_email_type_options(),
					'desc_tip'    => true,
				],
			];
		}

		/**
		 * Get content html.
		 *
		 * @return string
		 */
		public function get_content_html() {
			return wc_get_template_html(
				$this->template_html, [
					'email_heading'      => $this->get_heading(),
					'email_message'      => $this->email_message,
					'additional_content' => $this->get_additional_content(),
					'display_name'       => $this->display_name,
					'user_id'            => $this->user_id,
					'customer_email'     => $this->get_recipient(),
					'blogname'           => $this->get_blogname(),
					'sent_to_admin'      => false,
					'plain_text'         => false,
					'email'              => $this,
				], '', $this->template_base
			);
		}

		/**
		 * Get content plain.
		 *
		 * @return string
		 */
		public function get_content_plain() {
			return wc_get_template_html(
				$this->template_plain, [
					'email_heading'      => $this->get_heading(),
					'email_message'      => $this->email_message,
					'additional_content' => $this->get_additional_content(),
					'display_name'       => $this->display_name,
					'user_id'            => $this->user_id,
					'customer_email'     => $this->get_recipient(),
					'blogname'           => $this->get_blogname(),
					'sent_to_admin'      => false,
					'plain_text'         => true,
					'email'              => $this,
				], '', $this->template_base
			);
		}
	}
}
