<?php

namespace Limb_Chatbot\Includes\Repositories;

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

class Wp_Archive_Object_Repository extends Wp_Object_Repository {
	/**
	 * Fetch Archive 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 {
		$post_types_with_archives = get_post_types( [ 'public' => true, 'has_archive' => true ], 'objects' );

		// Add 'post' type manually since it has archive but might not be flagged
		$post_post_type = get_post_type_object( 'post' );
		if ( $post_post_type && ! isset( $post_types_with_archives['post'] ) ) {
			$post_types_with_archives['post'] = $post_post_type;
		}

		// Filter post types based on search
		if ( ! empty( $search_term ) ) {
			$post_types_with_archives = array_filter( $post_types_with_archives,
				function ( $post_type_obj ) use ( $search_term ) {
					return str_contains( strtolower( $post_type_obj->label ), strtolower( $search_term ) );
				} );
		}

		// Pagination logic
		$total_items              = count( $post_types_with_archives );
		$offset                   = ( $page - 1 ) * $per_page;
		$post_types_with_archives = array_slice( $post_types_with_archives, $offset, $per_page );

		// Map post types into archive objects
		$archives = array_map( function ( $post_type_obj ) {
			return Wp_Object::make( [
				'id'          => null,
				'title'       => $post_type_obj->label . ' ' . __( 'Archive', 'limb-chatbot' ),
				'link'        => get_post_type_archive_link( $post_type_obj->name ),
				'identifier'  => "archive:{$post_type_obj->name}",
				'object_type' => $post_type_obj->name,
			] );
		}, $post_types_with_archives );

		// Create collection and set total
		$collection = new Data_Object_Collection( $archives );
		$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', $total_items > 0 ? ceil( $total_items / $per_page ) : 0 );

		return $collection;
	}
}