<?php
/**
 * Output voor [bandboss_upcoming_events]
 * Prefix: bandupev_
 * Textdomain: bandboss-upcoming-events-manager
 */
if ( ! defined('ABSPATH') ) exit;

/* =========================
 *   STYLING HELPERS
 * ========================= */
function bandupev_style_defaults() {
	return array(
		'date_day'    => array('font'=>'var(--e-global-typography-text-font-family)','font_size'=>'28','font_color'=>'var(--e-global-color-text)','font_weight'=>'700'),
		'date_num'    => array('font'=>'var(--e-global-typography-text-font-family)','font_size'=>'28','font_color'=>'var(--e-global-color-accent)','font_weight'=>'400'),
		'date_month'  => array('font'=>'var(--e-global-typography-text-font-family)','font_size'=>'28','font_color'=>'var(--e-global-color-text)','font_weight'=>'300'),
		'date_year'   => array('font'=>'var(--e-global-typography-text-font-family)','font_size'=>'28','font_color'=>'var(--e-global-color-text)','font_weight'=>'300'),
		'venue'       => array('font'=>'var(--e-global-typography-text-font-family)','font_size'=>'24','font_color'=>'var(--e-global-color-text)','font_weight'=>'400'),
		'start_time'  => array('font'=>'var(--e-global-typography-text-font-family)','font_size'=>'16','font_color'=>'var(--e-global-color-text)','font_weight'=>'400'),
		'entrance_fee'=> array('font'=>'var(--e-global-typography-text-font-family)','font_size'=>'16','font_color'=>'var(--e-global-color-text)','font_weight'=>'400'),
		'city'        => array('font'=>'var(--e-global-typography-primary-font-family)','font_size'=>'24','font_color'=>'var(--e-global-color-accent)','font_weight'=>'400'),
		// Let op: 'color' bij ticket_sale gebruiken we als BUTTON background-color
		'ticket_sale' => array('font'=>'var(--e-global-typography-text-font-family)','font_size'=>'16','font_color'=>'var(--e-global-color-text)','font_weight'=>'700','color'=>'transparent'),
	);
}

/** Haal 1 style property op (Free => defaults; Pro => option fallback naar defaults) */
function bandupev_style($field, $prop) {
	if ( defined('BANDUPEV_IS_FREE') && BANDUPEV_IS_FREE ) {
		$defs = bandupev_style_defaults();
		return isset($defs[$field][$prop]) ? $defs[$field][$prop] : '';
	}
	$opt = get_option("bandupev_event_style_{$field}_{$prop}", '');
	if ($opt === '' || $opt === null) {
		$defs = bandupev_style_defaults();
		return isset($defs[$field][$prop]) ? $defs[$field][$prop] : '';
	}
	return $opt;
}

/** Bouw inline style string voor een veld */
function bandupev_style_attr($field) {
	$css = array();
	$font   = bandupev_style($field,'font');          if ($font)   $css[] = "font-family:{$font}";
	$weight = bandupev_style($field,'font_weight');   if ($weight) $css[] = "font-weight:{$weight}";
	$color  = bandupev_style($field,'font_color');    if ($color)  $css[] = "color:{$color}";
	$size   = bandupev_style($field,'font_size');     if ($size)   $css[] = "font-size:{$size}px";
	return implode('; ', $css);
}

/** Parse Y-m-d meta naar timestamp in WP-tz */
function bandupev_ts_from_meta( $ymd ) {
	$tz = wp_timezone();
	$dt = date_create_immutable_from_format('Y-m-d', (string) $ymd, $tz);
	return $dt ? $dt->getTimestamp() : 0;
}

/** Render 1 event-item (gebruikt voor zowel Coming als Past) */
function bandupev_render_event_item( $post_id ) {
	// Meta ophalen (nieuwe prefix upcoming_event_)
	$meta_keys = ['date','start_time','entrance_fee','venue','city','ticket_sale','facebook_event','website','country'];
	$values = [];
	foreach ( $meta_keys as $mk ) {
		$values[$mk] = get_post_meta( $post_id, 'upcoming_event_' . $mk, true );
	}
	$highlighted = get_post_meta( $post_id, 'upcoming_event_highlighted', true );
	$sold_out    = get_post_meta( $post_id, 'upcoming_event_sold_out', true );

	// Datum formatteren
	$ts = bandupev_ts_from_meta( $values['date'] );
	$day_style   = bandupev_style_attr('date_day');
	$num_style   = bandupev_style_attr('date_num');
	$month_style = bandupev_style_attr('date_month');
	$year_style  = bandupev_style_attr('date_year');

	echo '<div class="upcoming-event-item' . ( $highlighted ? ' highlighted' : '' ) . '">';
	echo '<div class="upcoming-event-table">';

		// Vlag (land)
		if ( ! empty( $values['country'] ) ) {
			echo '<div class="country-flag"><span class="fi fi-' . esc_attr( strtolower( $values['country'] ) ) . '"></span></div>';
		}

		// Datum + tijd/prijs
		echo '<div class="date-time">';
			echo '<p class="upcoming-event-meta-item upcoming-event-date">';
				if ( $ts ) {
					echo '<span class="day"     style="' . esc_attr( $day_style )   . '">' . esc_html( wp_date( 'D', $ts ) ) . '</span>';
					echo '<span class="day-num" style="' . esc_attr( $num_style )   . '">' . esc_html( wp_date( 'd', $ts ) ) . '</span>';
				}
			echo '</p>';
			echo '<p>';
				if ( $ts ) {
					echo '<span class="month"   style="' . esc_attr( $month_style ) . '">' . esc_html( wp_date( 'M', $ts ) ) . '</span>';
					echo '<span class="year"    style="' . esc_attr( $year_style )  . '">' . esc_html( "'" . wp_date( 'y', $ts ) ) . '</span>';
				}
			echo '</p>';
		echo '</div>';

		echo '<div class="time-price">';
			if ( ! empty( $values['start_time'] ) ) {
				$st_style = bandupev_style_attr('start_time');
				echo '<div><i class="far fa-clock" aria-hidden="true"></i> ';
				echo '<span class="upcoming-event-meta-item upcoming-event-starttime" style="' . esc_attr( $st_style ) . '">' . esc_html( $values['start_time'] ) . '</span>';
				echo '</div>';
			}
			if ( ! empty( $values['entrance_fee'] ) ) {
				$fee_style = bandupev_style_attr('entrance_fee');
				echo '<span class="upcoming-event-meta-item upcoming-event-entrance-fee" style="' . esc_attr( $fee_style ) . '">' . esc_html( $values['entrance_fee'] ) . '</span>';
			}
		echo '</div>';

		// Venue + City + Facebook
		echo '<div class="venue-locatie-facebook">';
			// Venue (optioneel klikbaar via website)
			echo '<div class="venue">';
				$v_style = bandupev_style_attr('venue');
				if ( ! empty( $values['venue'] ) ) {
					if ( ! empty( $values['website'] ) ) {
						echo '<a href="' . esc_url( $values['website'] ) . '" style="' . esc_attr( $v_style ) . '" target="_blank" rel="noopener noreferrer">';
					}
					echo '<span style="' . esc_attr( $v_style ) . '" class="upcoming-event-meta-item upcoming-event-venue">' . esc_html( $values['venue'] ) . '</span>';
					if ( ! empty( $values['website'] ) ) {
						echo '</a>';
					}
				}
			echo '</div>';

			// City + Facebook
			echo '<div class="locatie-facebook">';
				$c_style = bandupev_style_attr('city');
				if ( ! empty( $values['city'] ) ) {
					echo '<span class="upcoming-event-meta-item upcoming-event-city" style="' . esc_attr( $c_style ) . '">' . esc_html( $values['city'] ) . '</span>';
				}
				if ( ! empty( $values['facebook_event'] ) ) {
					echo ' <a href="' . esc_url( $values['facebook_event'] ) . '" target="_blank" rel="noopener noreferrer" aria-label="Facebook event">';
					echo '<span class="upcoming-event-meta-item upcoming-event-facebook-event"><i aria-hidden="true" class="dashicons-facebook"></i></span>';
					echo '</a>';
				}
			echo '</div>';
		echo '</div>';

		// Tickets / Sold out
		if ( ! empty( $values['ticket_sale'] ) || (string) $sold_out === '1' ) {
			// ruwe waardes
			$font       = bandupev_style('ticket_sale','font');
			$weight     = bandupev_style('ticket_sale','font_weight');
			$size       = (int) bandupev_style('ticket_sale','font_size');
			$bg         = bandupev_style('ticket_sale','color');
			$font_color = bandupev_style('ticket_sale','font_color');

			$btn_style = sprintf(
				'font-family:%s; font-weight:%s; font-size:%dpx; background-color:%s; color:%s',
				$font, $weight, $size, $bg, $font_color
			);

			echo '<div class="ticketbutton-container">';
			if ( (string) $sold_out === '1' ) {
				$badge_style = sprintf(
					'font-family:%s; font-weight:%s; color:%s; font-size:%dpx',
					$font, $weight, $font_color, $size
				);
				echo '<div class="soldout-message" style="' . esc_attr( $badge_style ) . '">'
					. esc_html__( 'Sold Out', 'bandboss-upcoming-events-manager' )
					. '</div>';
			} elseif ( ! empty( $values['ticket_sale'] ) ) {
				echo '<a href="' . esc_url( $values['ticket_sale'] ) . '"'
					. ' class="upcoming-event-ticket-sale" target="_blank" rel="noopener noreferrer"'
					. ' style="' . esc_attr( $btn_style ) . '">'
					. esc_html__( 'Tickets', 'bandboss-upcoming-events-manager' )
					. '</a>';
			}
			echo '</div>';
		}

	echo '</div>'; // .upcoming-event-table
	echo '</div>'; // .upcoming-event-item
}

/** Full-width pager: |<  <  [shown]/[total]  >  >| */
function bandupev_render_pagination_bar( $total, $per_page ) {
	echo '<div class="upcoming-events-pagination" data-per-page="' . esc_attr( $per_page ) . '" data-total="' . esc_attr( $total ) . '">';
	echo '<button type="button" class="uep-btn uep-first" aria-label="' . esc_attr__( 'First page', 'bandboss-upcoming-events-manager' ) . '">|&laquo;</button>';
	echo '<button type="button" class="uep-btn uep-prev" aria-label="' . esc_attr__( 'Previous page', 'bandboss-upcoming-events-manager' ) . '">&laquo;</button>';
	echo '<span class="uep-counter"><span class="uep-shown">' . esc_html( min( $per_page, $total ) ) . '</span>/<span class="uep-total">' . esc_html( $total ) . '</span></span>';
	echo '<button type="button" class="uep-btn uep-next" aria-label="' . esc_attr__( 'Next page', 'bandboss-upcoming-events-manager' ) . '">&raquo;</button>';
	echo '<button type="button" class="uep-btn uep-last" aria-label="' . esc_attr__( 'Last page', 'bandboss-upcoming-events-manager' ) . '">&raquo;|</button>';
	echo '</div>';
}

/* =========================
 *   SHORTCODE
 * ========================= */
function bandupev_upcoming_events_shortcode( $atts = [] ) {
	$atts = shortcode_atts(
		[ 'show_all' => 'false', 'max_items' => '' ],
		$atts,
		'bandboss_upcoming_events'
	);

	$today     = wp_date('Y-m-d');
	$mode      = get_option('bandupev_events_display_mode', 'number');
	$limit     = (int) get_option('bandupev_events_number_of_items', 3);
	$end_date  = get_option('bandupev_events_end_date', wp_date('Y-m-d', strtotime('+3 months', current_time('timestamp'))));
	$show_all  = ( strtolower($atts['show_all']) === 'true' );
	$max_items = (int) $atts['max_items'];

	// Compat: lees nieuwe CPT, plus oude indien nog aanwezig
	$post_types = array('upcoming_event');
	if (post_type_exists('bandupev_event')) {
		$post_types[] = 'bandupev_event';
	}

	ob_start();

	if ( $show_all ) {
		$base_args = [
			'post_type'           => $post_types,
			'post_status'         => 'publish',
			'meta_key'            => 'upcoming_event_date',
			'meta_type'           => 'DATE',
			'no_found_rows'       => true,
			'ignore_sticky_posts' => true,
		];

		// "Coming" — vanaf vandaag, oplopend, optioneel begrensd door max_items
		$coming_args = array_merge( $base_args, [
			'posts_per_page' => $max_items > 0 ? $max_items : -1,
			'orderby'        => 'meta_value',
			'order'          => 'ASC',
			'meta_query'     => [[
				'key'     => 'upcoming_event_date',
				'value'   => $today,
				'compare' => '>=',
				'type'    => 'DATE',
			]],
		] );
		$coming_q = new \WP_Query( $coming_args );

		// "Past" — voor vandaag, aflopend (nieuwste eerst), alles ophalen (client-side paginatie)
		$past_args = array_merge( $base_args, [
			'posts_per_page' => -1,
			'orderby'        => 'meta_value',
			'order'          => 'DESC',
			'meta_query'     => [[
				'key'     => 'upcoming_event_date',
				'value'   => $today,
				'compare' => '<',
				'type'    => 'DATE',
			]],
		] );
		$past_q = new \WP_Query( $past_args );

		$past_per_page = 25;

		echo '<div class="upcoming-events-wrapper">';

		echo '<div class="upcoming-events-tabs" role="tablist">';
		echo '<h3 class="upcoming-events-tab is-active" data-tab="coming" role="tab" tabindex="0" aria-selected="true">' . esc_html__( 'Coming', 'bandboss-upcoming-events-manager' ) . '</h3>';
		echo '<h3 class="upcoming-events-tab" data-tab="past" role="tab" tabindex="-1" aria-selected="false">' . esc_html__( 'Past', 'bandboss-upcoming-events-manager' ) . '</h3>';
		echo '</div>';

		// Coming panel
		echo '<div class="upcoming-events-panel is-active" data-panel="coming">';
		if ( $coming_q->have_posts() ) {
			echo '<div class="upcoming-events-list">';
			while ( $coming_q->have_posts() ) {
				$coming_q->the_post();
				bandupev_render_event_item( get_the_ID() );
			}
			echo '</div>';
			wp_reset_postdata();
		} else {
			echo '<p>' . esc_html__( 'No upcoming events found.', 'bandboss-upcoming-events-manager' ) . '</p>';
		}
		echo '</div>'; // .upcoming-events-panel[coming]

		// Past panel
		echo '<div class="upcoming-events-panel" data-panel="past">';
		if ( $past_q->have_posts() ) {
			echo '<div class="upcoming-events-list past-events-list" data-per-page="' . esc_attr( $past_per_page ) . '">';
			while ( $past_q->have_posts() ) {
				$past_q->the_post();
				bandupev_render_event_item( get_the_ID() );
			}
			echo '</div>';
			wp_reset_postdata();
			bandupev_render_pagination_bar( (int) $past_q->post_count, $past_per_page );
		} else {
			echo '<p>' . esc_html__( 'No past events found.', 'bandboss-upcoming-events-manager' ) . '</p>';
		}
		echo '</div>'; // .upcoming-events-panel[past]

		echo '</div>'; // .upcoming-events-wrapper

		return ob_get_clean();
	}

	$args = [
		'post_type'           => $post_types,
		'post_status'         => 'publish',
		'orderby'             => 'meta_value',
		'order'               => 'ASC',
		'meta_key'            => 'upcoming_event_date',
		'meta_type'           => 'DATE',
		'no_found_rows'       => true,
		'ignore_sticky_posts' => true,
	];

	if ( $mode === 'date' ) {
		$args['posts_per_page'] = -1;
		$args['meta_query'] = [
			'relation' => 'AND',
			[
				'key'     => 'upcoming_event_date',
				'value'   => $today,
				'compare' => '>=',
				'type'    => 'DATE',
			],
			[
				'key'     => 'upcoming_event_date',
				'value'   => $end_date,
				'compare' => '<=',
				'type'    => 'DATE',
			],
		];
	} else {
		$args['posts_per_page'] = max(1, $limit);
		$args['meta_query'] = [[
			'key'     => 'upcoming_event_date',
			'value'   => $today,
			'compare' => '>=',
			'type'    => 'DATE',
		]];
	}

	$q = new \WP_Query( $args );

	if ( ! $q->have_posts() ) {
		echo '<p>' . esc_html__('No upcoming events found.', 'bandboss-upcoming-events-manager') . '</p>';
		return ob_get_clean();
	}

	echo '<div class="upcoming-events-list">';
	while ( $q->have_posts() ) {
		$q->the_post();
		bandupev_render_event_item( get_the_ID() );
	}
	echo '</div>'; // .upcoming-events-list

	wp_reset_postdata();
	return ob_get_clean();
}

/* =========================
 *   ASSETS (flag icons + frontend js)
 * ========================= */
function bandupev_enqueue_flag_icons() {
	// Dit bestand staat relatief t.o.v. /includes/
	$rel  = '../assets/flag-icons/css/flag-icons.css';
	$path = plugin_dir_path(__FILE__) . $rel;
	$url  = plugin_dir_url(__FILE__)  . $rel;

	wp_enqueue_style(
		'bandupev-flag-icons',
		$url,
		array(),
		file_exists($path) ? (string) filemtime($path) : null
	);
}
add_action('wp_enqueue_scripts', 'bandupev_enqueue_flag_icons');

function bandupev_enqueue_frontend_js() {
	$rel  = '../assets/js/frontend.js';
	$path = plugin_dir_path(__FILE__) . $rel;
	$url  = plugin_dir_url(__FILE__)  . $rel;

	$ver = file_exists($path) ? (string) filemtime($path) : ( defined('BANDUPEV_VERSION') ? BANDUPEV_VERSION : null );
	wp_enqueue_script( 'bandupev-frontend-js', $url, array(), $ver, true );
}
add_action('wp_enqueue_scripts', 'bandupev_enqueue_frontend_js');
