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

namespace Popper\Actions;

use Popper\Action;

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

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

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

		$defaults = array(
			'user_email'           => '',
			'user_pass'            => wp_generate_password(),
			'show_admin_bar_front' => 'false',
		);

		$userdata = array();

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

		$userdata = wp_parse_args( $userdata, $defaults );

		if ( empty( $userdata['user_email'] ) || email_exists( $userdata['user_email'] ) ) {
			return;
		}

		if ( empty( $userdata['user_login'] ) ) {
			$userdata['user_login'] = $userdata['user_email'];
		}

		$user_id = wp_insert_user( $userdata );

		if ( ! is_wp_error( $user_id ) ) {
			wp_send_new_user_notifications( $user_id );
		} else {
			// you have an error...
			\Popper\Logging::add( 'Subscribe action', 'Error subscribing user. ' . $user_id->get_error_message(), $userdata, $popper_id, 'error' );
		}
	}
}
