<?php
namespace BwlFaqManager\Callbacks\Shortcodes;

use BwlFaqManager\Helpers\FaqColorScheme;
use BwlFaqManager\Controllers\Votes\FaqVoteContainer;


/**
 * Class FaqOutputCb
 *
 * Handles the output of FAQ shortcodes.
 *
 * @package BwlFaqManager
 * @since 1.6.1
 * @created 2015-10-30
 * @last-modified 2015-10-30
 */
class FaqOutputCb {

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

	/**
	 * Get the output of the FAQ interface.
	 *
	 * @param array  $atts Attributes for the shortcode.
	 * @param object $loop The loop object.
	 * @param string $id_prefix The prefix for the ID.
	 * @return string The output of the FAQ interface.
	 */
	public static function get_baf_output( $atts, $loop, $id_prefix = '' ) {

		global $post;

		extract( $atts ); // Fixed in version 1.6.6

		$bwl_advanced_faq_options = get_option( 'bwl_advanced_faq_options' );
		$preset                   = 0;

		if ( isset( $theme_id ) && ! empty( $theme_id ) ) {

			$theme_id = $theme_id;
			$preset   = 1;
		} elseif ( isset( $bwl_advanced_faq_options['bwl_advanced_faq_theme'] ) ) {

			$theme_id = $bwl_advanced_faq_options['bwl_advanced_faq_theme'];
		} else {

			$theme_id = 'default';
		}

		$faqColorScheme = new FaqColorScheme();

		$baf_predefined_theme_color_scheme = $faqColorScheme->baf_get_theme_color_scheme( $theme_id, $preset );

		// Initialize Data.

		$unique_faq_container_id = wp_rand();
		$sbox                    = isset( $sbox ) ? $sbox : 1;
		$search_only_title       = isset( $search_only_title ) ? $search_only_title : 0;
		$sbox_class              = isset( $sbox_class ) ? $sbox_class : '';
		$pag_limit               = isset( $pag_limit ) ? $pag_limit : 5;
		$paginate                = isset( $paginate ) ? $paginate : 0;
		$baf_section_class       = ( isset( $custom_layout ) && ! empty( $custom_layout ) ) ? "ac-container {$custom_layout}" : 'ac-container';

		// Color BackUp.
		// Default Light BG.
		$default_gradient_first_color = ( isset( $baf_predefined_theme_color_scheme['first_color'] ) ) ? trim( $baf_predefined_theme_color_scheme['first_color'] ) : '#F7F7F7';
		// Default Light Bg.
		$default_gradient_second_color = ( isset( $baf_predefined_theme_color_scheme['second_color'] ) ) ? trim( $baf_predefined_theme_color_scheme['second_color'] ) : '#FAFAFA';
		// Default Light Bg.
		$default_label_text_color = ( isset( $baf_predefined_theme_color_scheme['label_text_color'] ) ) ? trim( $baf_predefined_theme_color_scheme['label_text_color'] ) : '#777777';

		// For Custom Theme Color.
		// Deafult Gradient First Color.
		$first_color = ( isset( $first_color ) && ! empty( $first_color ) ) ? $first_color : $default_gradient_first_color;
		// Deafult Gradient Second Color.
		$second_color = ( isset( $second_color ) && $second_color != '' ) ? $second_color : $default_gradient_second_color;
		// Deafult Gradient Second Color.
		$label_text_color = ( isset( $label_text_color ) && $label_text_color != '' ) ? $label_text_color : $default_label_text_color;
		// Accordion Arrow.
		$default_accordion_arrow = ( isset( $bwl_advanced_faq_options['bwl_advanced_fa_arrow_up'] ) && $bwl_advanced_faq_options['bwl_advanced_fa_arrow_up'] != '' ) ? substr( $bwl_advanced_faq_options['bwl_advanced_fa_arrow_up'], 1, strlen( $bwl_advanced_faq_options['bwl_advanced_fa_arrow_up'] ) ) : 'f106';  // From Settings Page.
		// From Shortcode.
		// Deafult Gradient Second Color.
		$baf_accordion_arrow = ( isset( $accordion_arrow ) && $accordion_arrow != '' ) ? $accordion_arrow : $default_accordion_arrow;

		if ( isset( $faq_category ) && $faq_category != '' ) {
			$id_prefix = 'category-';
		} elseif ( isset( $faq_topics ) && $faq_topics != '' ) {
			$id_prefix = 'topic-';
		} elseif ( $id_prefix == 'single-' ) {
			$id_prefix          = 'single-';
			$collapse_status    = ( isset( $collapse ) && $collapse == 1 ) ? ' baf-single-collapse' : '';
			$baf_section_class .= ' single-faq-post' . $collapse_status;
			$sbox               = 0;
		} else {
			$id_prefix = wp_rand();
		}

		// Start Generating FAQ Output.

		$section_faq_unique_class = ' section_baf_' . $unique_faq_container_id;
		$tag_row_open             = '';

		if ( isset( $row_open ) && ! empty( $row_open ) ) {
			$section_faq_unique_class .= ' baf_row_open ';
			$tag_row_open             .= 'data-row_open="' . $row_open . '"';
		}

		// AIA.

		$baf_section_class .= ( isset( $aia ) && $aia == 1 ) ? ' aia_container' : '';

		$output = '<section class="baf_custom_style ' . $section_faq_unique_class . ' ' . $baf_section_class . '" container_id="' . $unique_faq_container_id . '" data-first_color="' . $first_color . '" data-second_color="' . $second_color . '" data-label_text_color="' . $label_text_color . '" data-accordion_arrow="' . $baf_accordion_arrow . '" ' . $tag_row_open . '  data-schema="' . $schema . '">'; // Open the container

		/*------ Get Options For Search Settings  ---------*/

		$bwl_advanced_faq_search_status = 1;

		if ( isset( $bwl_advanced_faq_options['bwl_advanced_faq_search_status'] ) ) {

			$bwl_advanced_faq_search_status = $bwl_advanced_faq_options['bwl_advanced_faq_search_status'];
		}

		$output .= '<input type="hidden" id="current_page"><input type="hidden" id="show_per_page">  ';

		if ( $bwl_advanced_faq_search_status && $sbox != 0 ) {

			$output .= do_shortcode( '[baf_sbox sbox_id="' . $unique_faq_container_id . '" placeholder="' . $placeholder . '" paginate="' . $paginate . '" sbox_class="' . $sbox_class . '" search_only_title="' . $search_only_title . '" pag_limit="' . $pag_limit . '" baf_suggestion_status="' . $baf_suggestion_status . '" baf_suggestion_prefix="' . $baf_suggestion_prefix . '" baf_suggestion="' . $baf_suggestion . '" highlight_color="' . $highlight_color . '"  highlight_bg="' . $highlight_bg . '"  cont_ext_class="' . $cont_ext_class . '" ]' );
		}

		if ( isset( $bwl_advanced_faq_options['bwl_collapsible_btn_status'] ) && $bwl_advanced_faq_options['bwl_collapsible_btn_status'] == 1 ) {

			if ( isset( $btn_ctrl ) && $btn_ctrl == 1 ) {

				$output .= '<div class="baf-ctrl-btn"><span class="baf-expand-all"><i class="fa fa-plus"></i></span><span class="baf-collapsible-all"><i class="fa fa-minus"></i></span></div>';
			}
		}

		/*------ FAQ Post Date/Time Information ---------*/

		$bwl_advanced_faq_meta_info_status = 0;

		if ( isset( $bwl_advanced_faq_options['bwl_advanced_faq_meta_info_status'] ) ) {

			$bwl_advanced_faq_meta_info_status = $bwl_advanced_faq_options['bwl_advanced_faq_meta_info_status'];
		}

		$bwl_advanced_faq_meta_info                = '';
		$bwl_advanced_faq_show_date_time_interface = '';

		/*------ FAQ Author Information ---------*/

		$bwl_advanced_faq_author_info_interface = '';

		/*------Direct Post Edit Permission ---------*/

		$bwl_advanced_faq_edit_status    = 0;
		$bwl_advanced_faq_edit_interface = '';

		if ( is_user_logged_in() ) :
			$bwl_advanced_faq_edit_status = 1;
		endif;

		/*------ Like Button Status ---------*/

		$bwl_advanced_faq_like_button_interface = '';
		$bwl_advanced_faq_like_button_status    = 1;

		if ( isset( $bwl_advanced_faq_options['bwl_advanced_faq_like_button_status'] ) ) {

			$bwl_advanced_faq_like_button_status = $bwl_advanced_faq_options['bwl_advanced_faq_like_button_status'];
		}

		/* ----- Logged In Requirement For Voting Status ---- */

		if ( isset( $bwl_advanced_faq_options['baf_logged_in_voting_status'] ) && $bwl_advanced_faq_options['baf_logged_in_voting_status'] == 1 ) {

			if ( ! is_user_logged_in() ) {

				$bwl_advanced_faq_like_button_status = 0;
			}
		}

		if ( $loop->have_posts() ) :

			$counter = 1;

			while ( $loop->have_posts() ) :

				// echo '<pre>';
				// print_r( get_the_title() );
				// print_r( get_the_ID() );
				// echo '</pre>';

				$loop->the_post();
				$post_id = get_the_ID();

				if ( $bwl_advanced_faq_like_button_status == 1 ) {

					$faqVoteContainer                       = new FaqVoteContainer();
					$bwl_advanced_faq_like_button_interface = $faqVoteContainer->getVoteContainer( $post_id );
				}

				// Get Author FAQ Author Information
				$bwl_advanced_faq_author_info_interface = "<span class='fa fa-user'></span> " . do_shortcode( '[bwla_author]' );

				// Likes Count.
				$votesCount  = get_post_meta( $post_id, 'baf_votes_count', true );
				$votesLayout = '<span class="fa fa-thumbs-up"></span>' . ( ( ! empty( $votesCount ) ) ? $votesCount : 0 );

				// Views Count.
				$viewsCount  = get_post_meta( $post_id, 'baf_views_count', true );
				$viewsLayout = '<span class="fa fa-eye"></span>' . ( ( ! empty( $viewsCount ) ) ? $viewsCount : 0 );

				// Get FAQ Date and Time
				$bwl_advanced_faq_show_date_time_interface = "<span class='fa fa-calendar'></span> " . get_the_date();

				// Get FAQ Edit Link
				if ( $bwl_advanced_faq_edit_status == 1 && current_user_can( 'edit_post', $post_id ) ) {
					$bwl_advanced_faq_edit_url       = get_edit_post_link();
					$bwl_advanced_faq_edit_interface = '<span class="fa fa-edit"></span> <a href="' . $bwl_advanced_faq_edit_url . '" target="_blank" title="' . get_the_title() . '">' . esc_html__( 'Edit', 'bwl-adv-faq' ) . '</a>';
				}

				// Initialize ingredient customizer addon option.
				$baf_ic_info = '';

				if ( shortcode_exists( 'baf_ic_products' ) ) {
					global $post;
					$backup                     = $post;
					$bwl_advanced_faq_meta_info = '';
					$baf_ic_info               .= do_shortcode( '[baf_ic_products f_id="' . $post_id . '"]' );
					$post                       = $backup;
				}

				if ( $bwl_advanced_faq_meta_info_status == 1 ) {

					$bwl_advanced_faq_meta_info = "<div class='bwl_meta_info'>" . $bwl_advanced_faq_author_info_interface . ' ' . $votesLayout . ' ' . $viewsLayout . ' ' . $bwl_advanced_faq_show_date_time_interface . ' ' . $bwl_advanced_faq_edit_interface . '</div>';
				}

				$bwl_advanced_faq_meta_info .= $baf_ic_info;

				$faqTitleTag = $bwl_advanced_faq_options['bwl_advanced_label_tag'] ?? 'label' ?: 'label';
				// empty, null, or false.

				$output .= '<div class="bwl-faq-container bwl-faq-container-' . $unique_faq_container_id . '" id="faq-' . $post_id . '">' .
				'<' . $faqTitleTag . ' class="baf_schema" label_id="ac-' . $id_prefix . $post_id . '" parent_container_id="' . $unique_faq_container_id . '">' . get_the_title() . '</' . $faqTitleTag . '>' .
				'<input id="ac-' . $id_prefix . $unique_faq_container_id . $post_id . '" name="accordion-1" type="checkbox">' .
				'<article class="ac-medium" article_id="ac-' . $id_prefix . $post_id . '">' . bwl_advanced_faq_excerpt( $sc_excerpt ) . $bwl_advanced_faq_meta_info . $bwl_advanced_faq_like_button_interface . '</article>' .
				'</div>';

				++$counter;

			endwhile;

			$output .= '<div id="baf_page_navigation" class="baf_page_navigation" data-paginate="' . $paginate . '" data-pag_limit="' . $pag_limit . '"></div>';

		else :

			$output .= '<p>' . esc_html__( 'Sorry, No FAQ Available!', 'bwl-adv-faq' ) . '</p>';

		endif;

		$output .= '</section>'; // Close the container

		wp_reset_postdata();

		return $output;
	}

	/**
	 * Get multi FAQ interface
	 *
	 * @param array $atts Attributes for the shortcode.
	 * @return string The output of the FAQ interface.
	 */
	public static function get_multi_faq_interface( $atts ) {

		shortcode_atts([
			'post_type'    => BWL_BAF_CPT,
			'limit'        => -1,
			'meta_key'     => '',
			'faq_category' => '',
			'faq_topics'   => '',
			'sbox'         => 0,
			'bwl_tabify'   => 0,
			'list'         => 0,
			'fpid'         => 0,
			'collapse'     => 0,
			'sc_excerpt'   => 0,
			'schema'       => 0,
		], $atts);

		extract( $atts );

		$args = [
			'post_status'    => 'publish',
			'post_type'      => $post_type,
			'posts_per_page' => -1,
		];

		$fpids = explode( ',', $fpid );

		if ( is_array( $fpids ) ) {
			$args['post__in'] = $fpids;
		}

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

		$id_prefix = 'multi-';

		$loop = new \WP_Query( $args );

		return self::get_baf_output( $atts, $loop, $id_prefix );
	}

	/**
	 * Get single FAQ interface
	 *
	 * @param array $atts Attributes for the shortcode.
	 * @return string The output of the FAQ interface.
	 */
	public static function get_single_faq_interface( $atts ) {

		shortcode_atts([
			'post_type'    => BWL_BAF_CPT,
			'limit'        => -1,
			'meta_key'     => '',
			'faq_category' => '',
			'faq_topics'   => '',
			'sbox'         => 0,
			'bwl_tabify'   => 0,
			'list'         => 0,
			'single'       => 1,
			'fpid'         => 0,
			'collapse'     => 0,
			'sc_excerpt'   => 0,
			'schema'       => 0,
		], $atts);

		extract( $atts );

		$args = [
			'post_status'    => 'publish',
			'post_type'      => $post_type,
			'posts_per_page' => 1,
			'p'              => $fpid,
		];

		$unique_faq_container_id = wp_rand();

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

		$id_prefix = 'single-';

		$loop = new \WP_Query( $args );

		return self::get_baf_output( $atts, $loop, $id_prefix );
	}

	/**
	 * Get dynamic sort arguments for the FAQ categories and topics posts
	 *
	 * @param int    $baf_cat_all_posts_id The ID of the FAQ category.
	 * @param string $baf_sort_prefix The prefix for the sort.
	 * @param string $baf_sort_filter The filter for the sort.
	 * @param int    $baf_term_id The ID of the term.
	 * @param string $faq_category The category of the FAQ.
	 * @param int    $limit The limit for the FAQ.
	 * @return array The arguments for the FAQ.
	 * @since: 1.2.0
	 * @created: 10.10.2014
	 * @updated: 13.08.2024
	 */
	public static function getDynamicSortArguments(
        $baf_cat_all_posts_id,
        $baf_sort_prefix,
        $baf_sort_filter,
        $baf_term_id,
        $faq_category,
        $limit
	) {
		// call db for post meta.
		$baf_cat_sorted_posts_id = explode( ',', get_option( $baf_sort_prefix . $baf_term_id ) );

		$baf_cat_final_sorted_posts_id = array_values( array_unique( array_merge( $baf_cat_sorted_posts_id, $baf_cat_all_posts_id ) ) );

		$args = [
			'post_type'      => BWL_BAF_CPT,
			'post_status'    => 'publish',
			'post__in'       => $baf_cat_final_sorted_posts_id,
			'orderby'        => 'post__in',
			'posts_per_page' => $limit,
		];

		$filterTag = $baf_sort_filter === 'topics' ? 'topic' : 'category';

		$args[ "advanced_faq_{$filterTag}" ] = $faq_category;

		return $args;
	}
}
