<?php
/**
 * Email notifications.
 *
 * @package TonItaliaRegistration
 */

defined( 'ABSPATH' ) || exit;

/**
 * Class TON_Reg_Mailer
 */
class TON_Reg_Mailer {

	/**
	 * @param object $registration Registration row.
	 * @param int    $user_id      User ID.
	 */
	public static function send_admin_notification( $registration, $user_id ) {
		$to      = get_option( 'ton_reg_admin_email', get_option( 'admin_email' ) );
		$subject = get_option( 'ton_reg_email_admin_subject', '' );
		$body    = get_option( 'ton_reg_email_admin_body', '' );

		$replacements = self::replacements( $registration, $user_id );
		$subject      = strtr( $subject, $replacements );
		$body         = strtr( $body, $replacements );

		wp_mail( $to, $subject, $body );
	}

	/**
	 * @param object $registration Registration row.
	 * @param int    $user_id      User ID.
	 */
	public static function send_user_confirmation( $registration, $user_id ) {
		$to      = $registration->email;
		$subject = get_option( 'ton_reg_email_user_subject', '' );
		$body    = get_option( 'ton_reg_email_user_body', '' );

		$replacements = self::replacements( $registration, $user_id );
		$subject      = strtr( $subject, $replacements );
		$body         = strtr( $body, $replacements );

		wp_mail( $to, $subject, $body );

		// Standard WP new user notification with password reset link.
		if ( function_exists( 'wp_send_new_user_notifications' ) ) {
			wp_send_new_user_notifications( $user_id, 'user' );
		}
	}

	/**
	 * @param object $registration  Registration row.
	 * @param int    $year          Target calendar year.
	 * @param string $reminder_type first|last.
	 */
	public static function send_renewal_reminder_to_member( $registration, $year, $reminder_type ) {
		$to = $registration->email ?? '';
		if ( ! is_email( $to ) ) {
			return;
		}

		$subject_key = 'first' === $reminder_type ? 'ton_reg_email_renewal_first_subject' : 'ton_reg_email_renewal_second_subject';
		$body_key    = 'first' === $reminder_type ? 'ton_reg_email_renewal_first_body' : 'ton_reg_email_renewal_second_body';
		$defaults    = TON_Reg_Defaults::options();

		$subject = get_option( $subject_key, $defaults[ $subject_key ] ?? '' );
		$body    = get_option( $body_key, $defaults[ $body_key ] ?? '' );

		$replacements = self::renewal_replacements( $registration, (int) $year );
		$subject      = strtr( $subject, $replacements );
		$body         = strtr( $body, $replacements );

		wp_mail( $to, $subject, $body );
	}

	/**
	 * @param array<int,object> $members       Registration rows.
	 * @param int               $year          Target calendar year.
	 * @param string            $reminder_type first|last.
	 */
	public static function send_renewal_admin_digest( $members, $year, $reminder_type ) {
		if ( empty( $members ) ) {
			return;
		}

		$to = get_option( 'ton_reg_admin_email', get_option( 'admin_email' ) );
		if ( ! is_email( $to ) ) {
			return;
		}

		$defaults = TON_Reg_Defaults::options();
		$subject  = get_option( 'ton_reg_email_renewal_admin_subject', $defaults['ton_reg_email_renewal_admin_subject'] ?? '' );
		$body     = get_option( 'ton_reg_email_renewal_admin_body', $defaults['ton_reg_email_renewal_admin_body'] ?? '' );

		$lines = array();
		foreach ( $members as $member ) {
			$lines[] = sprintf(
				'- %s %s <%s> (ID %d)',
				$member->nome ?? '',
				$member->cognome ?? '',
				$member->email ?? '',
				(int) $member->id
			);
		}

		$replacements = array(
			'{anno}'        => (string) (int) $year,
			'{lista_soci}'  => implode( "\n", $lines ),
			'{numero_soci}' => (string) count( $members ),
			'{quota}'       => (string) get_option( 'ton_reg_membership_fee', '10,00' ),
			'{admin_url}'   => admin_url( 'admin.php?page=ton-registrations&status=admitted&renewal_unpaid=1' ),
		);

		$subject = strtr( $subject, $replacements );
		$body    = strtr( $body, $replacements );

		wp_mail( $to, $subject, $body );
	}

	/**
	 * @param object $registration Registration.
	 * @param int    $user_id      User ID.
	 * @return array<string,string>
	 */
	private static function replacements( $registration, $user_id ) {
		$admin_url = admin_url( 'admin.php?page=ton-registrations&action=view&id=' . (int) $registration->id );

		return array(
			'{nome}'           => $registration->nome,
			'{cognome}'        => $registration->cognome,
			'{email}'          => $registration->email,
			'{codice_fiscale}' => $registration->codice_fiscale,
			'{ip}'             => $registration->registration_ip,
			'{login_url}'      => wp_lostpassword_url(),
			'{profile_url}'    => TON_Reg_Profile::profile_url(),
			'{gdpr_contact}'   => get_option( 'ton_reg_gdpr_contact', '' ),
			'{admin_url}'      => $admin_url,
		);
	}

	/**
	 * @param object $registration Registration.
	 * @param int    $year         Calendar year for payment.
	 * @return array<string,string>
	 */
	private static function renewal_replacements( $registration, $year ) {
		$admin_url = admin_url( 'admin.php?page=ton-registrations&action=view&id=' . (int) $registration->id );
		$payment   = get_option( 'ton_reg_payment_instructions', '' );

		$payment_replacements = array(
			'{quota}'        => (string) get_option( 'ton_reg_membership_fee', '10,00' ),
			'{anno}'         => (string) $year,
			'{beneficiario}' => (string) get_option( 'ton_reg_beneficiary', '' ),
			'{iban}'         => (string) get_option( 'ton_reg_iban', '' ),
			'{nome}'         => (string) ( $registration->nome ?? '' ),
			'{cognome}'      => (string) ( $registration->cognome ?? '' ),
		);
		$payment_instructions = strtr( $payment, $payment_replacements );

		return array_merge(
			$payment_replacements,
			array(
				'{email}'                  => (string) ( $registration->email ?? '' ),
				'{codice_fiscale}'         => (string) ( $registration->codice_fiscale ?? '' ),
				'{ip}'                     => (string) ( $registration->registration_ip ?? '' ),
				'{login_url}'              => wp_lostpassword_url(),
				'{profile_url}'            => TON_Reg_Profile::profile_url(),
				'{gdpr_contact}'           => (string) get_option( 'ton_reg_gdpr_contact', '' ),
				'{admin_url}'              => $admin_url,
				'{payment_instructions}'   => $payment_instructions,
			)
		);
	}
}
