<?php
/**
 * Recovery emails.
 *
 * @package FailedOrderRescueForWooCommerce
 */

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

class FORD_Email {
	/**
	 * Initialize hooks.
	 *
	 * @return void
	 */
	public static function init() {
		add_action( 'admin_post_ford_send_recovery_email', array( __CLASS__, 'handle_manual_send' ) );
	}

	/**
	 * Optional from name.
	 *
	 * @param string $from_name Existing from name.
	 * @return string
	 */
	public static function filter_from_name( $from_name ) {
		$custom = FORD_Settings::get( 'from_name' );

		return ! empty( $custom ) ? $custom : $from_name;
	}

	/**
	 * Optional from email.
	 *
	 * @param string $from_email Existing from email.
	 * @return string
	 */
	public static function filter_from_email( $from_email ) {
		$custom = FORD_Settings::get( 'from_email' );

		return is_email( $custom ) ? $custom : $from_email;
	}

	/**
	 * Handle manual email action.
	 *
	 * @return void
	 */
	public static function handle_manual_send() {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_die( esc_html__( 'You do not have permission to send recovery emails.', 'failed-order-rescue-for-woocommerce' ) );
		}

		$order_id = isset( $_GET['order_id'] ) ? absint( $_GET['order_id'] ) : 0;
		check_admin_referer( 'ford_send_recovery_email_' . $order_id );

		$sent = self::send_recovery_email( $order_id );

		wp_safe_redirect(
			add_query_arg(
				array(
					'page'       => 'ford-recovery',
					'ford_notice'=> $sent ? 'email_sent' : 'email_failed',
				),
				admin_url( 'admin.php' )
			)
		);
		exit;
	}

	/**
	 * Send recovery email for an order.
	 *
	 * @param int $order_id Order ID.
	 * @return bool
	 */
	public static function send_recovery_email( $order_id, $source = 'manual', $sequence_step = 0 ) {
		$order = wc_get_order( $order_id );

		if ( ! $order instanceof WC_Order ) {
			return false;
		}

		$email = $order->get_billing_email();

		if ( ! is_email( $email ) ) {
			return false;
		}

		$subject = self::replace_tokens( FORD_Settings::get( 'email_subject' ), $order );
		$heading = self::replace_tokens( FORD_Settings::get( 'email_heading' ), $order );
		$body    = wpautop( self::replace_tokens( FORD_Settings::get( 'email_body' ), $order ) );
		$pay_url = $order->get_checkout_payment_url();
		$coupon  = $order->get_meta( '_ford_pro_coupon_code', true );

		$message  = '<h2>' . esc_html( $heading ) . '</h2>';
		$message .= wp_kses_post( $body );
		if ( $coupon ) {
			$message .= '<p><strong>' . esc_html__( 'A recovery discount has been applied to your order.', 'failed-order-rescue-for-woocommerce' ) . '</strong></p>';
		}
		$message .= '<p><a style="display:inline-block;padding:12px 18px;background:#2271b1;color:#ffffff;text-decoration:none;border-radius:4px;" href="' . esc_url( $pay_url ) . '">' . esc_html__( 'Complete payment', 'failed-order-rescue-for-woocommerce' ) . '</a></p>';
		$message .= '<p>' . esc_html__( 'If the button does not work, copy and paste this link into your browser:', 'failed-order-rescue-for-woocommerce' ) . '<br><a href="' . esc_url( $pay_url ) . '">' . esc_html( $pay_url ) . '</a></p>';

		$headers = array( 'Content-Type: text/html; charset=UTF-8' );

		add_filter( 'wp_mail_from_name', array( __CLASS__, 'filter_from_name' ) );
		add_filter( 'wp_mail_from', array( __CLASS__, 'filter_from_email' ) );
		$sent = wp_mail( $email, $subject, $message, $headers );
		remove_filter( 'wp_mail_from_name', array( __CLASS__, 'filter_from_name' ) );
		remove_filter( 'wp_mail_from', array( __CLASS__, 'filter_from_email' ) );

		if ( $sent ) {
			$order->update_meta_data( '_ford_recovery_email_sent', 'yes' );
			$order->update_meta_data( '_ford_recovery_email_sent_at', current_time( 'mysql' ) );
			$order->update_meta_data( '_ford_recovery_email_source', sanitize_key( $source ) );
			if ( $sequence_step ) {
				$order->update_meta_data( '_ford_recovery_email_sequence_step', absint( $sequence_step ) );
			}
			$order->add_order_note( 'automation' === $source ? sprintf( __( 'Failed Order Rescue Pro sequence email %d sent.', 'failed-order-rescue-for-woocommerce' ), absint( $sequence_step ) ) : __( 'Failed Order Rescue recovery email sent manually.', 'failed-order-rescue-for-woocommerce' ) );
			$order->save();
		}

		return $sent;
	}

	/**
	 * Replace email template tokens.
	 *
	 * @param string   $template Template content.
	 * @param WC_Order $order Order object.
	 * @return string
	 */
	public static function replace_tokens( $template, $order ) {
		$customer_name = trim( $order->get_billing_first_name() . ' ' . $order->get_billing_last_name() );

		if ( '' === $customer_name ) {
			$customer_name = __( 'there', 'failed-order-rescue-for-woocommerce' );
		}

		$tokens = array(
			'{site_name}'     => wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ),
			'{customer_name}' => $customer_name,
			'{first_name}'    => $order->get_billing_first_name(),
			'{order_number}'  => $order->get_order_number(),
			'{order_total}'   => wp_strip_all_tags( $order->get_formatted_order_total() ),
			'{payment_url}'   => $order->get_checkout_payment_url(),
		);

		return strtr( $template, $tokens );
	}
}
