<?php
/**
 * WhatsApp click-to-message helper.
 *
 * Free tier — no analytics or logging (per ADR-29). Provides a tiny
 * static renderer that produces an <a href="https://wa.me/..."> link
 * with a sanitised number and a default message template.
 *
 * Templates and Elementor widgets call WhatsAppHandler::renderButton()
 * so the markup stays consistent and the number normalisation lives in
 * one place.
 *
 * @package ThemeREX\AutoDealer
 * @version 1.0.0
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Frontend;

use function ThemeREX\AutoDealer\getDealerMeta;

/**
 * Stateless WhatsApp button renderer.
 */
final class WhatsAppHandler {

	/**
	 * Render a WhatsApp button for a vehicle (uses the dealer's WhatsApp number).
	 *
	 * @param int    $post_id        Vehicle post ID.
	 * @param string $message_prefix Optional prefix added to the default message.
	 * @return string HTML or '' when no number is configured.
	 */
	public static function renderButton( int $post_id, string $message_prefix = '' ): string {
		$dealer_id = (int) get_post_meta( $post_id, '_trx_ad_dealer_id', true );
		if ( $dealer_id <= 0 ) {
			return '';
		}

		$dealer = getDealerMeta( $dealer_id );
		$number = self::normaliseNumber( (string) ( $dealer['whatsapp'] ?? '' ) );
		if ( '' === $number ) {
			return '';
		}

		$title   = (string) get_the_title( $post_id );
		$message = trim(
			$message_prefix . ' ' . sprintf(
			/* translators: 1: vehicle title 2: vehicle URL */
				__( "Hi, I'm interested in %1\$s — %2\$s", 'trx-auto-dealer' ),
				$title,
				(string) get_permalink( $post_id )
			)
		);

		$href = sprintf(
			'https://wa.me/%s?text=%s',
			rawurlencode( $number ),
			rawurlencode( $message )
		);

		return sprintf(
			'<a href="%1$s" class="trx-ad-btn trx-ad-btn--whatsapp" target="_blank" rel="noopener noreferrer" data-trx-ad-vehicle-id="%2$d">%3$s</a>',
			esc_url( $href ),
			(int) $post_id,
			esc_html__( 'WhatsApp', 'trx-auto-dealer' )
		);
	}

	/**
	 * Strip everything but digits. WhatsApp expects E.164-style digit-only
	 * input ("+44 7700 900123" → "447700900123").
	 *
	 * @param string $raw Raw phone number.
	 * @return string Digits only.
	 */
	public static function normaliseNumber( string $raw ): string {
		$digits = preg_replace( '/[^0-9]/', '', $raw );
		return is_string( $digits ) ? $digits : '';
	}
}
