<?php
/**
 * Mail
 *
 * @package Nisje
 */

namespace Dekode\Nisje\Resets;

/**
 * Setup mail details
 */
function mail_setup() {
	add_filter( 'wp_mail_from', __NAMESPACE__ . '\\mail_from' );
	add_filter( 'wp_mail_from_name', __NAMESPACE__ . '\\mail_from_name' );
	add_action( 'phpmailer_init', __NAMESPACE__ . '\\mail_return_path' );
	add_filter( 'bp_email_get_tokens', __NAMESPACE__ . '\\set_unsubscribe_token', 10, 4 );
}
add_action( 'init', __NAMESPACE__ . '\mail_setup' );

/**
 * Setup mail from
 *
 * @param string $from Mail from.
 * @return string Optimized Mail from.
 */
function mail_from( $from ) {
	$from = nisje_get_setting( 'mail_from', 'general' );
	if ( ! empty( $from ) ) {
		return $from;
	} else {
		return 'noreply@nisje.io';
	}
}

/**
 * Setup mail from name
 *
 * @param string $from_name Mail from name.
 * @return string Optimized Mail from name.
 */
function mail_from_name( $from_name ) {
	$from_name = nisje_get_setting( 'mail_from_name', 'general' );
	if ( ! empty( $from_name ) ) {
		return $from_name;
	} else {
		return 'Nisje';
	}
}

/**
 * Setup mail return path
 *
 * @param object $phpmailer PHPMailer object.
 */
function mail_return_path( $phpmailer ) {
	$phpmailer->Sender = $phpmailer->From; // phpcs:ignore
}

/**
 * Add default email tokens.
 *
 * @param array    $tokens        Email tokens.
 * @param string   $property_name Unused.
 * @param string   $transform     Unused.
 * @param BP_Email $email         Email being sent.
 * @return array
 */
function set_unsubscribe_token( $tokens, $property_name, $transform, $email ) {
	$tokens['unsubscribe'] = esc_url( home_url( 'account/notifications' ) );

	return $tokens;
}
