<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound

// Don't load directly
if (!defined('ABSPATH')) { exit; }

// Require object
if (empty($ics_data)) { return false; }

global $R34ICS;

$start_of_week = get_option('start_of_week', 0);

$date_format = r34ics_date_format((!empty($args['format']) ? $args['format'] : (get_locale() == 'en_US' ? 'D M j' : 'D j M')), true);

$ics_calendar_classes = apply_filters('r34ics_calendar_classes', array(
	'masonry_grouping_' . ($args['masonry_grouping'] ?? ''),
), $args, true);

// Feed colors custom CSS
if (!empty($ics_data['colors'])) {
	r34ics_feed_colors_css($ics_data, true);
}

// Prepare event details toggle lightbox
if ($args['toggle'] === 'lightbox') {
	r34ics_lightbox_container();
}
?>

<section class="<?php echo esc_attr($ics_calendar_classes); ?>" id="<?php echo esc_attr($ics_data['guid']); ?>" style="opacity: 0;">

	<?php
	// Title and description
	if (!empty($ics_data['title'])) {
		?>
		<<?php echo esc_attr($args['htmltagtitle']); ?> class="ics-calendar-title"><?php echo wp_kses_post($ics_data['title']); ?></<?php echo esc_attr($args['htmltagtitle']); ?>>
		<?php
	}
	if (!empty($ics_data['description'])) {
		?>
		<p class="ics-calendar-description"><?php echo wp_kses_post($ics_data['description']); ?></p>
		<?php
	}
	
	// Empty calendar message
	if (empty($ics_data['events']) || r34ics_is_empty_array($ics_data['events'])) {
		?>
		<p class="ics-calendar-error"><?php esc_html_e('No events found.', 'ics-calendar-pro'); ?></p>
		<?php
	}
	
	// Display calendar
	else {

		// Actions before rendering calendar wrapper (can include additional template output)
		do_action('r34ics_display_calendar_before_wrapper', $view, $args, $ics_data);

		// Color code key
		if (!empty(trim(@$args['color'], '|')) && (empty($args['legendposition']) || $args['legendposition'] == 'above')) {
			echo wp_kses(($R34ICS->color_key_html($args, $ics_data, true) ?: ''), r34ics_color_key_allowed());
		}
		
		?>
		<div class="ics-calendar-masonry-grid">
			<div class="ics-calendar-masonry-grid-sizer"></div>

			<?php
			// Build monthly calendars
			$i = 0;
			$skip_i = 0;
			$multiday_events_used = array();
			$years = $ics_data['events'];

			foreach ((array)$years as $year => $months) {

				foreach ((array)$months as $month => $days) {
					$ym = $year . $month;
				
					// Is this month in range? If not, skip to the next
					if (!r34ics_month_in_range($ym, $ics_data)) { continue; }
				
					$m = intval($month);
					$month_uid = $ics_data['guid'] . '-' . $ym;
								
					// Build month's calendar
					if (isset($days)) {

						foreach ((array)$days as $day => $day_events) {

							// Pull out multiday events and display them separately first
							// Multiday events need to be their own tiles even if using masonry_grouping = date
							foreach ((array)$day_events as $time => $events) {

								foreach ((array)$events as $event_key => $event) {

									// We're ONLY looking for multiday events right now
									if (empty($event['multiday'])) { continue; }

									// Give this instance its own unique ID, since multiple instances of a recurring event will have the same UID
									$multiday_instance_uid = $event['uid'] . '-' . $event['multiday']['start_date'];

									// Skip event if under the skip limit (but be sure to count it in $multiday_events_used!) 
									if (!empty($args['skip']) && $skip_i < $args['skip']) {
										if (!in_array($multiday_instance_uid, $multiday_events_used)) {
											$multiday_events_used[] = $multiday_instance_uid;
											$skip_i++;
										}
										continue;
									}

									// Have we used this event yet?
									if (!in_array($multiday_instance_uid, $multiday_events_used)) {

										// Format date/time for header
										/*
										Version 9.6.5.1 revises the change from version 9.6.3.2:
										Restructured into MM/DD/YYYY format because, for an unknown reason,
										both wp_date() and r34ics_date() are shifting these back by 1 day if
										in YYYYMMDD format.
										*/
										$md_start = !empty($event['multiday']['start_date'])
											? r34ics_date($date_format,
												substr($event['multiday']['start_date'],4,2) . '/' .
												substr($event['multiday']['start_date'],6,2) . '/' .
												substr($event['multiday']['start_date'],0,4)
											)
											: '';
										$md_end = !empty($event['multiday']['end_date'])
											? r34ics_date($date_format,
												substr($event['multiday']['end_date'],4,2) . '/' .
												substr($event['multiday']['end_date'],6,2) . '/' .
												substr($event['multiday']['end_date'],0,4)
											)
											: '';
										if ($time != 'all-day') {
											$md_start .= ' <small class="time-inline">' . r34ics_time_format($event['multiday']['start_time'], $args['timeformat'], $event['tz_start'], $event['multiday']['start_date']) . '</small>';
											$md_end .= ' <small class="time-inline">' . r34ics_time_format($event['multiday']['end_time'], $args['timeformat'], $event['tz_end'], $event['multiday']['end_date']) . '</small>';
										}
									
										$day_label = $md_start . ' &#8211; ' . $md_end;
										$day_uid = $ics_data['guid'] . '-' . r34ics_uid();

										$has_desc = r34ics_has_desc($args, $event);
									
										// We're grouping by event
										if (empty($args['masonry_grouping']) || $args['masonry_grouping'] == 'event') {
											?>
											<article class="ics-calendar-masonry-grid-item <?php echo esc_attr(r34ics_event_css_classes($event, $time, $args)); ?>" data-feed-key="<?php echo intval($event['feed_key']); ?>"<?php
												if (!empty($ics_data['colors'][$event['feed_key']]['base'])) { echo ' data-feed-color="' . esc_attr($ics_data['colors'][$event['feed_key']]['base']) . '"'; }
												if (!empty($event['categories'])) { echo ' data-categories="' . esc_attr($event['categories']) . '"'; }
												if (!empty($event['color'])) { echo ' data-color="' . esc_attr($event['color']) . '"'; }
											?>>
												<div class="ics-calendar-date" id="<?php echo esc_attr($day_uid); ?>"><?php echo wp_kses_post($day_label); ?></div>
											<?php
										}
										// We're grouping by date
										else {
											?>
											<article class="ics-calendar-masonry-grid-item">
												<div class="ics-calendar-date" id="<?php echo esc_attr($day_uid); ?>"><?php echo wp_kses_post($day_label); ?></div>
												<div class="ics-calendar-masonry-grid-item-event <?php echo esc_attr(r34ics_event_css_classes($event, $time, $args)); ?>" data-feed-key="<?php echo intval($event['feed_key']); ?>"<?php
												if (!empty($ics_data['colors'][$event['feed_key']]['base'])) { echo ' data-feed-color="' . esc_attr($ics_data['colors'][$event['feed_key']]['base']) . '"'; }
												if (!empty($event['categories'])) { echo ' data-categories="' . esc_attr($event['categories']) . '"'; }
												if (!empty($event['color'])) { echo ' data-color="' . esc_attr($event['color']) . '"'; }
											?>>
											<?php
										}
										// Event label (title)
										echo wp_kses_post($R34ICS->event_label_html($args, $event, (!empty($has_desc) ? array('has_desc') : null)));
	
										// Sub-label
										echo wp_kses_post($R34ICS->event_sublabel_html($args, $event, null));
	
										// Description/Location/Organizer
										echo wp_kses_post($R34ICS->event_description_html($args, $event, null, $has_desc));
										
										// We're grouping by date
										if (!empty($args['masonry_grouping']) && $args['masonry_grouping'] == 'date') {
											?>
											</div>
											<?php
										}
										?>
										</article>
										<?php
									
										// We've now used this event
										$multiday_events_used[] = $multiday_instance_uid;
										$i++;
										if (!empty($args['count']) && $i >= intval($args['count'])) {
											echo '</dl></div></article>';
											break(5);
										}
									}

									// Remove event from array (to skip day if it only has multiday events)
									unset($day_events[$time][$event_key]);

								}

								// Remove time from array if all of its events have been removed
								if (empty($day_events[$time])) { unset($day_events[$time]); }

							}
						
							// Skip day if all of its events were multiday
							if (empty($day_events)) { continue; }
						
							// Loop through day events
							$all_day_indicator_shown = !empty($args['hidealldayindicator']);

							// Assign day label and guid
							$day_label = r34ics_date($date_format, $month.'/'.$day.'/'.$year);
							$day_uid = $ics_data['guid'] . '-' . $year . $month . $day;
							
							// We're grouping by date
							if (!empty($args['masonry_grouping']) && $args['masonry_grouping'] == 'date') {
								?>
								<article class="ics-calendar-masonry-grid-item">
									<div class="ics-calendar-date" id="<?php echo esc_attr($day_uid); ?>"><?php echo wp_kses_post($day_label); ?></div>
								<?php
							}
							
							foreach ((array)$day_events as $time => $events) {
								foreach ((array)$events as $event) {

									// We're NOT looking for multiday events right now (these should all be removed above already)
									if (!empty($event['multiday'])) { continue; }

									// Skip event if under the skip limit
									if (!empty($args['skip']) && $skip_i < $args['skip']) {
										$skip_i++; continue;
									}

									$has_desc = r34ics_has_desc($args, $event);
									
									// We're grouping by event
									if (empty($args['masonry_grouping']) || $args['masonry_grouping'] == 'event') {
										?>
										<article class="ics-calendar-masonry-grid-item <?php echo esc_attr(r34ics_event_css_classes($event, $time, $args)); ?>" data-feed-key="<?php echo intval($event['feed_key']); ?>"<?php
											if (!empty($ics_data['colors'][$event['feed_key']]['base'])) { echo ' data-feed-color="' . esc_attr($ics_data['colors'][$event['feed_key']]['base']) . '"'; }
											if (!empty($event['categories'])) { echo ' data-categories="' . esc_attr($event['categories']) . '"'; }
											if (!empty($event['color'])) { echo ' data-color="' . esc_attr($event['color']) . '"'; }
										?>>
											<div class="ics-calendar-date" id="<?php echo esc_attr($day_uid); ?>"><?php echo wp_kses_post($day_label); ?></div>
										<?php
									}
									// We're grouping by date
									else {
										?>
										<div class="ics-calendar-masonry-grid-item-event <?php echo esc_attr(r34ics_event_css_classes($event, $time, $args)); ?>" data-feed-key="<?php echo intval($event['feed_key']); ?>"<?php
											if (!empty($ics_data['colors'][$event['feed_key']]['base'])) { echo ' data-feed-color="' . esc_attr($ics_data['colors'][$event['feed_key']]['base']) . '"'; }
											if (!empty($event['categories'])) { echo ' data-categories="' . esc_attr($event['categories']) . '"'; }
											if (!empty($event['color'])) { echo ' data-color="' . esc_attr($event['color']) . '"'; }
										?>>
										<?php
									}
									
									if ($time != 'all-day' && empty($args['hidetimes']) && !empty($event['start'])) {
										?>
										<div class="time" data-feed-key="<?php echo intval($event['feed_key']); ?>"<?php
											if (!empty($event['categories'])) { echo ' data-categories="' . esc_attr($event['categories']) . '"'; }
											if (!empty($event['color'])) { echo ' data-color="' . esc_attr($event['color']) . '"'; }
										?>>
											<?php
											echo wp_kses_post($event['start']);
											if (!empty($event['end']) && $event['end'] != $event['start']) {
												if (empty($args['showendtimes'])) {
													?>
													<span class="end_time show_on_hover">&#8211; <?php echo wp_kses_post($event['end']); ?></span>
													<?php
												}
												else {
													?>
													<span class="end_time">&#8211; <?php echo wp_kses_post($event['end']); ?></span>
													<?php
												}
											}
											?>
										</div>
										<?php
									}
									
									// Event label (title)
									echo wp_kses_post($R34ICS->event_label_html($args, $event, (!empty($has_desc) ? array('has_desc') : null)));

									// Sub-label
									echo wp_kses_post($R34ICS->event_sublabel_html($args, $event, null));

									// Description/Location/Organizer
									echo wp_kses_post($R34ICS->event_description_html($args, $event, null, $has_desc));

									// We're grouping by event
									if (empty($args['masonry_grouping']) || $args['masonry_grouping'] == 'event') {
										?>
										</article>
										<?php
									}
									// We're grouping by date
									else {
										?>
										</div>
										<?php
									}

									$i++;
									if (!empty($args['count']) && $i >= intval($args['count'])) {
										break(5);
									}
								}
							}
							
							// We're grouping by date
							if (!empty($args['masonry_grouping']) && $args['masonry_grouping'] == 'date') {
								?>
								</article>
								<?php
							}

						}
					}
				}
			}
			?>
		
		</div><!-- .ics-calendar-masonry-grid -->
		
		<?php
		// Color code key
		if (!empty(trim(@$args['color'], '|')) && !empty($args['legendposition']) && $args['legendposition'] == 'below') {
			echo wp_kses(($R34ICS->color_key_html($args, $ics_data, true) ?: ''), r34ics_color_key_allowed());
		}
	
		// Actions after rendering calendar wrapper (can include additional template output)
		do_action('r34ics_display_calendar_after_wrapper', $view, $args, $ics_data);

	}
	?>

</section>
