<?php
/**
 * Click-to-call button helper.
 *
 * Free tier — emits a tel: link, no logging (per ADR-29). Reuses the
 * dealer's primary phone number; falls back to the listing's dealer
 * meta lookup so templates only need a $post_id.
 *
 * @package ThemeREX\AutoDealer
 * @version 1.0.0
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Frontend;

use function ThemeREX\AutoDealer\getDealerMeta;

/**
 * Stateless click-to-call button renderer.
 */
final class CallHandler {

	/**
	 * Render the call button. Returns '' when the dealer has no phone.
	 *
	 * @param int $post_id Vehicle post ID.
	 * @return string
	 */
	public static function renderButton( int $post_id ): string {
		$dealer_id = (int) get_post_meta( $post_id, '_trx_ad_dealer_id', true );
		if ( $dealer_id <= 0 ) {
			return '';
		}

		$dealer = getDealerMeta( $dealer_id );
		$phone  = self::normaliseTel( (string) ( $dealer['phone'] ?? '' ) );
		if ( '' === $phone ) {
			return '';
		}

		return sprintf(
			'<a href="tel:%1$s" class="trx-ad-btn trx-ad-btn--call" data-trx-ad-vehicle-id="%2$d">%3$s %4$s</a>',
			esc_attr( $phone ),
			(int) $post_id,
			esc_html__( 'Call', 'trx-auto-dealer' ),
			esc_html( self::formatDisplay( (string) ( $dealer['phone'] ?? '' ) ) )
		);
	}

	/**
	 * tel: links accept "+", digits, and a few separators. Strip the rest.
	 *
	 * @param string $raw Raw phone number.
	 * @return string Cleaned for href.
	 */
	public static function normaliseTel( string $raw ): string {
		$cleaned = preg_replace( '/[^0-9+\-\s]/', '', $raw );
		$cleaned = is_string( $cleaned ) ? trim( $cleaned ) : '';
		// Collapse internal whitespace runs.
		$cleaned = (string) preg_replace( '/\s+/', '', $cleaned );
		return $cleaned;
	}

	/**
	 * Visible label keeps spaces/dashes for readability.
	 */
	private static function formatDisplay( string $raw ): string {
		$cleaned = preg_replace( '/[^0-9+\-\s\(\)]/', '', $raw );
		return is_string( $cleaned ) ? trim( $cleaned ) : '';
	}
}
