<?php

namespace Limb_Chatbot\Includes\Repositories;

use Limb_Chatbot\Includes\Data_Objects\Wp_Object;
use Limb_Chatbot\Includes\Services\Data_Object_Collection;
use WP_Query;

class Wp_Post_Object_Repository extends Wp_Object_Repository {

	/**
	 * Fetch the posts objects
	 *
	 * @param $group_name
	 * @param $search_term
	 * @param $per_page
	 * @param $page
	 *
	 * @return Data_Object_Collection
	 */
	public function get_items( $group_name, $search_term, $per_page, $page ): Data_Object_Collection {
		$paged_posts_args = [
			'post_type'      => $group_name,
			'post_status'    => 'publish',
			'posts_per_page' => $per_page,
			'paged'          => $page,
		];

		if ( ! empty( $search_term ) ) {
			$paged_posts_args['s'] = $search_term;
		}

		// Perform the WP_Query
		$posts_query = new WP_Query( $paged_posts_args );

		// Map the posts into the required format with page context identifiers
		$posts = array_map( function ( $post ) use ( $group_name ) {
			return Wp_Object::make( [
				'id'          => $post->ID,
				'title'       => ! empty( $post->post_title ) ? $post->post_title : __( '(no title)', 'limb-chatbot' ),
				'link'        => get_permalink( $post->ID ),
				'identifier'  => "singular:{$group_name}:{$post->ID}",
				'object_type' => $group_name,
			] );
		}, $posts_query->posts );

		// Create collection and set total
		$collection = new Data_Object_Collection( $posts );
		$collection->set_total( $posts_query->found_posts );

		// Add pagination properties
		$collection->push_property( 'page', $page );
		$collection->push_property( 'per_page', $per_page );
		$collection->push_property( 'total_pages', ceil( $posts_query->found_posts / $per_page ) );

		return $collection;
	}
}