<?php
/**
 * Saying hello to somebody who has just signed up.
 *
 * @package TextTango
 */

declare( strict_types=1 );

namespace TextTango\WooCommerce;

use TextTango\Consent\Recipient;
use TextTango\Messages\MessageLog;
use TextTango\Sending\Sender;

defined( 'ABSPATH' ) || exit;

/**
 * The welcome message for a new account (spec §6).
 *
 * ### Why it often will not send, and why that is right
 *
 * A welcome needs a number, and most registrations do not have one. WordPress
 * registration asks for an email; WooCommerce checkout registration fills in a
 * billing phone, but only after the order is placed, which is a different hook
 * from this one. So this fires on `user_register` and quietly does nothing
 * whenever there is no number yet.
 *
 * The alternative — waiting, and sending a welcome hours later when a number
 * finally appears — is worse. A "welcome, your account is ready" that arrives
 * after somebody has already used the account reads as a mistake, and the
 * moment it was worth saying has gone.
 *
 * ### Why it is a service message
 *
 * Somebody who has just created an account on this store is being told their
 * account exists. That is about a thing they did, not an offer, so it sends
 * without marketing consent — the same reasoning that lets an order update
 * send. It is still subject to the opt-out list, because a hard stop outranks
 * everything.
 */
final class Accounts {

	/**
	 * Event id.
	 */
	public const EVENT = 'account_created';

	/**
	 * Register hooks.
	 */
	public function register(): void {
		add_action( 'user_register', array( self::class, 'on_register' ) );
	}

	/**
	 * Somebody signed up.
	 *
	 * @param int $user_id New user.
	 */
	public static function on_register( $user_id ): void {
		$user_id = (int) $user_id;

		if ( $user_id <= 0 || ! Events::is_enabled( self::EVENT ) ) {
			return;
		}

		$recipient = Recipient::for_user( $user_id );

		if ( '' === $recipient ) {
			return;
		}

		$body = Templates::render(
			Events::template( self::EVENT ),
			Templates::account_values( $user_id )
		);

		/** This filter is documented in src/WooCommerce/Notifications.php */
		$body = (string) apply_filters( 'texttango_message_template', $body, self::EVENT, null );

		if ( '' === trim( $body ) ) {
			return;
		}

		Sender::queue(
			array(
				'to'         => $recipient,
				'message'    => $body,
				'event'      => self::EVENT,
				// Keyed on the account rather than on the moment: an account is
				// created once, so a plugin that fires `user_register` twice —
				// importers do — cannot produce two welcomes.
				'dedupe_key' => MessageLog::build_dedupe_key( self::EVENT, (string) $user_id, 'created' ),
				'wp_user_id' => $user_id,
			)
		);
	}
}
