<?php
namespace BwlFaqManager\Callbacks\Shortcodes;

/**
 * Class FaqTabsCb
 *
 * Handles the FAQ tabs shortcodes.
 *
 * @package BwlFaqManager
 */
class FaqTabsCb {

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

	/**
	 * Shortcode handler for a single FAQ tab.
	 *
	 * @param array  $atts    Shortcode attributes.
	 * @param string $content Content between shortcode tags.
	 * @return void
	 */
	public function get_faq_tab( $atts, $content = null ) {

		extract(shortcode_atts([
			'title'    => '',
			'link'     => '',
			'target'   => '',
			'vertical' => 0,
		], $atts));

		global $single_tab_array;

		$single_tab_array[] = [
			'title'    => $title,
			'link'     => $link,
			'content'  => trim( do_shortcode( $content ) ),
			'vertical' => $vertical,
		];
	}


	/**
	 * Shortcode handler for multiple FAQ tabs.
	 *
	 * @param array  $atts    Shortcode attributes.
	 * @param string $content Content between shortcode tags.
	 * @return string         HTML output for the FAQ tabs.
	 */
	public function get_faq_tabs( $atts, $content = null ) {

		global $single_tab_array;

		// Vertical FAQ Tab: Introduced in version 1.6.3

		$atts = shortcode_atts([
			'vertical' => 0,
			'rtl'      => 0,
		], $atts);

		extract( $atts );

		$bwl_faq_tabs_ver            = '';
		$bwl_faq_content_wrapper_ver = '';

		if ( isset( $vertical ) && $vertical === 1 ) {
			$bwl_faq_tabs_ver            = ' bwl-faq-tabs-ver';
			$bwl_faq_content_wrapper_ver = ' bwl-faq-content-wrapper-ver';
		}

		$single_tab_array = []; // clear the array

		$tab_navigation = '<div class="bwl-faq-wrapper">';
		$tab_content    = '';
		$tab_output     = '';

		$tab_navigation .= '<ul class="bwl-faq-tabs' . $bwl_faq_tabs_ver . '">';

		// execute the '[tab]' shortcode first to get the title and content - acts on global $single_tab_array
		do_shortcode( $content );

		// declare our vars to be super clean here

		foreach ( $single_tab_array as $tab => $tab_attr_array ) {

			$random_id = wp_rand();

			$default = ( $tab === 0 ) ? ' class="active"' : '';

			if ( $tab_attr_array['link'] != '' ) {

				$tab_navigation .= '<li' . $default . '><a class="bwl-faq-link" href="' . $tab_attr_array['link'] . '" target="' . $tab_attr_array['target'] . '" rel="tab' . $random_id . '"><span>' . $tab_attr_array['title'] . '</span></a></li>';
			} else {

				$tab_navigation .= '<li' . $default . '><a href="#" rel="tab' . $random_id . '"><span>' . $tab_attr_array['title'] . '</span></a></li>';
				$tab_content    .= '<div class="bwl-faq-tab-content" id="tab' . $random_id . '" ' . ( $tab !== 0 ? 'style="display:none"' : '' ) . '>' . $tab_attr_array['content'] . '</div>';
			}
		}

		$tab_navigation .= '</ul>';

		$tab_output  = $tab_navigation . '<div class="bwl-faq-content-wrapper' . $bwl_faq_content_wrapper_ver . '">' . $tab_content . '</div>';
		$tab_output .= '</div>';

		return $tab_output;
	}
}
