<?php
/**
 * Instance helpers.
 *
 * @package    EventKoi
 * @subpackage EventKoi\Helpers
 */

use EKLIB\StellarWP\DB\DB;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! function_exists( 'eventkoi_get_instance_override' ) ) {
	/**
	 * Get override data for a specific instance timestamp.
	 *
	 * @param int $event_id Event post ID.
	 * @param int $timestamp Instance start timestamp.
	 *
	 * @return array|null Array of overrides or null.
	 */
	function eventkoi_get_instance_override( $event_id, $timestamp ) {
		$row = DB::table( 'eventkoi_recurrence_overrides' )
		         ->where( 'event_id', $event_id )
		         ->where( 'timestamp', $timestamp )
		         ->get();

		return $row ? maybe_unserialize( $row->data ) : null;
	}
}

if ( ! function_exists( 'eventkoi_merge_instance_data' ) ) {
	/**
	 * Merge event data with instance override.
	 *
	 * @param array $event_data Raw event array.
	 * @param array $override Override array.
	 *
	 * @return array Merged data.
	 */
	function eventkoi_merge_instance_data( $event_data, $override ) {
		foreach ( $override as $key => $value ) {
			if ( null !== $value ) {
				$event_data[ $key ] = $value;
			}
		}

		return $event_data;
	}
}

if ( ! function_exists( 'eventkoi_get_template_ids_by_pattern' ) ) {
	/**
	 * Return template ids by pattern or conditional logic
	 *
	 * @param $pattern
	 *
	 * @return array
	 */
	function eventkoi_get_template_ids_by_pattern( $pattern = 'include/singular' ): array {

		$results   = array();
		$templates = get_posts(
			array(
				'post_type'      => 'elementor_library',
				'posts_per_page' => - 1,
				'post_status'    => 'publish',
				'meta_query'     => array(
					array(
						'key'     => '_elementor_conditions',
						'compare' => 'EXISTS',
					),
				),
			)
		);

		foreach ( $templates as $template ) {
			$conditions = get_post_meta( $template->ID, '_elementor_conditions', true );

			if ( ! empty( $conditions ) ) {
				foreach ( $conditions as $condition ) {
					if ( strpos( $condition, $pattern ) !== false ) {
						$results[] = array(
							'slug'  => $template->post_name,
							'title' => $template->post_title,
						);
						break;
					}
				}
			}
		}

		return $results;
	}
}

if ( ! function_exists( 'eventkoi_get_calendar_options' ) ) {
	/**
	 * Get calendar options
	 *
	 * @return array
	 */
	function eventkoi_get_calendar_options() {
		$options = array( '' => __( 'Select a calendar', 'eventkoi-lite' ) );
		$terms   = get_terms(
			array(
				'taxonomy'   => 'event_cal',
				'hide_empty' => false,
			)
		);

		if ( ! is_wp_error( $terms ) ) {
			foreach ( $terms as $term ) {
				$options[ (string) $term->term_id ] = eventkoi_decode_term_name( $term->name );
			}
		}

		return $options;
	}
}

if ( ! function_exists( 'eventkoi_get_month_options' ) ) {
	/**
	 * Get month options
	 *
	 * @return array
	 */
	function eventkoi_get_month_options() {
		return array(
			'current'   => __( 'Current month', 'eventkoi-lite' ),
			'january'   => __( 'January', 'eventkoi-lite' ),
			'february'  => __( 'February', 'eventkoi-lite' ),
			'march'     => __( 'March', 'eventkoi-lite' ),
			'april'     => __( 'April', 'eventkoi-lite' ),
			'may'       => __( 'May', 'eventkoi-lite' ),
			'june'      => __( 'June', 'eventkoi-lite' ),
			'july'      => __( 'July', 'eventkoi-lite' ),
			'august'    => __( 'August', 'eventkoi-lite' ),
			'september' => __( 'September', 'eventkoi-lite' ),
			'october'   => __( 'October', 'eventkoi-lite' ),
			'november'  => __( 'November', 'eventkoi-lite' ),
			'december'  => __( 'December', 'eventkoi-lite' ),
		);
	}
}

if ( ! function_exists( 'eventkoi_get_weekday_options' ) ) {
	/**
	 * Get weekday options
	 *
	 * @return array
	 */
	function eventkoi_get_weekday_options() {
		return array(
			'monday'    => __( 'Monday', 'eventkoi-lite' ),
			'tuesday'   => __( 'Tuesday', 'eventkoi-lite' ),
			'wednesday' => __( 'Wednesday', 'eventkoi-lite' ),
			'thursday'  => __( 'Thursday', 'eventkoi-lite' ),
			'friday'    => __( 'Friday', 'eventkoi-lite' ),
			'saturday'  => __( 'Saturday', 'eventkoi-lite' ),
			'sunday'    => __( 'Sunday', 'eventkoi-lite' ),
		);
	}
}

if ( ! function_exists( 'eventkoi_sanitize_calendar_selection' ) ) {
	/**
	 * Sanitize calendar selection
	 *
	 * @param mixed $calendars Calendar selection.
	 *
	 * @return array
	 */
	function eventkoi_sanitize_calendar_selection( $calendars ) {
		if ( empty( $calendars ) ) {
			return array();
		}

		if ( is_string( $calendars ) ) {
			$calendars = trim( $calendars );

			// Support comma-delimited values (e.g. "2,5,9") from UI controls.
			if ( false !== strpos( $calendars, ',' ) ) {
				return array_values(
					array_filter(
						array_map( 'absint', array_map( 'trim', explode( ',', $calendars ) ) )
					)
				);
			}

			$id = absint( $calendars );
			return $id > 0 ? array( $id ) : array();
		}

		if ( is_array( $calendars ) ) {
			return array_values(
				array_filter(
					array_map( 'absint', $calendars )
				)
			);
		}

		return array();
	}
}

if ( ! function_exists( 'eventkoi_sanitize_week_start' ) ) {
	/**
	 * Sanitize week start
	 *
	 * @param mixed $value Week start.
	 *
	 * @return string
	 */
	function eventkoi_sanitize_week_start( $value ) {
		$value   = strtolower( (string) $value );
		$options = array( 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' );

		return in_array( $value, $options, true ) ? $value : 'monday';
	}
}

if ( ! function_exists( 'eventkoi_sanitize_timeframe' ) ) {
	/**
	 * Sanitize timeframe
	 *
	 * @param mixed $value Timeframe.
	 *
	 * @return string
	 */
	function eventkoi_sanitize_timeframe( $value ) {
		$value = strtolower( (string) $value );

		return in_array( $value, array( 'month', 'week' ), true ) ? $value : 'month';
	}
}

if ( ! function_exists( 'eventkoi_normalize_default_month' ) ) {
	/**
	 * Normalize default month
	 *
	 * @param mixed $value Default month.
	 *
	 * @return string
	 */
	function eventkoi_normalize_default_month( $value ) {
		$value = strtolower( (string) $value );

		if ( 'current' === $value || empty( $value ) ) {
			return '';
		}

		$options = array( 'current', 'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december' );

		return in_array( $value, $options, true ) ? $value : '';
	}
}

if ( ! function_exists( 'eventkoi_normalize_default_year' ) ) {
	/**
	 * Normalize default year
	 *
	 * @param mixed $value Default year.
	 *
	 * @return string
	 */
	function eventkoi_normalize_default_year( $value ) {
		$value = trim( (string) $value );

		if ( empty( $value ) ) {
			return '';
		}

		return preg_match( '/^\d{4}$/', $value ) ? $value : '';
	}
}

if ( ! function_exists( 'eventkoi_get_events' ) ) {
	/**
	 * Get all events
	 *
	 * @return array
	 */
	function eventkoi_get_events() {
		$options    = array();
		$all_events = get_posts(
			array(
				'post_type'      => 'eventkoi_event',
				'posts_per_page' => - 1,
				'post_status'    => 'publish',
			)
		);

		if ( is_wp_error( $all_events ) ) {
			return $options;
		}

		foreach ( $all_events as $event_post ) {
			$options[ (string) $event_post->ID ] = $event_post->post_title;
		}

		return $options;
	}
}

if ( ! function_exists( 'eventkoi_get_event_data_options' ) ) {
	/**
	 * Get available event data options.
	 *
	 * @return array
	 */
	function eventkoi_get_event_data_options() {
		return array(
			'event_title'                 => __( 'Event Title', 'eventkoi-lite' ),
			'event_details'               => __( 'Event Details', 'eventkoi-lite' ),
			'event_timezone'              => __( 'Event Timezone', 'eventkoi-lite' ),
			'event_gmap'                  => __( 'Event Google Map', 'eventkoi-lite' ),
			'event_image'                 => __( 'Event Image', 'eventkoi-lite' ),
			'event_image_url'             => __( 'Event Image URL', 'eventkoi-lite' ),
			'event_calendar_url'          => __( 'Event Calendar URL', 'eventkoi-lite' ),
			'event_calendar'              => __( 'Event Calendar', 'eventkoi-lite' ),
			'event_calendar_link'         => __( 'Event Calendar Link', 'eventkoi-lite' ),
			'event_location'              => __( 'Event Location', 'eventkoi-lite' ),
			'event_location_name'         => __( 'Event Location Name', 'eventkoi-lite' ),
			'event_location_address'      => __( 'Event Location Address', 'eventkoi-lite' ),
			'event_location_unit'         => __( 'Event Location Apartment/Unit', 'eventkoi-lite' ),
			'event_location_city'         => __( 'Event Location City', 'eventkoi-lite' ),
			'event_location_state'        => __( 'Event Location State', 'eventkoi-lite' ),
			'event_location_country'      => __( 'Event Location Country', 'eventkoi-lite' ),
			'event_location_zip'          => __( 'Event Location Post Code', 'eventkoi-lite' ),
			'event_datetime_with_summary' => __( 'Event Datetime with Summary', 'eventkoi-lite' ),
			'event_datetime'              => __( 'Event Datetime', 'eventkoi-lite' ),
			'event_date'                  => __( 'Event Date', 'eventkoi-lite' ),
			'event_time'                  => __( 'Event Time', 'eventkoi-lite' ),
			'event_date_type'             => __( 'Event Date Type', 'eventkoi-lite' ),
			'event_rulesummary'           => __( 'Event Rule Summary', 'eventkoi-lite' ),
			'event_capacity'              => __( 'Event Capacity', 'eventkoi-lite' ),
			'event_capacity_remaining'    => __( 'Event Capacity Remaining', 'eventkoi-lite' ),
			'event_capacity_sold'         => __( 'Event Capacity Sold', 'eventkoi-lite' ),
			'event_sold_out'              => __( 'Event Sold Out', 'eventkoi-lite' ),
			'event_low_stock'             => __( 'Event Low Stock', 'eventkoi-lite' ),
			'event_ticket_count'          => __( 'Event Ticket Count', 'eventkoi-lite' ),
			'event_ticket_summary'        => __( 'Event Ticket Summary', 'eventkoi-lite' ),
			'event_sales_start'           => __( 'Event Sales Start', 'eventkoi-lite' ),
			'event_sales_end'             => __( 'Event Sales End', 'eventkoi-lite' ),
			'event_ticket_price_from'     => __( 'Event Ticket Price From', 'eventkoi-lite' ),
			'event_ticket_price_to'       => __( 'Event Ticket Price To', 'eventkoi-lite' ),
			'event_ticket_price_range'    => __( 'Event Ticket Price Range', 'eventkoi-lite' ),
			'event_date_year'             => __( 'Event Date Year', 'eventkoi-lite' ),
			'event_date_month'            => __( 'Event Date Month', 'eventkoi-lite' ),
			'event_date_month_short'      => __( 'Event Date Month Short', 'eventkoi-lite' ),
			'event_date_day'              => __( 'Event Date Day', 'eventkoi-lite' ),
			'event_date_day_name'         => __( 'Event Date Day Name', 'eventkoi-lite' ),
			'event_date_iso'              => __( 'Event Date ISO', 'eventkoi-lite' ),
			'event_rsvp_capacity'         => __( 'Event RSVP Capacity', 'eventkoi-lite' ),
			'event_rsvp_remaining'        => __( 'Event RSVP Remaining', 'eventkoi-lite' ),
			'event_rsvp_going'            => __( 'Event RSVP Going', 'eventkoi-lite' ),
			'event_rsvp_full'             => __( 'Event RSVP Full', 'eventkoi-lite' ),
		);
	}
}

if ( ! function_exists( 'eventkoi_get_default_event_data_items' ) ) {
	/**
	 * Get default event data items for the repeater.
	 *
	 * @return array
	 */
	function eventkoi_get_default_event_data_items() {
		return array(
			array(
				'data_type' => 'event_title',
				'show'      => 'yes',
			),
			array(
				'data_type' => 'event_datetime',
				'show'      => 'yes',
			),
			array(
				'data_type' => 'event_location',
				'show'      => 'yes',
			),
			array(
				'data_type' => 'event_details',
				'show'      => 'yes',
			),
		);
	}
}
