<?php
namespace Prodigy\Includes\Frontend\Mappers;

use Prodigy\Includes\Prodigy;

/**
 * Prodigy breadcrumbs data mapper
 *
 * @version    3.0.9
 * @package    Prodigy
 * @subpackage Prodigy/includes
 */
class Prodigy_Breadcrumbs_Data_Mapper extends Prodigy_Main_Data_Mapper {

	/**
	 * Prepare data and variables to inject in template
	 *
	 * @param array $options
	 *
	 * @return array
	 */
	public function get_default_parameters( array $options ): array {
		$customizerShopOptions = $this->customizer_shop_options;
		$currentObject         = get_queried_object();

		$categoryData             = $this->get_category_data( $currentObject );
		$options['category_name'] = $categoryData['name'];
		$options['url_to']        = $categoryData['url'];

		$options['style_curr_page']                   = $options['style_curr_page'] ?? 'yes';
		$options['prodigy_shop_products_breadcrumbs'] = $customizerShopOptions['prodigy_shop_products_breadcrumbs'] ?? true;
		$options['show_breadcrumbs']                  = isset( $options['idwidget'] )
														|| ( $customizerShopOptions['prodigy_shop_products_breadcrumbs'] ?? true );

		return $options;
	}

	/**
	 * @param $currentObject
	 *
	 * @return array
	 */
	private function get_category_data( $currentObject ): array {
		$linkToShop   = get_permalink( get_page_by_path( 'shop' ) );
		$categoryData = array(
			'name' => '',
			'url'  => $linkToShop,
		);

		if ( ! empty( $currentObject ) ) {
			if ( $this->is_valid_taxonomy_term( $currentObject ) ) {
				$categoryData['name'] = $currentObject->name;
				$categoryData['url']  = '/' . $currentObject->taxonomy . '/' . $currentObject->slug;
			} elseif ( isset( $currentObject->ID ) ) {
				$pageLink            = get_page_link( $currentObject->ID );
				$categoryData['url'] = $pageLink;
				if ( $pageLink !== $linkToShop ) {
					$categoryData['name'] = $currentObject->post_title;
				}
			}
		}

		return $categoryData;
	}

	/**
	 * @param $currentObject
	 *
	 * @return bool
	 */
	private function is_valid_taxonomy_term( $currentObject ): bool {
		return ! is_wp_error( get_term( $currentObject->term_id, Prodigy::get_prodigy_category_type() ) )
				|| ! is_wp_error( get_term( $currentObject->term_id, Prodigy::get_prodigy_tag_type() ) );
	}
}
