<?php
/**
 * All the Rest endpoints used by the Plugin.
 *
 * @package Flexible_FAQs
 */

namespace WPGO_Plugins\Flexible_Faqs;

/**
 * Register custom REST API endpoints.
 */
class Custom_Rest_Api_Endpoints {

	/**
	 * Common root paths/directories.
	 *
	 * @var $module_roots
	 */
	protected $module_roots;

	/**
	 * Main class constructor.
	 *
	 * @param Array $module_roots Root plugin path/dir.
	 */
	public function __construct( $module_roots ) {

		$this->module_roots       = $module_roots;
		$this->rest_api_namespace = 'flexible-faqs/v1';

		add_action( 'rest_api_init', array( &$this, 'register_endpoints' ) );
	}

	/**
	 * Register REST API
	 */
	public function register_endpoints() {

		// FAQ POSTS ENDPOINTS.

		// Get all public faq posts.
		register_rest_route(
			$this->rest_api_namespace,
			'/posts',
			array(
				'methods'             => 'GET',
				'callback'            => array( &$this, 'get_posts' ),
				'permission_callback' => function () {
					return '';
				},
			)
		);

		// Get all public faq groups.
		register_rest_route(
			$this->rest_api_namespace,
			'/groups',
			array(
				'methods'             => 'GET',
				'callback'            => array( &$this, 'get_groups' ),
				'permission_callback' => function () {
					return '';
				},
			)
		);

		// Get individual faqs for a given faq post ID.
		register_rest_route(
			$this->rest_api_namespace,
			'/get-faqs/(?P<type>[a-zA-Z0-9-_]+)',
			array(
				'methods'             => 'GET',
				'callback'            => array( &$this, 'get_faqs' ),
				'permission_callback' => function () {
					return '';
				},
			)
		);

		// Get individual faqs for a specified group ID.
		register_rest_route(
			$this->rest_api_namespace,
			'/get-group-faqs/(?P<type>[a-zA-Z0-9-_]+)',
			array(
				'methods'             => 'GET',
				'callback'            => array( &$this, 'get_group_faqs' ),
				'permission_callback' => function () {
					return '';
				},
			)
		);
	}

	// CALLBACK FUNCTIONS FOR ENDPOINTS.

	// @TODO use this in 'permission_callback' above (and test)
	/**
	 * Checks the permissions to current user.
	 *
	 * @return Boolean True if current user have permissions to edit post, false otherwise.
	 */
	public function check_permissions() {
		return current_user_can( 'edit_posts' );
	}

	/**
	 * Get public FAQ posts.
	 *
	 * @return Array List of all FAQ posts (type 'wpgo_faq').
	 */
	public function get_posts() {

		$args  = array(
			'post_type'      => 'wpgo_faq',
			'posts_per_page' => -1,
		);
		$posts = get_posts( $args );

		$faq_posts = array();
		foreach ( $posts as $post ) {
			$active_faq             = Utility::get_faq_items_count( $post->ID );
			$faq_posts[ $post->ID ] = $post->post_title . ' (' . $active_faq['active_count'] . ')';
		}

		return $faq_posts;
	}

	/**
	 * Get public FAQ groups.
	 *
	 * @return Array List of all FAQ groups.
	 */
	public function get_groups() {

		$args   = array( 'taxonomy' => 'wpgo_faq_group' );
		$groups = get_terms( $args );

		$faq_groups = array();
		foreach ( $groups as $group ) {

			$args            = array(
				'post_type'   => 'wpgo_faq',
				'numberposts' => -1,
				'tax_query'   => array(
					array(
						'taxonomy'         => 'wpgo_faq_group',
						'field'            => 'term_id',
						'terms'            => $group->term_id,
						'include_children' => false,
					),
				),
			);
			$faq_group_posts = get_posts( $args );

			// Get post count for each FAQ post in group.
			$active_group_faqs = 0;
			foreach ( $faq_group_posts as $faq_group_post ) {
				$active_group_faqs_arr = Utility::get_faq_items_count( $faq_group_post->ID );
				$active_group_faqs    += $active_group_faqs_arr['active_count'];
			}

			$faq_groups[ $group->term_id ] = $group->name . ' (' . $active_group_faqs . ')';
		}

		return $faq_groups;
	}

	/**
	 * Get FAQs.
	 *
	 * @param WP_REST_Request $request The data received in the request.
	 * @return Array Nested array containing titles of FAQs sets and items in those FAQ sets.
	 */
	public function get_faqs( WP_REST_Request $request ) {

		$faq_id   = $request->get_param( 'type' );
		$post_arr = array();
		array_push( $post_arr, (int) $faq_id );
		return self::get_faqs_meta( $post_arr );
	}

	/**
	 * Get Group of FAQs
	 *
	 * @param WP_REST_Request $request The data received in the request.
	 * @return Array Nested array FAQ sets present in a group for FAQs.
	 */
	public function get_group_faqs( WP_REST_Request $request ) {

		$faq_group_id = $request->get_param( 'type' );

		$args            = array(
			'post_type'   => 'wpgo_faq',
			'numberposts' => -1,
			'tax_query'   => array(
				array(
					'taxonomy'         => 'wpgo_faq_group',
					'field'            => 'term_id',
					'terms'            => $faq_group_id,
					'include_children' => false,
				),
			),
		);
		$faq_group_posts = get_posts( $args );

		// Get post count for each faq post in group.
		$tmp = array();
		foreach ( $faq_group_posts as $faq_group_post ) {
			$id = $faq_group_post->ID;
			array_push( $tmp, $id );
		}

		return self::get_faqs_meta( $tmp );
	}

	// @TODO remove the below commented out code if it is not used any more.

	/**
	 * Get individual faq items from faq post meta
	 */
	// public static function get_faqs_meta($faq_post_ids) {

	// $faqs = array();
	// foreach($faq_post_ids as $faq_post_id) {

	// get post object
	// $faq_post = get_post($faq_post_id);

	// get q/a arrays from db
	// $faq_questions = get_post_meta( $faq_post_id, '_wpgo_faq_cpt_questions' )[0];
	// $faq_answers = get_post_meta( $faq_post_id, '_wpgo_faq_cpt_answers' )[0];

	// combine into new array where each element is an array of post title and sub array of faqs
	// $tmpArr = array();
	// $tmpArrOuter = array();
	// foreach($faq_questions as $key => $q) {
	// $tmp = array();
	// array_push($tmp, $faq_questions[$key]);
	// array_push($tmp, $faq_answers[$key]);
	// array_push($tmpArr, $tmp);
	// }
	// array_push($tmpArrOuter, $faq_post->post_title);
	// array_push($tmpArrOuter, $tmpArr);

	// for single sets of faqs there will only be one entry but it keeps it consistent with expected format of faq data
	// array_push($faqs, $tmpArrOuter);
	// }

	// return $faqs;
	// }

	/**
	 * Get individual faq items from faq post meta
	 *
	 * @param Array $faq_post_ids The IDs of FAQ sets.
	 * @return Array Nested array containing titles of FAQs sets and items in those FAQ sets.
	 */
	public static function get_faqs_meta( $faq_post_ids ) {

		$faqs = array();
		foreach ( $faq_post_ids as $faq_post_id ) {

			// Get post object.
			$faq_post = get_post( $faq_post_id );

			// Get q/a arrays from DB.
			$faq_questions = get_post_meta( $faq_post_id, '_wpgo_faq_cpt_questions' )[0];
			$faq_answers   = get_post_meta( $faq_post_id, '_wpgo_faq_cpt_answers' )[0];

			// Combine into new array where each element is an array of post title and sub array of FAQs.
			$tmp_arr       = array();
			$tmp_arr_outer = array();
			foreach ( $faq_questions as $key => $q ) {
				$tmp             = array();
				$tmp['question'] = $faq_questions[ $key ];
				$tmp['answer']   = $faq_answers[ $key ];
				$tmp['expanded'] = false; // @todo Allow this to optionally be set on each FAQ item in CPT editor, default value should still be false.
				array_push( $tmp_arr, $tmp );
			}
			$tmp_arr_outer['title'] = $faq_post->post_title;
			$tmp_arr_outer['items'] = $tmp_arr;

			// For single sets of faqs there will only be one entry but it keeps it consistent with expected format of faq data.
			array_push( $faqs, $tmp_arr_outer );
		}

		return $faqs;
	}
} /* End class definition */
