<?php
/**
 * Privacy-safe order formatting.
 *
 * @package VoidPulse
 */

namespace VoidPulse\Privacy;

defined( 'ABSPATH' ) || exit;

final class SafeOrderFormatter {
	/**
	 * Format customer identity.
	 *
	 * @param \WC_Order $order Order.
	 * @param string    $format Format.
	 * @return string
	 */
	public function customer( $order, $format ) {
		$first = sanitize_text_field( $order->get_billing_first_name() );
		$last  = sanitize_text_field( $order->get_billing_last_name() );

		switch ( $format ) {
			case 'first_initial':
				$initial = function_exists( 'mb_substr' ) ? mb_substr( $last, 0, 1 ) : substr( $last, 0, 1 );
				$value   = $first ? $first . ( $last ? ' ' . strtoupper( $initial ) . '.' : '' ) : __( 'Someone', 'voidpulse-social-proof-for-woocommerce' );
				break;
			case 'anonymous':
				$value = __( 'Anonymous customer', 'voidpulse-social-proof-for-woocommerce' );
				break;
			case 'customer':
				$value = __( 'Customer', 'voidpulse-social-proof-for-woocommerce' );
				break;
			case 'someone':
				$value = __( 'Someone', 'voidpulse-social-proof-for-woocommerce' );
				break;
			case 'first_name':
			default:
				$value = $first ?: __( 'Someone', 'voidpulse-social-proof-for-woocommerce' );
				break;
		}

		return sanitize_text_field( (string) apply_filters( 'voidpulse_customer_display_name', $value, $order, $format ) );
	}

	/**
	 * Format general location without street data.
	 *
	 * @param \WC_Order $order Order.
	 * @param string    $format Format.
	 * @return string
	 */
	public function location( $order, $format ) {
		if ( 'hidden' === $format ) {
			return '';
		}
		$city    = sanitize_text_field( $order->get_billing_city() );
		$region  = sanitize_text_field( $order->get_billing_state() );
		$country = sanitize_text_field( $order->get_billing_country() );

		if ( $country && function_exists( 'WC' ) && WC()->countries ) {
			$countries = WC()->countries->get_countries();
			$country   = isset( $countries[ $country ] ) ? $countries[ $country ] : $country;
		}
		if ( $region && function_exists( 'WC' ) && WC()->countries ) {
			$states = WC()->countries->get_states( $order->get_billing_country() );
			$region = isset( $states[ $region ] ) ? $states[ $region ] : $region;
		}

		switch ( $format ) {
			case 'region':
				$value = $region;
				break;
			case 'country':
				$value = $country;
				break;
			case 'city_country':
				$value = implode( ', ', array_filter( array( $city, $country ) ) );
				break;
			case 'city':
			default:
				$value = $city;
				break;
		}
		return sanitize_text_field( (string) apply_filters( 'voidpulse_location_display', $value, $order, $format ) );
	}
}
