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

class Builder_Mosaic_Posts extends Builder_Mosaic_Provider {

	protected static function init():void{
		add_action( 'template_redirect', array( __CLASS__, 'post_lightbox_init' ), 100 );
	}

	public static function get_items(array &$settings,int $limit,int $paged ):array {

		$settings+=array(
			'post_type_post' => 'post',
			'term_type' => 'category',
			'tax' => 'category',
			'post_slug' => '',
			'offset' => '',
			'order' => 'desc',
			'orderby' => 'date',
			'lightbox_link' => '',
			'lightbox_width' => '',
			'lightbox_height' => '',
			'lightbox_width_unit' => 'px',
			'lightbox_height_unit' => 'px',
			'tax_category' => '0',
		);
		$args = array(
			'post_type' => $settings['post_type_post'],
			'post_status' => 'publish',
			'posts_per_page' => $limit,
			'order' => $settings['order'],
			'orderby' => $settings['orderby'],
			'paged' => $paged,
			'ignore_sticky_posts' => true,
		);
		if ( $settings['offset'] !== '' ) {
			$args['offset'] = ( ( $paged - 1 ) * $limit ) + $settings['offset'];
		}
		if ( $settings['term_type'] === 'post_slug' ) {
			if ( $settings['post_slug'] !== '' ) {
				$args['post__in'] = Themify_Builder_Model::parse_slug_to_ids( $settings['post_slug'], $settings['post_type'] );
			}
		} elseif($settings['term_type'] !== 'all') {
			$terms = isset( $settings["tax_{$settings['tax']}"] ) ? $settings["tax_{$settings['tax']}"] : ( isset($settings['tax_category'] ) ? $settings['tax_category'] : false );
			if ( $terms === false ) {
			    return ['error'=>__('No term has been specified.', 'builder-mosaic' )];
			}
			Themify_Builder_Model::parseTermsQuery( $args, $terms, $settings['tax'] );
		}

		if ( method_exists( 'Themify_Builder_Model', 'parse_query_filter' ) ) {
			Themify_Builder_Model::parse_query_filter( $settings, $args );
		}
		
		$query = new WP_Query( apply_filters( 'themify_builder_mosaic_query', $args, $settings ) );
		
		$items = array();
		if ( $query->have_posts() ) {
			global $post;
			if ( is_object( $post ) ){
				$saved_post = clone $post;
			}
			add_filter( 'excerpt_length', array( __CLASS__, 'excerpt_length' ), 999 );
			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;
			}
			while ( $query->have_posts() ) {
				$query->the_post();
				$url = self::get_permalink();
				$lightbox_size = '';
				if ( $settings['lightbox_link']==='1' ) {
					$url = add_query_arg( array( 'tb-mosaic-lightbox' => 1 ), $url );
					if ( ! empty( $settings['lightbox_width'] ) || ! empty( $settings['lightbox_height'] ) ) {
						$lightbox_size = sprintf( '%s|%s', $settings['lightbox_width'] .  $settings['lightbox_width_unit'], $settings['lightbox_height'] .  $settings['lightbox_height_unit'] );
					}
				}
				$items[] = array(
					'title' => get_the_title(),
					'image' => has_post_thumbnail() ? get_the_post_thumbnail_url( get_the_id(), 'full' ) : '',
					'text' => '<p>' . get_the_excerpt() . '</p>',
					'link' => $url,
					'css_classes' => str_replace( 'post ', '', implode( ' ', get_post_class() ) ),
					'link_lightbox' => $settings['lightbox_link']==='1',
					'lightbox_size' => $lightbox_size,
					'badge' => ( $categories = get_the_category() ) ? $categories[0]->name : '',
				);
			}
			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;
			}
			remove_filter( 'excerpt_length', array( __CLASS__, 'excerpt_length' ), 999 );
		}

		return array(
			'items' => $items,
			'total_items' => $query->found_posts - (int) $settings['offset'],
		);
	}

	/**
	 * Sets the excerpt length, high priority to ensure content is not trimmed by external sources.
	 */
	public static function excerpt_length():int {
		return 100;
	}

	/**
	 * Returns the post permalink.
	 * in Themify themes, if External Link custom field is used, that URL will be used instead.
	 */
	public static function get_permalink():string {
		$url = function_exists( 'themify_get' )?themify_get( 'external_link', '' ):'';
		return $url!==''?$url:get_permalink();
	}


	/**
	 * Handle display of single post lightbox
	 *
	 * @hook to template_redirect
	 */
	public static function post_lightbox_init():void {
		if ( self::is_lightbox() && is_singular() ) {
			show_admin_bar( false );
			add_filter( 'body_class', array( __CLASS__, 'lightbox_body_class' ) );
			add_filter( 'template_include', array( __CLASS__, 'template_include' ), 100 );
			add_action( 'wp_enqueue_scripts', array( __CLASS__, 'wp_enqueue_scripts' ), 100 );
		}
	}

	/**
	 * Template to display in the lightbox window
	 *
	 * @return string
	 */
	public static function template_include(?string $file ):string {
		return __DIR__ . '/templates/post-lightbox.php';
	}

	/**
	 * Adds stylesheet for single post lightbox
	 */
	public static function wp_enqueue_scripts():void {
		wp_enqueue_style( 'tb_mosaic_lightbox', trailingslashit( plugin_dir_url( __FILE__ ) ) . 'assets/tbp-post-lightbox.min.css',null,Builder_Mosaic::get_version() );
	}

	/**
	 * Adds a unique classname to <body> when page is displayed inside lightbox
	 *
	 * @return array
	 */
	public static function lightbox_body_class(array $classes ):array {
		$classes[] = 'tb_mosaic_lightbox';

		return $classes;
	}
}