<?php
/**
 * Formatting functions.
 *
 * @package HBFWC
 */

defined( 'ABSPATH' ) || exit;

/**
 * Price formatting without currency symbol.
 *
 * @param mixed $price The original price.
 *
 * @return float
 */
function hbfwc_raw_price( $price ) {
	return hbfwc_price_to_float($price);
}

/**
 * Get the date format.
 *
 * @return string
 */
function hbfwc_get_date_format() {
	$settings = get_option( 'woocommerce_hbfwc_settings', array() );
	return isset( $settings['date_format'] ) ? $settings['date_format'] : 'D, j M';
}

function hbfwc_kses_register_args( $allowed_tags ) {
	$svgs = hbfwc_get_svg_args();
	return array_merge( $allowed_tags, $svgs );
}

/**
 * Get svg tag args.
 *
 * @return array
 */
function hbfwc_get_svg_args() {
	$svg_args = array(
		'svg'    => array(
			'class'           => true,
			'aria-hidden'     => true,
			'aria-labelledby' => true,
			'role'            => true,
			'xmlns'           => true,
			'width'           => true,
			'height'          => true,
			'viewbox'         => true, // Must be lower case!.
			'fill'            => true,
		),
		'defs'   => array( 'type' => true ),
		'style'  => array( 'type' => true ),
		'g'      => array(
			'fill'  => true,
			'class' => true,
		),
		'title'  => array(
			'title' => true,
			'class' => true,
		),
		'circle' => array(
			'cx'    => true,
			'cy'    => true,
			'r'     => true,
			'class' => true,
		),
		'line'   => array(
			'x1'    => true,
			'y1'    => true,
			'x2'    => true,
			'y2'    => true,
			'class' => true,
		),
		'path'   => array(
			'd'               => true,
			'fill'            => true,
			'stroke'          => true,
			'stroke-width'    => true,
			'stroke-linecap'  => true,
			'stroke-linejoin' => true,
			'class'           => true,
		),
	);

	return $svg_args;
}

/**
 * Print the array in pretty way.
 *
 * @param array  $list_arrays The list array.
 * @param string $conjunction The conjunction.
 *
 * @return string
 */
function hbfwc_natural_language_join( array $list_arrays, $conjunction = 'and' ): string {
	if ( count( $list_arrays ) < 2 ) {
		return implode( ',', $list_arrays );
	}

	$oxford_separator = count( $list_arrays ) === 2 ? ' ' : ', ';
	$last             = array_pop( $list_arrays );

	if ( $list_arrays ) {
		return implode( ', ', $list_arrays ) . $oxford_separator . $conjunction . ' ' . $last;
	}

	return $last;
}

/**
 * Add svg tag to kses post.
 *
 * @param array  $tags Current allowed html tags.
 * @param string $context The context.
 *
 * @return array
 */
function hbfwc_add_allowed_svg( $tags, $context ) {
	if ( 'post' === $context ) {
		$svg_tags = hbfwc_get_svg_args();
		foreach ( $svg_tags as $ntag => $attrs ) {
			$tags[ $ntag ] = $attrs;
		}
	}

	return $tags;
}

/**
 * Normalize price input
 */
function hbfwc_parse_price_input( $raw_input ) {
	$clean = wc_clean( $raw_input );
	$clean = html_entity_decode( $clean );
	$clean = trim( str_replace( array( "\xc2\xa0", ' ' ), '', $clean ) );

	// Preserve canonical numeric input before locale-based normalization.
	if ( is_numeric( $clean ) ) {
		return wc_format_decimal( $clean, wc_get_price_decimals() );
	}

	$thousand_sep = wc_get_price_thousand_separator();
	$decimal_sep  = wc_get_price_decimal_separator();

	$normalized = str_replace( $thousand_sep, '', $clean );
	$normalized = str_replace( $decimal_sep, '.', $normalized );

	$price = wc_format_decimal( $normalized, wc_get_price_decimals() );
	return $price;
}

/**
 * Change the price string to float.
 * @param string $price The price
 * @return float
 */
function hbfwc_price_to_float( $price ) {
	$clean = wc_clean( $price ); // cleaning basic.
	$clean = html_entity_decode( $clean );
	$clean = trim( str_replace( array( "\xc2\xa0", ' ' ), '', $clean ) );

	// Keep canonical numeric values (e.g. 1250000.00000000) untouched by locale parsing.
	if ( is_numeric( $clean ) ) {
		return (float) $clean;
	}

	$thousand = wc_get_price_thousand_separator();
	$decimal  = wc_get_price_decimal_separator();

	if ( $thousand ) {
		$clean = str_replace( $thousand, '', $clean );
	}

	if ( $decimal !== '.' ) {
		$clean = str_replace( $decimal, '.', $clean );
	}

	$float = wc_format_decimal( $clean, wc_get_price_decimals() );
	return (float) $float;
}

/**
 * Return a translatable nights label for a given night count.
 *
 * @param int $nights Number of nights.
 * @return string e.g. "1 night" or "3 nights".
 */
function hbfwc_get_nights_label( int $nights ): string {
	$nights = absint( $nights );
	return sprintf(
		/* translators: Number of nights */
		_n( '%s night', '%s nights', $nights, 'hotel-booking-for-woocommerce' ),
		number_format_i18n( $nights )
	);
}

function hbfwc_wp_kses_input() {
	return [
		'div' => [
			'id'    => true,
			'class' => true,
		],
		'span' => [
			'class'      => true,
			'aria-label' => true,
			'data-tip'   => true,
			'tabindex'   => true
		],
		'input' => [
			'type'        => true,
			'id'          => true,
			'class'       => true,
			'placeholder' => true,
			'style'       => true,
			'name'        => true,
			'value'       => true,
			'disabled'    => true
		]
	];
}

/**
 * Parse **text** and ***text*** into safe HTML tags.
 *
 * - ***text*** => <em>text</em>
 * - **text**  => <strong>text</strong>
 *
 * @param string $text
 * @return string Safe HTML
 */
function hbfwc_parse_stars_to_html( string $text ): string {
	// ***text*** to <em>
	$text = preg_replace_callback(
		'/\*\*\*([^\*]+)\*\*\*/u',
		function ( $m ) {
			return '<em>' . esc_html( $m[1] ) . '</em>';
		},
		$text
	);

	// **text** to <strong>
	$text = preg_replace_callback(
		'/\*\*([^\*]+)\*\*/u',
		function ( $m ) {
			return '<strong>' . esc_html( $m[1] ) . '</strong>';
		},
		$text
	);

	// Escape the rest (but keep our tags)
	return wp_kses(
		$text,
		[
			'strong' => [],
			'em'     => [],
		]
	);
}

/**
 * Insert new array after specific key.
 */
function hbfwc_array_insert_after_key( array $array, string $after_key, array $insert ): array {
    $position = array_search(
        $after_key,
        array_keys( $array ),
        true
    );

    if ( false === $position ) {
        return array_merge( $array, $insert );
    }

    return array_merge(
        array_slice( $array, 0, $position + 1, true ),
        $insert,
        array_slice( $array, $position + 1, null, true )
    );
}
