<?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_Payment_Reminder_Email' ) ) {
	/**
	 * Class YITH_Pre_Order_Payment_Reminder_Email
	 */
	class YITH_Pre_Order_Payment_Reminder_Email extends YITH_Pre_Order_Email {

		/**
		 * Constructor.
		 */
		public function __construct() {
			$this->id             = 'ywpo_payment_reminder_email';
			$this->customer_email = true;
			$this->title          = __( 'YITH Pre-Order: Payment reminder', 'yith-pre-order-for-woocommerce' );
			$this->description    = sprintf(
				// translators: %s: placeholders.
				__( 'Notifies the customer that the pre-order has been placed correctly. Available placeholders: %s', 'yith-pre-order-for-woocommerce' ),
				'<code>{customer_name}, {product_title}, {product_link}, {order_number}, {order_link}, {product_table}, {pending_payment}, {site_title}.</code>'
			);

			$this->heading    = __( 'Pay for your pre-order', 'yith-pre-order-for-woocommerce' );
			$this->subject    = __( 'Your pre-order placed on {site_title} is waiting to be paid for', 'yith-pre-order-for-woocommerce' );
			$this->email_body = __(
				"Hi {customer_name},\n\nYour pre-order has been completed and is now awaiting payment:\n{order_link}\n{product_table}\n{pending_payment}\nRegards,\n{site_title}",
				'yith-pre-order-for-woocommerce'
			);

			$this->template_html = 'emails/ywpo-email-user-payment-reminder.php';

			add_action( 'ywpo_payment_reminder_email', array( $this, 'trigger' ), 10, 3 );

			parent::__construct();
			$this->email_type = 'html';
		}

		/**
		 * Triggers the email sending process.
		 *
		 * @param WC_Order   $order The WC_Order object.
		 * @param WC_Product $product The WC_Product object.
		 * @param string|int $item_id The Order Item ID.
		 */
		public function trigger( $order, $product, $item_id ) {
			if ( ! $order || ! $product || 'cancelled' === $order->get_status() ) {
				return;
			}

			// Avoid errors with third-party plugins that use $this->object for the WC_Order instance.
			$this->object = $order;

			$this->data = apply_filters(
				'ywpo_payment_reminder_email_object',
				array(
					'order'   => $order,
					'product' => $product,
					'item_id' => $item_id,
				),
				$order,
				$product,
				$item_id
			);

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

			$order_link = apply_filters(
				'ywpo_payment_reminder_email_order_link',
				'<a href="' . $order->get_view_order_url() . '">' . _x( 'Order', 'WooCommerce shop order', 'yith-pre-order-for-woocommerce' ) . ' #' . $order->get_id() . '</a>',
				$order,
				$product,
				$item_id
			);

			$this->placeholders['{customer_name}'] = $order->get_formatted_billing_full_name();
			$this->placeholders['{product_title}'] = $product->get_title();
			$this->placeholders['{product_link}']  = $product_link;
			$this->placeholders['{order_number}']  = $order->get_order_number();
			$this->placeholders['{order_link}']    = $order_link;

			$this->recipient = $order->get_billing_email();

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

			if ( $this->is_enabled() && $this->get_recipient() ) {
				$return = $this->send(
					$this->get_recipient(),
					$this->get_subject(),
					$this->get_content(),
					$this->get_headers(),
					$this->get_attachments()
				);
				if ( $return ) {
					$order->update_meta_data( '_ywpo_pay_reminder_email_sent', 'yes' );
					$order->save();
				}
			}
		}

		/**
		 * 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();
			}
			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_payment_reminder_email_notification_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_payment_reminder_email_notification_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,
					'desc_tip'    => false,
				),
				'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,
					'desc_tip'    => false,
				),
				'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_Payment_Reminder_Email();
