<?php
/**
 * Query published testimonials for widget library mode.
 *
 * @package Rsmspark_Content_Widgets
 */

defined( 'ABSPATH' ) || exit;

/**
 * Rsmspark_Testimonials_Library
 */
class Rsmspark_Testimonials_Library {

	/**
	 * @param array<string, mixed> $args Query args.
	 * @return array<int, array<string, mixed>>
	 */
	public static function profiles( array $args = array() ) {
		$limit   = max( 1, min( 24, absint( $args['limit'] ?? 12 ) ) );
		$orderby = sanitize_key( (string) ( $args['orderby'] ?? 'date' ) );
		$order   = strtoupper( sanitize_key( (string) ( $args['order'] ?? 'DESC' ) ) );

		if ( ! in_array( $orderby, array( 'date', 'menu_order', 'title' ), true ) ) {
			$orderby = 'date';
		}
		if ( ! in_array( $order, array( 'ASC', 'DESC' ), true ) ) {
			$order = 'DESC';
		}

		$query = new WP_Query(
			array(
				'post_type'              => Rsmspark_Testimonials_CPT::CPT,
				'post_status'            => 'publish',
				'posts_per_page'         => $limit,
				'orderby'                => $orderby,
				'order'                  => $order,
				'no_found_rows'          => true,
				'update_post_meta_cache' => true,
				'update_post_term_cache' => false,
			)
		);

		if ( ! $query->have_posts() ) {
			return array();
		}

		$profiles = array();
		foreach ( $query->posts as $post ) {
			if ( ! $post instanceof WP_Post ) {
				continue;
			}

			$photo = get_the_post_thumbnail_url( $post, 'medium' );
			if ( ! $photo ) {
				$photo = '';
			}

			$profiles[] = array(
				'id'    => 'profile-post-' . $post->ID,
				'photo' => $photo,
				'name'  => get_the_title( $post ),
				'role'  => Rsmspark_Testimonials_CPT::get_role( $post->ID ),
				'quote' => get_the_excerpt( $post ),
				'bio'   => apply_filters( 'the_content', $post->post_content ),
			);
		}

		wp_reset_postdata();

		return $profiles;
	}

	/**
	 * @return int
	 */
	public static function published_count() {
		$counts = wp_count_posts( Rsmspark_Testimonials_CPT::CPT );
		return isset( $counts->publish ) ? (int) $counts->publish : 0;
	}

	/**
	 * @return int
	 */
	public static function pending_count() {
		$counts = wp_count_posts( Rsmspark_Testimonials_CPT::CPT );
		return isset( $counts->pending ) ? (int) $counts->pending : 0;
	}
}
