<?php
/**
 * Tag filter shortcode.
 *
 * @package EventimUSEventListings
 */

defined( 'ABSPATH' ) || exit;

global $evuselConfig;
add_shortcode( $evuselConfig::SHORTCODE_TAG_FILTER, 'evusel_tag_filter_shortcode' );
/**
 * Render tag filter shortcode.
 *
 * @param array $atts Shortcode attributes.
 * @return string Shortcode output.
 */
function evusel_tag_filter_shortcode( $atts ) {
	global $evuselConfig;

	$hideRepeating = $evuselConfig->get( 'show_repeating_events' ) === false;
	$selectedTags  = isset( $atts['tags'] ) ?
		array_filter( explode( ',', $atts['tags'] ) ) :
		'';

	$args = array(
		'post_type'      => 'seetickets-event',
		'posts_per_page' => -1,
		'post_parent'    => 0,
		'tax_query'      => array(
			array(
				'taxonomy' => 'seetickets-event-tag',
				'field'    => 'slug',
				'terms'    => $selectedTags,
			),
		),
		'meta_query'     => array( 'relation' => 'AND' ),
		'no_found_rows'  => true,
		'orderby'        => 'meta_value',
		'order'          => 'ASC',
		'meta_key'       => 'event_time',
		'meta_type'      => 'datetime',
	);

	if ( $hideRepeating ) {
		$args['post_parent'] = 0;
	}

	evusel_add_passed_meta_criteria( $args );

	$events = get_posts( $args );

	// Filter multi-day events to show only the parent once
	if ( ! $hideRepeating ) {
		$events = evusel_filter_multi_day_events_results( $events );
	}

	$string = '<div id="list-view-events">';

	if ( empty( $events ) ) {
		$string .= '<div id="filtered-events-list" class="seetickets-list-events"><p>There are no events with the selected tag(s)</p></div>';
	} else {

		$templateType = $atts['type'] ?? 'list';
		$listType     = $templateType === 'list' ? 'l' : 'g';

		$columnAmount = (int) $evuselConfig->get( 'shortcodes.list_view.column_amount' );
		$mainClasses  = 'seetickets-list-events ';
		$mainClasses .= $listType === 'l' ? '' : 'grid-container display-flex grid-cols-' . $columnAmount . ' ';

		$string .= '<div id="filtered-events-list" class="' . esc_attr( $mainClasses ) . '">';

		foreach ( $events as $event ) {

			// if ($hideRepeating && has_post_parent($event)) {

			// $parent = get_post_parent($event);
			// $repeatingDates = $parent->repeating_dates;
			// $lastRepeatingDate = end($repeatingDates);
			// $sortDateTime = DateTime::createFromFormat('Ymd', $event->sort_date);

			// if ($lastRepeatingDate != $sortDateTime->format('m/d/Y')) {
			// continue; // Skip all repeating event,s except for the last one.
			// }
			// }

			$eventDateTime = evusel_get_event_display_date_time( $event->ID );
			$eventImage    = evusel_get_event_image( $event->ID );

			$ticketLink       = evusel_get_ticket_link( $event );
			$ticketButtonLink = evusel_get_ticket_link( $event, true );
			$ticketShareLink  = urldecode( $ticketLink );

			$eventTitle = get_post_meta( $event->ID, 'event_title', true );

			$btnText   = evusel_get_ticket_status_button_text( $event );
			$ariaLabel = evusel_get_ticket_button_aria_label( false, $eventTitle, $eventDateTime );

			$socialClasses = $evuselConfig->get( 'social_icon_circles' ) === 'on' ? 'social-circle ' : 'social-icon ';
			$classes       = evusel_get_ticket_status_button_classes( $event );

			$containerClasses  = 'seetickets-list-event-container mdc-card ';
			$containerClasses .= $listType === 'g' ? 'grid-item ' : '';
			$containerClasses .= $evuselConfig->get( 'shortcodes.tag_filter.material_list_style' ) === 'outlined' ? 'mdc-card--outlined ' : '';

			$dimensionsPerColumn = $evuselConfig->get( 'imageDimensionsPerColumn' );

			$gridImageContainerStyle  = $listType === 'l' ? 'width: 275px; height: 275px; ' : 'width: 100%; aspect-ratio: 1 / 1; ';
			$gridImageContainerStyle .= $evuselConfig->get( 'event_image_style' ) === 'square' ?
				'object-fit: cover; ' :
				'object-fit: contain; ';

			$image = evusel_anchorize( '<img src="' . esc_url( $eventImage ) . '" style="' . esc_attr( $gridImageContainerStyle ) . '" class="seetickets-list-view-event-image">', $event );

			$buttonTarget          = "<a href='" . esc_url( $ticketLink ) . "'  class='seetickets-buy-btn " . esc_attr( $classes ) . " fs-12 '  aria-label='" . esc_attr( $ariaLabel ) . "' >" . esc_html( $btnText ) . '</a>';
			$openEventPageToNewTab = $evuselConfig->get( 'open_event_page_to_new_tab' );
			if ( $openEventPageToNewTab == 'on' ) {
				$buttonTarget = "<a href='" . esc_url( $ticketLink ) . "' target='_blank' class='seetickets-buy-btn " . esc_attr( $classes ) . " fs-12 '  aria-label='" . esc_attr( $ariaLabel ) . "' >" . esc_html( $btnText ) . '</a>';
			}

				$listElementTemplate = str_replace(
					array(
						'{%image%}',
						'{%cardLabels%}',
						'{%buttonClasses%}',
						'{%eventButtonText%}',
						'{%eventContainerClass%}',
						'{%eventContainerStyle%}',
						'{%pluginDirUrl%}',
						'{%facebookShareText%}',
						'{%twitterSharetext%}',
						'{%ticketLink%}',
						'{%socialClasses%}',
						'{%ariaLabel%}',
						'{%facebookIcon%}',
						'{%twitterIcon%}',
						'{%openEventPageToNewTab%}',
					),
					array(
						$image,
						evusel_getCardLabelsHtml( $event, $eventTitle, 'tags', false, $eventDateTime ),
						esc_attr( $classes ),
						esc_html( $btnText ),
						esc_attr( $containerClasses ),
						'',
						esc_url( EVUSEL_PLUGIN_DIR_URL ),
						esc_url( $ticketShareLink ),
						esc_url( $ticketShareLink ),
						esc_url( $ticketButtonLink ),
						esc_attr( $socialClasses ),
						esc_attr( $ariaLabel ),
						'<span class="d-inline-block ' . esc_attr( $socialClasses ) . '">' . file_get_contents( EVUSEL_PLUGIN_DIR . '/images/facebook-icon.svg' ) . '</span>',
						'<span class="d-inline-block ' . esc_attr( $socialClasses ) . '">' . file_get_contents( EVUSEL_PLUGIN_DIR . '/images/x-twitter-brands-solid.svg' ) . '</span>',
						$buttonTarget,
					),
					file_get_contents( EVUSEL_PLUGIN_DIR . "includes/templates/event_{$templateType}_element.html" )
				);

				$string .= $listElementTemplate;
		}

			$string .= '</div></div>';
	}

	if ( empty( $events ) ) {
		$string .= '</div>';
	}

		return $string;
}
