<?php
/**
 * Notification Email Helper Functions
 *
 * Provides utility functions for parsing and sanitizing
 * comma-separated notification email addresses.
 *
 * @package    Karate_Club_Manager
 * @subpackage Karate_Club_Manager/includes
 * @since      1.0.320
 */

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

/**
 * Parse a comma-separated email string into an array of valid emails for wp_mail().
 *
 * Splits on commas, trims whitespace, validates each address with is_email(),
 * removes duplicates, and falls back to admin_email if no valid addresses remain.
 *
 * @since 1.0.320
 * @param string $email_string Comma-separated email addresses.
 * @param string $fallback     Fallback email if all are invalid. Defaults to admin_email option.
 * @return array Array of valid email addresses (never empty).
 */
function macm_parse_notification_emails( $email_string, $fallback = '' ) {
	if ( empty( $fallback ) ) {
		$fallback = get_option( 'admin_email' );
	}

	if ( empty( $email_string ) ) {
		return array( $fallback );
	}

	$parts  = explode( ',', $email_string );
	$emails = array();

	foreach ( $parts as $part ) {
		$trimmed = trim( $part );
		if ( is_email( $trimmed ) ) {
			$emails[] = $trimmed;
		}
	}

	// Deduplicate.
	$emails = array_unique( $emails );

	if ( empty( $emails ) ) {
		return array( $fallback );
	}

	return array_values( $emails );
}

/**
 * Sanitize a comma-separated email string for database storage.
 *
 * Splits on commas, trims whitespace, validates each address,
 * removes duplicates, and returns a clean comma-separated string.
 * Returns empty string if no valid emails found.
 *
 * @since 1.0.320
 * @param string $email_string Comma-separated email addresses.
 * @return string Sanitized comma-separated email string, or empty string.
 */
function macm_sanitize_notification_emails( $email_string ) {
	if ( empty( $email_string ) ) {
		return '';
	}

	$parts  = explode( ',', $email_string );
	$emails = array();

	foreach ( $parts as $part ) {
		$trimmed = sanitize_email( trim( $part ) );
		if ( is_email( $trimmed ) ) {
			$emails[] = $trimmed;
		}
	}

	// Deduplicate.
	$emails = array_unique( $emails );

	return implode( ', ', $emails );
}
