<?php
/**
 * This file belongs to the YIT Framework.
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE (GPL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-3.0.txt
 *
 * @package YITH\PreOrder\Includes\Emails
 * @author YITH <plugins@yithemes.com>
 */

if ( ! defined( 'YITH_WCPO_VERSION' ) ) {
	exit( 'Direct access forbidden.' );
}

if ( ! class_exists( 'YITH_Pre_Order_Release_Date_Changed_Email' ) ) {
	/**
	 * Class YITH_Pre_Order_Release_Date_Changed_Email
	 */
	class YITH_Pre_Order_Release_Date_Changed_Email extends YITH_Pre_Order_Email {

		/**
		 * Constructor.
		 */
		public function __construct() {
			$this->id             = 'ywpo_release_date_changed_email';
			$this->customer_email = true;
			$this->title          = __( 'YITH Pre-Order: Availability date changed', 'yith-pre-order-for-woocommerce' );
			$this->description    = sprintf(
				// translators: %s: placeholders.
				__( 'If the administrator changes the availability date, the user will be notified. Available placeholders: %s', 'yith-pre-order-for-woocommerce' ),
				'<code>{customer_name}, {product_title}, {product_link}, {old_release_date}, {old_release_datetime}, {new_release_date}, {new_release_datetime}, {offset}, {site_title}.</code>'
			);

			$this->heading = __( 'There is a new availability date for the product you pre-ordered', 'yith-pre-order-for-woocommerce' );
			$this->subject = __( 'There is a new availability date for the product you pre-ordered', 'yith-pre-order-for-woocommerce' );

			$this->email_body = __(
				"Hi {customer_name},\n\nWe would like to inform you that the availability date for the product you pre-ordered in our shop has changed:
{product_table}\nWe are sorry for this but, please, be patient: great things take time!\n\nRegards,\n{site_title}",
				'yith-pre-order-for-woocommerce'
			);

			$this->template_html = 'emails/ywpo-email-user-release-date-changed.php';

			add_action( 'ywpo_release_date_changed_email', array( $this, 'trigger' ), 10, 4 );

			parent::__construct();
			$this->email_type = 'html';
			$this->enabled    = get_option( 'ywpo_release_date_change_email_enabled', 'no' );
		}

		/**
		 * Triggers the email sending process.
		 *
		 * @param string     $email The customer email address.
		 * @param string|int $product_id The WC_Product ID.
		 * @param int        $old_release_date The previous release date in timestamp format.
		 * @param int        $new_release_date The new release date in timestamp format.
		 */
		public function trigger( $email, $product_id, $old_release_date, $new_release_date ) {
			if ( ! $this->is_enabled() ) {
				return;
			}

			$this->recipient = $email;

			$product = wc_get_product( $product_id );

			$this->data = array(
				'product'          => $product,
				'old_release_date' => $old_release_date,
				'new_release_date' => $new_release_date,
			);

			$product_link = apply_filters( 'ywpo_release_date_changed_email_product_link', '<a href="' . $product->get_permalink() . '">' . $product->get_title() . '</a>', $product );

			$user     = get_user_by( 'email', $email );
			$username = '';
			if ( $user ) {
				if ( get_user_meta( $user->ID, 'billing_first_name', true ) ) {
					$username = get_user_meta( $user->ID, 'billing_first_name', true );
				} elseif ( $user->first_name ) {
					$username = $user->first_name;
				} elseif ( $user->display_name ) {
					$username = $user->display_name;
				}
			}
			$username = apply_filters( 'ywpo_release_date_changed_username', $username, $user, $email, $product_id, $old_release_date, $new_release_date );

			$this->placeholders['{customer_name}']        = $username;
			$this->placeholders['{product_title}']        = $product->get_title();
			$this->placeholders['{product_link}']         = $product_link;
			$this->placeholders['{old_release_date}']     = $old_release_date ? ywpo_print_date( $old_release_date ) : '';
			$this->placeholders['{old_release_datetime}'] = $old_release_date ? ywpo_print_datetime( $old_release_date ) : '';
			$this->placeholders['{new_release_date}']     = $new_release_date ? ywpo_print_date( $new_release_date ) : '';
			$this->placeholders['{new_release_datetime}'] = $new_release_date ? ywpo_print_datetime( $new_release_date ) : '';
			$this->placeholders['{offset}']               = ywpo_get_timezone_offset_label();

			$this->email_body = $this->format_string( $this->get_option( 'email_body', $this->email_body ) );

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

		/**
		 * Get content html.
		 *
		 * @return string
		 * @throws WC_Data_Exception Exception.
		 */
		public function get_content_html() {
			if ( has_filter( 'woocommerce_is_email_preview' ) ) {
				$this->data = $this->get_dummy_data( true );
			}
			return wc_get_template_html(
				$this->template_html,
				array(
					'email_heading' => $this->get_heading(),
					'sent_to_admin' => false,
					'plain_text'    => false,
					'email'         => $this,
				),
				'',
				YITH_WCPO_TEMPLATE_PATH
			);
		}

		/**
		 * Init settings for the email.
		 */
		public function init_settings() {
			$this->settings            = get_option( $this->get_option_key(), null );
			$this->settings['enabled'] = get_option( 'ywpo_release_date_change_email_enabled', 'yes' );

			// If there are no settings defined, use defaults.
			if ( ! is_array( $this->settings ) ) {
				$form_fields    = $this->get_form_fields();
				$this->settings = array_merge( array_fill_keys( array_keys( $form_fields ), '' ), wp_list_pluck( $form_fields, 'default' ) );
			}
		}

		/**
		 * Processes and saves options.
		 * If there is an error thrown, will continue to save and validate fields, but will leave the erring field out.
		 *
		 * @return bool was anything saved?
		 */
		public function process_admin_options() {
			$this->init_settings();

			$post_data = $this->get_post_data();

			foreach ( $this->get_form_fields() as $key => $field ) {
				if ( 'title' !== $this->get_field_type( $field ) ) {
					try {
						if ( 'enabled' === $key ) {
							update_option( 'ywpo_release_date_change_email_enabled', $this->get_field_value( $key, $field, $post_data ) );
						}
						$this->settings[ $key ] = $this->get_field_value( $key, $field, $post_data );
					} catch ( Exception $e ) {
						$this->add_error( $e->getMessage() );
					}
				}
			}

			return update_option( $this->get_option_key(), apply_filters( 'woocommerce_settings_api_sanitized_fields_' . $this->id, $this->settings ), 'yes' );
		}

		/**
		 * Initialise Settings Form Fields - these are generic email options most will use.
		 */
		public function init_form_fields() {
			$this->form_fields = array(
				'enabled'    => array(
					'title'   => __( 'Enable/Disable', 'yith-pre-order-for-woocommerce' ),
					'type'    => 'checkbox',
					'label'   => __( 'Enable this email notification', 'yith-pre-order-for-woocommerce' ),
					'default' => 'yes',
				),
				'subject'    => array(
					'title'       => __( 'Subject', 'yith-pre-order-for-woocommerce' ),
					'type'        => 'text',
					// translators: %s: email subject.
					'description' => sprintf( __( 'This controls the email subject line. Leave blank to use the default subject: <code>%s</code>.', 'yith-pre-order-for-woocommerce' ), $this->subject ),
					'placeholder' => '',
					'default'     => $this->subject,
				),
				'heading'    => array(
					'title'       => __( 'Email heading', 'yith-pre-order-for-woocommerce' ),
					'type'        => 'text',
					// translators: %s: email heading.
					'description' => sprintf( __( 'This controls the main heading included in the email notification. Leave blank to use the default heading: <code>%s</code>.', 'yith-pre-order-for-woocommerce' ), $this->heading ),
					'placeholder' => '',
					'default'     => $this->heading,
				),
				'email_body' => array(
					'title'       => __( 'Email body', 'yith-pre-order-for-woocommerce' ),
					'type'        => 'textarea',
					// translators: %s: email body.
					'description' => sprintf( __( 'Defaults to <code>%s</code>', 'yith-pre-order-for-woocommerce' ), $this->email_body ),
					'placeholder' => '',
					'default'     => $this->email_body,
				),
			);
		}
	}
}

return new YITH_Pre_Order_Release_Date_Changed_Email();
