<?php
/**
 * Helper functions.
 *
 * @package TradeSchoolManager
 */

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

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound, WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- "tsm_" is this plugin's registered prefix (see phpcs.xml.dist).

/**
 * Backwards-compat shim. The All-In-One build has every feature unlocked,
 * so this always returns true. Kept for any third-party code that hooked
 * the legacy filter.
 */
function tradeschool_manager_is_pro_active() {
	return (bool) apply_filters( 'tradeschool_manager_is_pro_active', true );
}

/**
 * Deprecated. Returns an empty string so existing call sites are harmless.
 * Kept to avoid fatal errors if external code calls it.
 */
function tsm_pro_badge( $echo = true ) {
	return '';
}

/**
 * Deprecated. The "Upgrade to Pro" notice is no longer shown  -  every
 * feature ships in the All-In-One build. Left as a no-op for compat.
 */
function tsm_upgrade_notice( $feature_label = '' ) {
	// no-op
}

/**
 * Get a plugin setting value.
 */
function tsm_get_setting( $key, $default = '' ) {
	$settings = get_option( 'tsm_settings', array() );
	return isset( $settings[ $key ] ) ? $settings[ $key ] : $default;
}

/**
 * Format a phone number for display.
 *
 * Strips non-digits, recognizes the common North-American (10 or 11-digit
 * leading 1) shapes and formats them as (XXX) XXX-XXXX [ x EXT ]. Numbers
 * that don't match a known pattern  -  including international numbers  -  are
 * returned with light spacing preserved so we never mangle a user's value.
 *
 * @param string $raw  Raw stored phone string.
 * @return string      Display-formatted phone (empty string if blank).
 */
function tsm_format_phone( $raw ) {
	$raw = trim( (string) $raw );
	if ( '' === $raw ) {
		return '';
	}

	// Capture an extension (x, ext, extension) if present.
	$ext = '';
	if ( preg_match( '/(?:\s*(?:x|ext\.?|extension)\s*)(\d{1,6})\s*$/i', $raw, $m ) ) {
		$ext = $m[1];
		$raw = preg_replace( '/(?:\s*(?:x|ext\.?|extension)\s*)\d{1,6}\s*$/i', '', $raw );
	}

	$digits = preg_replace( '/\D+/', '', $raw );

	// 11-digit US/Canada with leading 1.
	if ( 11 === strlen( $digits ) && '1' === $digits[0] ) {
		$digits = substr( $digits, 1 );
	}

	if ( 10 === strlen( $digits ) ) {
		$out = sprintf( '(%s) %s-%s', substr( $digits, 0, 3 ), substr( $digits, 3, 3 ), substr( $digits, 6 ) );
	} elseif ( 7 === strlen( $digits ) ) {
		$out = sprintf( '%s-%s', substr( $digits, 0, 3 ), substr( $digits, 3 ) );
	} else {
		// Unknown shape  -  return original trimmed value, untouched.
		$out = trim( $raw );
	}

	if ( '' !== $ext ) {
		$out .= ' x ' . $ext;
	}
	return $out;
}
