<?php
/**
 * Shared account contact email resolution.
 *
 * @package SiteStaffr
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Resolves the authoritative customer contact email for onboarding and billing.
 */
class SiteStaffr_Account_Contact {

	/**
	 * Resolve the current notification email, falling back to the WordPress admin email.
	 *
	 * @param array|null $settings Optional settings array.
	 * @return string
	 */
	public static function get_notification_email( $settings = null ) {
		if ( null === $settings ) {
			$settings = get_option( 'sitestaffr_settings', array() );
		}

		$saved_email = isset( $settings['notification_email'] ) ? sanitize_email( $settings['notification_email'] ) : '';
		if ( ! empty( $saved_email ) && is_email( $saved_email ) ) {
			return $saved_email;
		}

		return sanitize_email( get_option( 'admin_email', '' ) );
	}

	/**
	 * Resolve the notification email to persist during saves.
	 *
	 * @param string     $posted_email Raw email from the request payload.
	 * @param array|null $settings     Optional existing settings array.
	 * @return string
	 */
	public static function resolve_notification_email_for_save( $posted_email, $settings = null ) {
		$posted_email = sanitize_email( $posted_email );
		if ( ! empty( $posted_email ) && is_email( $posted_email ) ) {
			return $posted_email;
		}

		return self::get_notification_email( $settings );
	}
}
