<?php
/**
 * Dynamic Tag: Post Category Post Count
 *
 * @package captain-widgets-kit
 * @since   1.1.0
 */

use Elementor\Core\DynamicTags\Tag;
use Elementor\Modules\DynamicTags\Module;
if ( ! defined( 'ABSPATH' ) ) {
	exit; }
/**
 * Class Captwiki_Tag_Post_Category_Post_Count
 * Outputs the post count of the first post category.
 */
class Captwiki_Tag_Post_Category_Post_Count extends Tag {
	/**
	 * Get tag name.
	 *
	 * @return string
	 */
	public function get_name(): string {
		return 'captwiki-tag-post-category-post-count'; }
	/**
	 * Get tag title.
	 *
	 * @return string
	 */
	public function get_title(): string {
		return esc_html__( 'Post Category Post Count', 'captain-widgets-kit' ); }
	/**
	 * Get tag group.
	 *
	 * @return array
	 */
	public function get_group(): array {
		return array( 'captwiki-post' ); }
	/**
	 * Get tag categories.
	 *
	 * @return array
	 */
	public function get_categories(): array {
		return array( Module::TEXT_CATEGORY ); }
	/**
	 * Check whether settings are required.
	 *
	 * @return bool
	 */
	public function is_settings_required() {
		return true; }
	/**
	 * Register tag controls.
	 *
	 * @return void
	 */
	protected function register_controls(): void {}
	/**
	 * Render tag output.
	 *
	 * @return void
	 */
	public function render(): void {
		$category = null;
		if ( is_category() ) {
			$q = get_queried_object();
			if ( $q instanceof \WP_Term ) {
				$category = $q; }
		} else {
			$post_id = get_the_ID();
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended
			if ( ! $post_id && ! empty( $_REQUEST['post_id'] ) ) {
				$post_id = absint( wp_unslash( $_REQUEST['post_id'] ) ); } // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			if ( ! $post_id ) {
				return; }
			$terms = get_the_terms( $post_id, 'category' );
			if ( empty( $terms ) || is_wp_error( $terms ) ) {
				return; }
			$category = $terms[0];
		}
		if ( ! empty( $category ) && isset( $category->count ) ) {
			echo esc_html( $category->count ); }
	}
}
