<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

class Builder_Mosaic_Event_Posts extends Builder_Mosaic_Provider {

	public static function is_available():bool {
		return class_exists( 'Themify_Event_Post',false );
	}

	public static function get_items(array &$settings,int $limit,int $paged ):array {
		if ( ! function_exists( 'themify_event_post_parse_query' ) ) {
			return ['error'=>__( 'Please update the Event Post plugin to latest version.', 'builder-mosaic' )];
		}
		$settings+=array(
			'tep_show' => 'mix',
			'tep_category' => 0,
			'tep_offset' => 0,
			'tep_order' => 'desc',
			'tep_orderby' => 'event_date',
		);


		$args = themify_event_post_parse_query( array(
			'show' => $settings['tep_show'],
			'limit' => $limit,
			'offset' => $settings['tep_offset'],
			'category' => preg_replace( '/\|[multiple|single]*$/', '', $settings['tep_category'] ),
			'order' => $settings['tep_order'],
		) );

		if ( $paged > 1 ) {
			$args['offset'] = ( ( $paged - 1 ) * $limit ) + $settings['tep_offset'];
		}
		$query = new WP_Query( $args );
		$items = array();
		if ( $query->have_posts() ) {
			if(isset(Themify_Builder::$is_loop)){
				$isLoop=Themify_Builder::$is_loop;
				Themify_Builder::$is_loop=true;
			}
			else{//backward
				global $ThemifyBuilder;
				$isLoop = $ThemifyBuilder->in_the_loop === true;
				$ThemifyBuilder->in_the_loop = true;
			}
			global $post;
			if ( is_object( $post ) ){
				$saved_post = clone $post;
			}
			while ( $query->have_posts() ) {
				$query->the_post();

				ob_start();
				themify_event_post_date();
				$event_date = ob_get_clean();

				$items[] = array(
					'title' => get_the_title(),
					'image' => has_post_thumbnail() ? get_the_post_thumbnail_url( get_the_id(), 'full' ) : '',
					'text' => '<p>'. $event_date. get_the_excerpt(). '</p>',
					'link' => get_permalink(),
					'css_classes' => str_replace( 'post ', '', join( ' ', get_post_class() ) ),
				);
			}
			if ( isset( $saved_post ) ) {
				$post = $saved_post;
				setup_postdata( $saved_post );
				unset($saved_post);
			}
			if(isset(Themify_Builder::$is_loop)){
				Themify_Builder::$is_loop=$isLoop;
			}
			else{//backward
				$ThemifyBuilder->in_the_loop = $isLoop;
			}
		}
		return array(
			'items' => $items,
			'total_items' => $query->found_posts,
		);
	}
}