<?php
/**
 * Perform Email Action.
 *
 * @package popper
 */

namespace Popper\Actions;

use Popper\Action;

/**
 * Class Email action
 *
 * @since 1.0.0
 */
class Email extends Action {

	/**
	 * The action label.
	 *
	 * @var string $type Type of action.
	 */
	protected $type = 'Email';

	/**
	 * {inheritDoc}
	 */
	public function process( $settings, $data, $popper_id ) {

		$defaults = array(
			'from'         => get_option( 'admin_email' ),
			'to'           => get_option( 'admin_email' ),
			'subject'      => __( 'New form submitted', 'popper' ),
			'message'      => '',
			'headers'      => array( 'Content-Type: text/html; charset=UTF-8' ),
		);

		$payload = array();

		if ( ! empty( $settings['merge_fields'] ) ) {
			foreach ( $settings['merge_fields'] as $key => $value ) {
				$payload[ $key ] = $data[ $value ] ?? $value;
			}
		}

		if ( ! empty( $payload['from'] ) ) {
			$name = $payload['name'] ?? $payload['from'];
			$defaults['headers'][] = 'From: ' . $name . ' <' . $payload['from'] . '>';
		}

		if ( empty( $payload['to'] ) ) {
			$payload['to'] = get_option( 'admin_email' );
		}

		if ( empty( $payload['subject'] ) ) {
			$payload['subject'] = $settings['merge_fields']['subject'] ?? $defaults['subject'];
		}

		$args = wp_parse_args( $payload, $defaults );

		$sent = wp_mail( $args['to'], $args['subject'], $args['message'], $args['headers'] );

		if ( ! $sent ) {
			\Popper\Logging::add( 'Email action', 'Email not sent.', $args, $popper_id, 'event' );
		}
	}
}
