<?php
namespace BwlFaqManager\Callbacks\Shortcodes;

use BwlFaqManager\Callbacks\Shortcodes\FaqOutputCb;

/**
 * Class FaqItemsCb
 *
 * Handles the FAQ items shortcode callbacks.
 *
 * @package BwlFaqManager
 */
class FaqItemsCb {

	/**
	 * Constructor for the FaqItemsCb class.
	 */
	public function __construct() {}

	/**
	 * Shortcode handler for the FAQ items.
	 *
	 * @param array $atts Shortcode attributes.
	 * @return string HTML output for the FAQ items.
	 */
	public function get_faq_items( $atts ) {

		$atts = shortcode_atts([
			'post_type'             => BWL_BAF_CPT,
			'meta_key'              => '',
			'orderby'               => 'menu_order',
			'order'                 => 'ASC',
			'limit'                 => -1,
			'faq_category'          => '',
			'faq_topics'            => '',
			'sbox'                  => 1,
			'search_only_title'     => 0,
			'sbox_class'            => '',
			'placeholder'           => esc_html__( 'Search...', 'bwl-adv-faq' ),
			'highlight_color'       => '#000000',
			'highlight_bg'          => '#FDE990',
			'baf_suggestion_status' => 0,
			'baf_suggestion_prefix' => esc_html__( 'Popular searches:', 'bwl-adv-faq' ),
			'baf_suggestion'        => '',
			'cont_ext_class'        => '',
			'btn_ctrl'              => 1,
			'bwl_tabify'            => 0,
			'list'                  => 0, // list=1 enables multiple catgories or topics group
			'multi'                 => 0,
			'single'                => 0,
			'taxonomy_info_search'  => 0,
			'taxonomy_info'         => 0, // It will display taxonomy description.
			'taxonomy_title'        => 1, // 0=hide the taxonomy title
			'collapse'              => 0,
			'fpid'                  => 0, // display mutiple FAQs
			'paginate'              => 0, // enable or disable pagination
			'pag_limit'             => 5,
			'post_ids'              => '',
			'theme_id'              => '', // light, red, blue,green,pink,orange
			'first_color'           => '',
			'second_color'          => '',
			'label_text_color'      => '',
			'accordion_arrow'       => '',
			'custom_layout'         => '', // baf_layout_flat, baf_layout_semi_round, baf_layout_round
			'row_open'              => '', // Mention the row number that you would like to open when load the page.
			'sc_excerpt'            => 0,
			'schema'                => 0,
			'aia'                   => 0,
		], $atts);

		extract( $atts );

		// Meta Key Update.

		if ( $meta_key === 'votes_count' ) {
			$meta_key = 'baf_votes_count';
		}

		// Show Single FAQ. Introduced Version 1.4.9

		if ( $multi == 1 ) {

			return FaqOutputCb::get_multi_faq_interface( $atts );
		}

		if ( $single == 1 ) {

			return FaqOutputCb::get_single_faq_interface( $atts );
		}

		// New Feature added in version 1.4.6

		if ( $list == 1 && $faq_category != '' ) {

			return $this->get_list_faq_interface( $atts );
		}

		if ( $list == 1 && $faq_topics != '' ) {

			return $this->get_list_faq_interface( $atts );
		}

		if ( $faq_category != '' ) {
			$id_prefix       = 'category-';
			$baf_sort_prefix = PREFIX_BAF_CAT;
			$baf_sort_filter = 'category';
		}

		if ( $faq_topics != '' ) {
			$id_prefix       = 'topic-';
			$baf_sort_prefix = PREFIX_BAF_TOPIC;
			$baf_sort_filter = 'topics';
		}

		$args = [
			'post_status'           => 'publish',
			'post_type'             => $post_type,
			'orderby'               => $orderby,
			'order'                 => $order,
			'posts_per_page'        => $limit,
			'advanced_faq_category' => $faq_category,
			'advanced_faq_topics'   => $faq_topics,
		];

		if ( isset( $post_ids ) && $post_ids != '' ) {
			$args['post__in'] = explode( ',', $post_ids );
		}

		if ( isset( $meta_key ) && $meta_key != '' ) {
			$args['meta_key'] = $meta_key;
		}

		$loop = new \WP_Query( $args );

		/**********************************************************
		 * @Description: Check if tabbify faq and custom order has been setted then we
		 * need to adjust loop.
		 * @since: Version 1.6.1
		 * ********************************************************* */

		if ( isset( $bwl_tabify ) && $bwl_tabify == 1 && isset( $orderby ) && $orderby === 'menu_order' ) {

			$baf_cat_all_posts_id = [];
			$baf_term_id          = 0;

			if ( $loop->have_posts() ) :

				while ( $loop->have_posts() ) :

					$loop->the_post();

					if ( $faq_topics != '' ) {
						$category_info = get_term_by( 'slug', $faq_topics, 'advanced_faq_' . $baf_sort_filter );
					} else {
						$category_info = get_term_by( 'slug', $faq_category, 'advanced_faq_' . $baf_sort_filter );
					}

					$baf_term_id            = $category_info->term_id;
					$baf_cat_all_posts_id[] = get_the_ID();

				endwhile;

			endif;

			wp_reset_query();

			$args = FaqOutputCb::getDynamicSortArguments( $baf_cat_all_posts_id, $baf_sort_prefix, $baf_sort_filter, $baf_term_id, $faq_category, $limit );

			$loop = new \WP_Query( $args );
		}

		return FaqOutputCb::get_baf_output( $atts, $loop );
	}

	public function get_list_faq_interface( $atts ) {

		extract( $atts );

		$unique_faq_container_id = wp_rand();

		$list_output = '<section class="ac-container" container_id="' . $unique_faq_container_id . '" id="' . $unique_faq_container_id . '">';

		$list_inner_output = '';

		// Some Reset: Fix in version 1.5.3

		$orderby   = trim( $atts['orderby'] ) ?? 'menu_order' ?: 'menu_order';
		$order     = trim( $atts['order'] ) ?? 'ASC' ?: 'ASC';
		$limit     = trim( $atts['limit'] ) ?? -1 ?: -1;
		$paginate  = $atts['paginate'] ?? 1 ?: 1;
		$pag_limit = $atts['pag_limit'] ?? 5 ?: 5;

		if ( isset( $atts['sbox'] ) && $atts['sbox'] == 1 ) {

			// Added in version 1.7.1
			// Search Only Title
			$search_only_title = $atts['search_only_title'] ?? 0 ?: 0;
		}
		// Custom Class For Search Box.

		$sbox_extra_class = 'baf_filter_list'; // important class

		if ( isset( $atts['sbox_class'] ) && $atts['sbox_class'] != '' ) {
			$sbox_extra_class .= ' ' . $atts['sbox_class']; // add extra space before the custom class.
		}

		// Generate search box.
		$list_inner_output .= do_shortcode(
            "[baf_sbox sbox_id='$unique_faq_container_id' 
        unique_id='$unique_faq_container_id' 
        pag_limit='$pag_limit' 
        paginate='$paginate'
        sbox_class='$sbox_extra_class' 
        taxonomy_info_search='1']"
		);

		$taxonomyType  = ( isset( $faq_topics ) && trim( $faq_topics ) != '' ) ? 'topics' : 'category';
		$faqTaxonomies = ( isset( $faq_topics ) && trim( $faq_topics ) != '' ) ? explode( ',', $faq_topics ) : explode( ',', $faq_category );

		foreach ( $faqTaxonomies as $topics ) {

			$taxonomyDetails = get_term_by( 'slug', $topics, "advanced_faq_{$taxonomyType}" );

			$list_inner_output .= '<div class="baf_taxonomy_info_container">';

			$list_inner_output .= $taxonomy_title ? "<h2>{$taxonomyDetails->name}</h2>" : '';

			// Display Topics Description.
			// Since: Version 1.6.7

			$list_inner_output .= $taxonomy_info && ! empty( $taxonomyDetails->description ) ? "<p class='baf_taxonomy_info'>{$taxonomyDetails->description}</p>" : '';

			$list_inner_output .= '</div>';

			if ( $orderby == 'menu_order' ) {

				$list_inner_output .= do_shortcode( '[bwla_dsort_faq baf_sort_filter="' . $taxonomyType . '" faq_' . $taxonomyType . '="' . $topics . '" baf_term_id="' . $taxonomyDetails->term_id . '" sbox="0" sbox_class="' . $sbox_class . '" search_only_title="' . $search_only_title . '" btn_ctrl="' . $btn_ctrl . '" order="' . $order . '" orderby="' . $orderby . '" pag_limit="' . $pag_limit . '" paginate="' . $paginate . '" limit="' . $limit . '" theme_id="' . $theme_id . '" first_color="' . $first_color . '" second_color="' . $second_color . '" label_text_color="' . $label_text_color . '" accordion_arrow="' . $accordion_arrow . '" custom_layout="' . $custom_layout . '" sc_excerpt="' . $sc_excerpt . '" schema="' . $schema . '" /]' );
			} else {

				$list_inner_output .= do_shortcode( '[bwla_faq faq_' . $taxonomyType . '="' . $topics . '" sbox="0" sbox_class="' . $sbox_class . '" search_only_title="' . $search_only_title . '" btn_ctrl="' . $btn_ctrl . '" list="0" order="' . $order . '" orderby="' . $orderby . '" pag_limit="' . $pag_limit . '" paginate="' . $paginate . '" limit="' . $limit . '" theme_id="' . $theme_id . '" first_color="' . $first_color . '" second_color="' . $second_color . '" label_text_color="' . $label_text_color . '" accordion_arrow="' . $accordion_arrow . '" custom_layout="' . $custom_layout . '" sc_excerpt="' . $sc_excerpt . '" schema="' . $schema . '" /]' );
			}
		}

		$list_output .= $list_inner_output;

		$list_output .= '</section>';

		return $list_output;
	}
}
