<?php
/**
 * Register Latest Post Via rest API, so another website can scrap latest post.
 *
 * @package wpmedia
 */

/**
 * Register Rest Route
 *
 * Example link https://domain.com/wp-json/wpmedia/v1/get-posts
 */
add_action(
	'rest_api_init',
	function() {
		/* @link https://developer.wordpress.org/reference/functions/register_rest_route/ */
		register_rest_route(
			'wpmedia/v1',
			'/get-posts/',
			array(
				'methods'             => 'GET',
				'callback'            => 'wpmedia_restapi_recentposts',
				'permission_callback' => '__return_true',
			)
		);
	}
);


/**
 * Rest Results
 *
 * @param string $request request param.
 */
function wpmedia_restapi_recentposts( $request ) {
	$parameters = $request->get_query_params();

	// Default 6 items.
	$number = isset( $parameters['number'] ) ? (int) $parameters['number'] : 6;
	// Max 20 items.
	if ( $number > 20 ) {
		$number = 20;
	}

	// Category.
	$catids = isset( $parameters['categories'] ) ? array_map( 'absint', $parameters['categories'] ) : array( 0 );
	if ( in_array( 0, $catids, true ) ) {
		$catids = array( 0 );
	}

	// Tags.
	$tagids = isset( $parameters['tags'] ) ? array_map( 'absint', $parameters['tags'] ) : array( 0 );
	if ( in_array( 0, $tagids, true ) ) {
		$tagids = array( 0 );
	}

	$apijson = get_theme_mod( 'gmr_api-customjson', '' );
	$keyjson = isset( $parameters['key'] ) ? esc_html( $parameters['key'] ) : '';

	// Latest post.
	$args = array(
		'orderby'                => 'date',
		'order'                  => 'DESC',
		'posts_per_page'         => (int) $number,
		'post_type'              => 'post',
		'post_status'            => 'publish',
		'ignore_sticky_posts'    => true,
		'update_post_term_cache' => false,
		'update_post_meta_cache' => false,
		'cache_results'          => false,
		'no_found_rows'          => true,
		'fields'                 => 'ids',
	);

		// add categories param only if 'all categories' was not selected.
	if ( ! in_array( 0, $catids, true ) ) {
		$args['category__in'] = $catids;
	}

		// Add tag option.
	if ( ! in_array( 0, $tagids, true ) ) {
		$args['tag__in'] = $tagids;
	}

	$query = new \WP_Query( $args );

	$items    = array();
	$allitems = array();

	if ( $query->have_posts() ) {
		while ( $query->have_posts() ) {
			$query->the_post();
			// Title.
			$items['title'] = esc_html( get_the_title() );
			// Date.
			$items['date'] = wpmedia_posted_on( false );
			// Excerpt.
			$items['excerpt'] = esc_html( get_the_excerpt() );
			// Permalink.
			$items['url'] = esc_url( get_permalink() );
			// Image Thumb.
			$items['imagethumbnail'] = get_the_post_thumbnail(
				get_the_ID(),
				'thumbnail',
				array(
					'alt' => the_title_attribute(
						array(
							'echo' => false,
						)
					),
				)
			);
			// Image Medium.
			$items['imagemedium'] = get_the_post_thumbnail(
				get_the_ID(),
				'medium',
				array(
					'alt' => the_title_attribute(
						array(
							'echo' => false,
						)
					),
				)
			);
			// Image Medium Large.
			$items['imagemediumlarge'] = get_the_post_thumbnail(
				get_the_ID(),
				'medium_large',
				array(
					'alt' => the_title_attribute(
						array(
							'echo' => false,
						)
					),
				)
			);
			// Image Large.
			$items['imagelarge'] = get_the_post_thumbnail(
				get_the_ID(),
				'large',
				array(
					'alt' => the_title_attribute(
						array(
							'echo' => false,
						)
					),
				)
			);
			// Get Categories.
			$items['categories'] = wpmedia_category( get_the_ID(), false );
			// Get Post Format.
			$items['post_format'] = wpmedia_postformat_thumbnails( false );
			// All items.
			$allitems[] = $items;
		}
		wp_reset_postdata();
	}
	$data = array(
		'success' => false,
	);
	if ( isset( $keyjson ) && ! empty( $keyjson ) ) {
		if ( $apijson === $keyjson ) {
			$data = array(
				'success' => true,
				'items'   => $allitems,
			);
		}
	}

	return $data;

}
