<?php

namespace Limb_Chatbot\Includes\Repositories;

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

class Wp_Term_Object_Repository extends Wp_Object_Repository {

	/**
	 * Fetch term objects
	 *
	 * @param $group_name
	 * @param $search
	 * @param $per_page
	 * @param $page
	 *
	 * @return Data_Object_Collection
	 */
	public function get_items( $group_name, $search, $per_page, $page ): Data_Object_Collection {
		$taxonomy = str_replace( 'taxonomy_', '', $group_name );

		// First, get the total number of terms without limiting
		$total_terms_args = [
			'taxonomy'   => $taxonomy,
			'hide_empty' => false,
			'number'     => 0,
		];

		if ( ! empty( $search ) ) {
			$total_terms_args['search'] = $search;
		}

		// Get all terms to calculate total items
		$total_terms_query = new WP_Term_Query( $total_terms_args );
		$total_items       = count( $total_terms_query->get_terms() );

		// Now, apply pagination to the actual query
		$paged_terms_args = [
			'taxonomy'   => $taxonomy,
			'hide_empty' => false,
			'number'     => $per_page,
			'offset'     => ( $page - 1 ) * $per_page,
		];

		if ( ! empty( $search ) ) {
			$paged_terms_args['search'] = $search;
		}

		// Fetch the paginated terms
		$terms_query = new WP_Term_Query( $paged_terms_args );
		$terms       = array_map( function ( $item ) use ( $taxonomy ) {
			return Wp_Object::make( [
				'id'          => $item->term_id,
				'title'       => $item->name,
				'link'        => get_term_link( $item->term_id ),
				'identifier'  => "term:{$taxonomy}:{$item->term_id}",
				'object_type' => $taxonomy,
			] );
		}, $terms_query->get_terms() );

		// Create collection and set total
		$collection = new Data_Object_Collection( $terms );
		$collection->set_total( $total_items );

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

		return $collection;
	}
}