<?php
/**
 * Extra schema formats registered by the plugin itself.
 *
 * @package MenuVerse
 */

namespace WPXero\MenuVerse\Settings;

defined( 'ABSPATH' ) || exit;

/**
 * Registers schema formats through the same public filter an add on would use.
 *
 * `Schema_Sanitizer` dispatches on `format` and then fires
 * `menuverse_sanitize_format_{$format}`, so a format needs no change to the
 * sanitizer itself — this class is simply the first consumer of that seam.
 */
class Formats {

	/**
	 * Hooks the formats.
	 *
	 * @return void
	 */
	public function boot() {
		add_filter( 'menuverse_sanitize_format_phone', array( $this, 'sanitize_phone' ), 10, 1 );
	}

	/**
	 * Reduces a telephone number to digits with at most one leading plus.
	 *
	 * The stored value is a bare number rather than a `tel:` URL, because the
	 * same field feeds both a `tel:` link and a wa.me address — and wa.me
	 * rejects the plus. Building the destination is the render path's job.
	 *
	 * @param string $value Sanitized value so far.
	 * @return string
	 */
	public function sanitize_phone( $value ) {
		$value = preg_replace( '/[^0-9+]/', '', (string) $value );

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

		$leading = '+' === $value[0] ? '+' : '';

		return $leading . str_replace( '+', '', $value );
	}
}
