<?php
/**
 * Smart Loop Template for Posts & WooCommerce Products with AJAX support
 *
 * @package Theplus
 * @since 6.0.5
 */

global $post, $product;

$PostType = ! empty( $settings['query'] ) ? $settings['query'] : 'post';

if ( empty( $post ) || ! isset( $post->ID ) ) {
	return; // Exit if not inside valid WP Loop or AJAX post context
}

setup_postdata( $post );

$_post_id = get_the_ID();
$_title   = get_the_title();
$_content = apply_filters( 'the_content', get_the_content() );


$template = str_replace( '{{tpae_title}}', $_title, $content_html );


if ( 'product' === $PostType ) {
	if ( empty( $product ) || ! is_a( $product, 'WC_Product' ) ) {
		$product = wc_get_product( $_post_id );
	}
}

// Basic content replacements
$template = str_replace( '{{tpae_excerpt}}', get_the_excerpt(), $template );
$template = str_replace( '{{tpae_image}}', get_the_post_thumbnail(), $template );
$template = str_replace( '{{tpae_permalink}}', get_permalink(), $template );
$template = str_replace( '{{tpae_image_url}}', get_the_post_thumbnail_url(), $template );
$template = str_replace( '{{tpae_author_meta}}', get_the_author_meta( 'display_name' ), $template );
$template = str_replace( '{{tpae_author_url}}', get_author_posts_url( get_the_author_meta( 'ID' ) ), $template );
$template = str_replace( '{{tpae_author_logo}}', get_custom_logo(), $template );

$template = str_replace( '{{tpae_time_created}}', get_the_date( 'H:i:s' ), $template );

// WooCommerce product price and cart logic
if ( $product instanceof WC_Product ) {
	$template = str_replace( '{{tpae_product_price}}', $product->get_price_html(), $template );

	if ( $product->is_type( 'variable' ) ) {
		$regular = wc_format_price_range(
			$product->get_variation_regular_price( 'min', true ),
			$product->get_variation_regular_price( 'max', true )
		);

		$sale = wc_format_price_range(
			$product->get_variation_sale_price( 'min', true ),
			$product->get_variation_sale_price( 'max', true )
		);

		$template = str_replace( '{{tpae_product_regular_price}}', $regular, $template );
		$template = str_replace( '{{tpae_product_sale_price}}', $sale, $template );
	} else {
		$template = str_replace( '{{tpae_product_regular_price}}', wc_price( $product->get_regular_price() ), $template );
		$template = str_replace( '{{tpae_product_sale_price}}', wc_price( $product->get_sale_price() ), $template );
	}

	$template = str_replace( '{{tpae_product_sku}}', $product->get_sku(), $template );
	$template = str_replace( '{{tpae_product_add_to_cart}}', do_shortcode( '[add_to_cart id="' . $product->get_id() . '"]' ), $template );
}

// Dynamic date formatting
$date_placeholders = array(
	'{{tpae_date_created}}' => 'Y-m-d',
	'{{tpae_date_created_m_y_d}}' => 'M Y d',
	'{{tpae_date_created_f_d_y}}' => 'F d, Y',
	'{{tpae_date_created_d_m_y}}' => 'd/m/Y',
	'{{tpae_date_created_m_d_y}}' => 'm-d-Y',
	'{{tpae_date_created_d_m_y_h}}' => 'd M Y H:i',
	'{{tpae_date_created_h_m_a}}' => 'h:i A',
	'{{tpae_date_created_d_m_y_g}}' => 'l, d M Y',
	'{{tpae_date_created_iso}}' => 'c',
	'{{tpae_date_created_rfc}}' => 'r',
	'{{tpae_date_created_day_month}}' => 'd F',
	'{{tpae_date_created_month_year}}' => 'F Y',
	'{{tpae_date_created_day}}' => 'l',
	'{{tpae_date_created_M_D_Y}}' => 'M d, Y',
);

foreach ( $date_placeholders as $placeholder => $format ) {
	$template = str_replace( $placeholder, get_the_date( $format ), $template );
}

// Dynamic sliced title: {{tpae_title_5}}
preg_match_all( '/\{\{tpae_title_(\d+)\}\}/', $template, $matches );
if ( ! empty( $matches[1] ) ) {
	foreach ( $matches[1] as $len ) {
		$template = str_replace( '{{tpae_title_' . $len . '}}', mb_substr( $_title, 0, (int) $len ), $template );
	}
}

// Dynamic sliced content: {{tpae_description_50}}
preg_match_all( '/\{\{tpae_description_(\d+)\}\}/', $template, $matches );
if ( ! empty( $matches[1] ) ) {
	foreach ( $matches[1] as $len ) {
		$template = str_replace( '{{tpae_description_' . $len . '}}', mb_substr( strip_tags( $_content ), 0, (int) $len ), $template );
	}
}
$template = str_replace( '{{tpae_description}}', $_content, $template );

// Categories
$category_output = '';
$current_post_type = get_post_type( $_post_id );
$terms = [];

if ( $current_post_type === 'product' ) {
	$terms = wp_get_post_terms( $_post_id, 'product_cat' );
} elseif ( $current_post_type === 'page' ) {
	foreach ( get_object_taxonomies( 'page', 'names' ) as $taxonomy ) {
		if ( ! in_array( $taxonomy, ['category', 'post_tag', 'post_format'] ) ) {
			$terms = array_merge( $terms, wp_get_post_terms( $_post_id, $taxonomy ) );
		}
	}
} else {
	$terms = get_the_category( $_post_id );
}

foreach ( $terms as $term ) {
	$category_output .= '<a href="' . esc_url( get_term_link( $term ) ) . '"><span class="tpae-slb-category">' . esc_html( $term->name ) . '</span></a>';
}
$template = str_replace( '{{tpae_category}}', $category_output, $template );

// Tags
$tag_output = '';
$tags = get_the_tags( $_post_id );
if ( $tags ) {
	foreach ( $tags as $tag ) {
		$tag_output .= '<a href="' . get_tag_link( $tag ) . '"><span class="tpae-slb-tag">' . esc_html( $tag->name ) . '</span></a>';
	}
	$template = str_replace( '{{tpae_tag}}', $tag_output, $template );

	preg_match_all( '/\{\{tpae_tag_(\d+)\}\}/', $template, $tag_matches );
	if ( ! empty( $tag_matches[1] ) ) {
		foreach ( $tag_matches[1] as $count ) {
			$selected_tags = array_slice( $tags, 0, (int) $count );
			$output = '';
			foreach ( $selected_tags as $tag ) {
				$output .= '<a href="' . get_tag_link( $tag ) . '"><span class="tpae-slb-tag">' . esc_html( $tag->name ) . '</span></a>';
			}
			$template = str_replace( '{{tpae_tag_' . $count . '}}', $output, $template );
		}
	}
}

// ACF Support
if ( function_exists( 'get_field' ) ) {
	preg_match_all( '/\{\{([a-zA-Z0-9_\-]+)\}\}/', $template, $acf_matches );
	$built_in = array(
		'tpae_title', 'tpae_excerpt', 'tpae_image', 'tpae_permalink', 'tpae_image_url', 'tpae_author_meta',
		'tpae_author_url', 'tpae_author_logo', 'tpae_time_created', 'tpae_product_price',
		'tpae_product_regular_price', 'tpae_product_sale_price', 'tpae_product_sku',
		'tpae_product_add_to_cart', 'tpae_description', 'tpae_category', 'tpae_tag',
	);

	foreach ( $acf_matches[1] as $field ) {
		if ( in_array( $field, $built_in, true ) ) continue;

		$value = get_field( $field, $_post_id );
		if ( is_array( $value ) && isset( $value['url'] ) ) {
			$value = '<img src="' . esc_url( $value['url'] ) . '" alt="' . esc_attr( $value['alt'] ?? '' ) . '" />';
		} elseif ( is_array( $value ) ) {
			$value = implode( ', ', array_map( 'esc_html', $value ) );
		}
		$template = str_replace( '{{' . $field . '}}', wp_kses_post( $value ), $template );
	}
}

?>

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
	<div class="blog-list-content">
		<?php echo $template; ?>
		<?php require THEPLUS_WSTYLES . 'dynamic-listing/blog-skeleton.php'; ?>
	</div>
</article>

<?php wp_reset_postdata(); ?>