<?php
/**
 * Just announced events shortcode.
 *
 * @package EventimUSEventListings
 */

defined( 'ABSPATH' ) || exit;

/**
 * Render just announced events shortcode.
 *
 * @param array $atts Shortcode attributes.
 * @return string Shortcode output.
 */
function evusel_just_announced_events_shortcode( $atts ) {

	global $evuselConfig;
	$limit         = intval( $evuselConfig->get( 'shortcodes.just_announced.no_to_display' ) );
	$hideRepeating = $evuselConfig->get( 'show_repeating_events' ) === false;

	$string = '';

	$tagParameters = isset( $atts['tag-parameters'] ) ?
		array_filter( explode( ',', $atts['tag-parameters'] ) ) :
		'';

	$args = array(
		'numberposts'   => -1,
		'post_type'     => 'seetickets-event',
		'post_status'   => array( 'publish' ),
		'no_found_rows' => true,
	);

	if ( ! empty( $tagParameters ) ) {
		$args['tax_query'] = array(
			array(
				'taxonomy' => 'seetickets-event-tag',
				'field'    => 'slug',
				'terms'    => $tagParameters,
			),
		);
	}

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

	$all_events = get_posts( $args );

	if ( ! is_array( $all_events ) ) {
		$all_events = array();
	}

	if ( ! $hideRepeating ) {
		$all_events = evusel_filter_multi_day_events_results( $all_events );
	}

	$events_with_dates = array();

	foreach ( $all_events as $event ) {
		if ( ! is_object( $event ) || ! isset( $event->ID ) ) {
			continue;
		}

		$publish_date = null;
		$source       = 'none';

		if ( function_exists( 'get_field' ) ) {
			$publish_date = get_field( 'publish_date', $event->ID );
			if ( ! empty( $publish_date ) ) {
				$source = 'acf_field';
			}
		}

		if ( empty( $publish_date ) ) {
			$publish_date = get_post_meta( $event->ID, 'publish_date', true );
			if ( ! empty( $publish_date ) ) {
				$source = 'post_meta';
			}
		}

		if ( empty( $publish_date ) ) {
			$publish_date = $event->post_date;
			if ( ! empty( $publish_date ) ) {
				$source = 'post_date';
			}
		}

		if ( empty( $publish_date ) ) {
			$publish_date = get_post_meta( $event->ID, 'event_time', true );
			if ( ! empty( $publish_date ) ) {
				$source = 'event_time';
			}
		}

		if ( ! empty( $publish_date ) ) {
			if ( function_exists( 'evusel_debug_log' ) ) {
				evusel_debug_log( 'Just Announced Events - Event ID: ' . $event->ID . ', publish_date: ' . $publish_date . ', source: ' . $source );
			}
			$events_with_dates[] = array(
				'event'        => $event,
				'publish_date' => $publish_date,
			);
		}
	}

	if ( ! empty( $events_with_dates ) ) {
		usort(
			$events_with_dates,
			function( $a, $b ) {
				$date_a = strtotime( $a['publish_date'] );
				$date_b = strtotime( $b['publish_date'] );

				if ( false === $date_a || false === $date_b ) {
					return 0;
				}

				if ( $date_a === $date_b ) {
					return $b['event']->ID - $a['event']->ID;
				}

				return $date_b - $date_a;
			}
		);

		$events = array_slice( array_column( $events_with_dates, 'event' ), 0, $limit );
	} else {
		$events = array();
	}

	$string .= '<div id="list-view-events"><div id="just-announced-events-list" class="seetickets-list-events">';

	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 );
		$dispevliIsInPast = evuselIsInPast( $event );
		$eventImage       = evusel_get_event_image( $event->ID );

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

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

		$ticketLink = evusel_get_ticket_link( $event );

		$socialClasses    = $evuselConfig->get( 'social_icon_circles' ) === 'on' ? 'social-circle ' : 'social-icon ';
		$ticketLink       = evusel_get_ticket_link( $event );
		$ticketButtonLink = evusel_get_ticket_link( $event, true );
		$ticketShareLink  = urldecode( $ticketLink );

		$classes  = $dispevliIsInPast ? 'disabled ' : '';
		$classes .= evusel_get_ticket_status_button_classes( $event );

		$containerClasses  = 'seetickets-list-event-container mdc-card ';
		$containerClasses .= $evuselConfig->get( 'shortcodes.just_announced.material_list_style' ) === 'outlined' ? 'mdc-card--outlined ' : '';

		$style  = 'width: 275px; height: 275px; ';
		$style .= $evuselConfig->get( 'event_image_style' ) === 'square' ?
			'object-fit: cover; ' :
			'object-fit: contain; ';

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

		$openEventPageToNewTab = $evuselConfig->get( 'open_event_page_to_new_tab' );
		$ticketLink            = evusel_get_ticket_link( $event );
		if ( $openEventPageToNewTab == 'on' ) {

			$listElementTemplate = str_replace(
				array(
					'{%image%}',
					'{%cardLabels%}',
					'{%buttonClasses%}',
					'{%eventButtonText%}',
					'{%eventContainerClass%}',
					'{%eventContainerStyle%}',
					'{%pluginDirUrl%}',
					'{%ticketLink%}',
					'{%socialClasses%}',
					'{%ariaLabel%}',
					'{%facebookShareText%}',
					'{%twitterSharetext%}',
					'{%facebookIcon%}',
					'{%twitterIcon%}',
					'{%openEventPageToNewTab%}',
				),
				array(
					$image,
					evusel_getCardLabelsHtml( $event, $eventTitle, 'just-announced', false, $eventDateTime ),
					esc_attr( $classes ),
					esc_html( $btnText ),
					esc_attr( $containerClasses ),
					'',
					esc_url( EVUSEL_PLUGIN_DIR_URL ),
					esc_url( $ticketButtonLink ),
					esc_attr( $socialClasses ),
					esc_attr( $ariaLabel ),
					esc_url( $ticketShareLink ),
					esc_url( $ticketShareLink ),
					'<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>',
					"<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>',
				),
				file_get_contents( EVUSEL_PLUGIN_DIR . 'includes/templates/event_list_element.html' )
			);
		} else {
			$listElementTemplate = str_replace(
				array(
					'{%image%}',
					'{%cardLabels%}',
					'{%buttonClasses%}',
					'{%eventButtonText%}',
					'{%eventContainerClass%}',
					'{%eventContainerStyle%}',
					'{%pluginDirUrl%}',
					'{%ticketLink%}',
					'{%socialClasses%}',
					'{%ariaLabel%}',
					'{%facebookShareText%}',
					'{%twitterSharetext%}',
					'{%facebookIcon%}',
					'{%twitterIcon%}',
					'{%openEventPageToNewTab%}',
				),
				array(
					$image,
					evusel_getCardLabelsHtml( $event, $eventTitle, 'just-announced', false, $eventDateTime ),
					esc_attr( $classes ),
					esc_html( $btnText ),
					esc_attr( $containerClasses ),
					'',
					esc_url( EVUSEL_PLUGIN_DIR_URL ),
					esc_url( $ticketButtonLink ),
					esc_attr( $socialClasses ),
					esc_attr( $ariaLabel ),
					esc_url( $ticketShareLink ),
					esc_url( $ticketShareLink ),
					'<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>',
					"<a href='" . esc_url( $ticketLink ) . "'  class='seetickets-buy-btn " . esc_attr( $classes ) . " fs-12 '  aria-label='" . esc_attr( $ariaLabel ) . "' >" . esc_html( $btnText ) . '</a>',
				),
				file_get_contents( EVUSEL_PLUGIN_DIR . 'includes/templates/event_list_element.html' )
			);
		}
		$string .= $listElementTemplate;
	}

	if ( empty( $events ) ) {
		$string .= file_get_contents( EVUSEL_PLUGIN_DIR . 'includes/templates/no_events_found.html' );
	}

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

	return $string;
}

add_shortcode( $evuselConfig::SHORTCODE_JUST_ANNOUNCED_EVENTS, 'evusel_just_announced_events_shortcode' );
