<?php
/**
 * Past events shortcode.
 *
 * @package EventimUSEventListings
 */

defined( 'ABSPATH' ) || exit;

global $evuselConfig;
add_shortcode( $evuselConfig::SHORTCODE_PAST_EVENTS, 'evusel_past_events_shortcode' );
/**
 * Render past events shortcode.
 *
 * @return string Shortcode output.
 */
function evusel_past_events_shortcode() {

	// TODO: implement hiding repeating events if re-enabled.

	global $evuselConfig;

	$string    = '<div id="list-view-events">';
	$maxEvents = $evuselConfig->get( 'shortcodes.past_events.max_events' );
	$limit     = $evuselConfig->get( 'shortcodes.past_events.per_page' );
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading sanitized GET parameter for pagination
	$page = isset( $_GET['sepage'] ) ? intval( $_GET['sepage'] ) : 1;

	$currentLimit = ( $page * $limit ) > $maxEvents ? $maxEvents - ( ( $page - 1 ) * $limit ) : $limit;

	$passedIf = $evuselConfig->get( 'shortcodes.past_events.past_event_if' );

	$getPosts = new WP_Query();
	$args     = array(
		'posts_per_page' => $currentLimit,
		'post_type'      => 'seetickets-event',
		'post_status'    => array( 'publish' ),
		'meta_query'     => array( 'relation' => 'OR' ),
		'orderby'        => array(
			'eventpassed_clause'       => 'desc',
			'eventtimepassed_clause'   => 'desc',
			'offsaletimepassed_clause' => 'desc',
		),
	);

	$dateTimeZone = new DateTimeZone( 'UTC' );

	$now = ( new DateTime( 'now', $dateTimeZone ) );

	if ( in_array( 'eventdatepassed', $passedIf ) ) {
		$args['meta_query']['eventpassed_clause'] = array(
			'key'     => 'sort_date',
			'value'   => $now->format( 'Ymd' ),
			'compare' => '<',
			'type'    => 'date',
		);
	}
	if ( in_array( 'eventtimepassed', $passedIf ) ) {
		$utcNow                                       = ( clone $now )->setTimezone( new DateTimeZone( 'UTC' ) );
		$args['meta_query']['eventtimepassed_clause'] = array(
			'key'     => 'end_time',
			'value'   => $utcNow->format( 'Y-m-d H:i:s' ),
			'compare' => '<',
			'type'    => 'datetime',
		);
	}
	if ( in_array( 'offsaletimepassed', $passedIf ) ) {
		$args['meta_query']['offsaletimepassed_clause'] = array(
			'key'     => 'offsale',
			'value'   => $now->format( 'Y-m-d H:i:s' ),
			'compare' => '<',
			'type'    => 'datetime',
		);
	}

	$events     = $getPosts->query( $args );
	$totalPages = $getPosts->max_num_pages;
	$maxPages   = ceil( $maxEvents / $limit );
	$totalPages = $totalPages > $maxPages ? $maxPages : $totalPages;

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

	foreach ( $events as $index => $event ) {

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

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

		$alternate = $evuselConfig->get( 'shortcodes.list_view.use_alternating_view' ) === 'on' && ( $index % 2 ) !== 0 ? '_alternate' : '';

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

		$containerClasses  = 'seetickets-list-event-container mdc-card ';
		$containerClasses .= $evuselConfig->get( 'shortcodes.past_events.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 );

		$listElementTemplate = str_replace(
			array(
				'{%image%}',
				'{%cardLabels%}',
				'{%eventContainerClass%}',
				'{%eventContainerStyle%}',
				'{%pluginDirUrl%}',
			),
			array(
				$image,
				evusel_getCardLabelsHtml( $event, $eventTitle, 'past-evets', false, $eventDateTime ),
				esc_attr( $containerClasses ),
				'',
				esc_url( EVUSEL_PLUGIN_DIR_URL ),
			),
			file_get_contents( EVUSEL_PLUGIN_DIR . 'includes/templates/event_list_element_past' . $alternate . '.html' )
		);

		$string .= $listElementTemplate;
	}

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

	if ( $totalPages > $page ) {
		$string .= '<div class="display-flex justify-center"><button id="seetickets-past-events-load-more-button" class="seetickets-load-more-btn" data-see-ajax-page="2" data-see-total-pages="' . esc_attr( $totalPages ) . '">+ LOAD MORE EVENTS<img src="' . esc_url( EVUSEL_PLUGIN_DIR_URL . '/images/spinner.svg' ) . '" alt="" id="convert-webp-spinner"></button></div>';
	}

	return $string;
}

add_action( 'wp_ajax_evusel_fetch_past_events', 'evusel_fetch_past_events' );
add_action( 'wp_ajax_nopriv_evusel_fetch_past_events', 'evusel_fetch_past_events' );
/**
 * Fetch past events via AJAX.
 *
 * @return void
 */
function evusel_fetch_past_events() {
	$nonce = isset( $_GET['nonce'] ) ? sanitize_text_field( wp_unslash( $_GET['nonce'] ) ) : '';
	if ( empty( $nonce ) || ! wp_verify_nonce( $nonce, 'evusel-nonce' ) ) {
		wp_die( esc_html__( 'Security check failed', 'eventim-us-event-listings' ) );
	}

	global $evuselConfig;

	$string = '';
	$limit  = $evuselConfig->get( 'shortcodes.past_events.per_page' );

	$page      = isset( $_REQUEST['seeAjaxPage'] ) ? intval( $_REQUEST['seeAjaxPage'] ) : 1;
	$offset    = ( $page - 1 ) * $limit;
	$maxEvents = $evuselConfig->get( 'shortcodes.past_events.max_events' );

	$currentLimit = ( $page * $limit ) > $maxEvents ? $maxEvents - ( ( $page - 1 ) * $limit ) : $limit;

	$passedIf = $evuselConfig->get( 'shortcodes.past_events.past_event_if' );

	$getPosts = new WP_Query();
	$args     = array(
		'posts_per_page' => $currentLimit,
		'offset'         => $offset,
		'post_type'      => 'seetickets-event',
		'post_status'    => array( 'publish' ),
		'meta_query'     => array( 'compare' => 'OR' ),
		'orderby'        => 'meta_value',
		'order'          => 'DESC',
		'meta_key'       => 'sort_date',
		'meta_type'      => 'date',
		'no_found_rows'  => true,
	);

	$dateTimeZone = new DateTimeZone( 'UTC' );
	$now          = ( new DateTime() )->setTimezone( $dateTimeZone );

	if ( in_array( 'eventdatepassed', $passedIf ) || in_array( 'eventtimepassed', $passedIf ) ) {

		$args['meta_query'][] = array(
			'key'     => 'sort_date',
			'value'   => $now->format( 'Ymd' ),
			'compare' => '<=',
			'type'    => 'date',
		);
	}
	if ( in_array( 'offsaletimepassed', $passedIf ) ) {

		$args['meta_query'][] = array(
			'key'     => 'offsale',
			'value'   => $now->format( 'Y-m-d H:i:s' ),
			'compare' => '<=',
			'type'    => 'datetime',
		);
	}

	$events = $getPosts->query( $args );

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

	foreach ( $events as $index => $event ) {

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

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

		$alternate =
			( $index + $offset ) % 2 !== 0 &&
			$evuselConfig->get( 'shortcodes.list_view.use_alternating_view' ) === 'on' ?
				'_alternate' :
				'';

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

		$containerClasses  = 'seetickets-list-event-container mdc-card ';
		$containerClasses .= $evuselConfig->get( 'shortcodes.past_events.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 );

		$listElementTemplate = str_replace(
			array(
				'{%image%}',
				'{%cardLabels%}',
				'{%eventContainerClass%}',
				'{%eventContainerStyle%}',
				'{%pluginDirUrl%}',
			),
			array(
				$image,
				evusel_getCardLabelsHtml( $event, $eventTitle, 'past-evets', false, $eventDateTime ),
				esc_attr( $containerClasses ),
				'',
				esc_url( EVUSEL_PLUGIN_DIR_URL ),
			),
			file_get_contents( EVUSEL_PLUGIN_DIR . 'includes/templates/event_list_element_past' . $alternate . '.html' )
		);

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

	echo wp_kses_post( $string );
	wp_die();
}
