<?php

/**
 * WP Delicious Pro Shortcodes.
 *
 * @package Delicious_Recipes_Pro
 * @since 1.0.0
 */

defined( 'ABSPATH' ) || exit;
/**
 * Shortcodes handler.
 */
class Delicious_Recipes_Pro_Shortcodes {
	/**
	 * Init shortcodes.
	 */
	public static function init() {
		$shortcodes = array(
			'dr_guest_recipe_submission' => __CLASS__ . '::guest_recipe_submission',
			'dr_recipe_equipments'       => __CLASS__ . '::recipe_equipments',
			'DR_AFFILIATE_DISCLOSURE'    => __CLASS__ . '::affiliate_disclosure',
			'dr_submit_recipe'           => __CLASS__ . '::guest_recipe_submission',
			'dr_my_recipes'              => __CLASS__ . '::my_recipes',
			'dr_favorites_recipes'       => __CLASS__ . '::favorite_recipes',
			'dr_all_recipes'             => __CLASS__ . '::browse_recipes',
			'dr_edit_profile'            => __CLASS__ . '::edit_profile',
			'dr_login'                   => __CLASS__ . '::login_page',
		);

		foreach ( $shortcodes as $shortcode => $function ) {
			add_shortcode( apply_filters( "{$shortcode}_shortcode_tag", $shortcode ), $function );
		}
	}

	/**
	 * Add Guest Recipe Submission shortcode.
	 *
	 * @return string
	 */
	public static function guest_recipe_submission() {

		// If REST_REQUEST is defined (by WordPress) and is a TRUE, then it's a REST API request.
		$is_rest_route = ( defined( 'REST_REQUEST' ) && REST_REQUEST );
		if (
			( is_admin() && ! $is_rest_route ) || // admin and AJAX (via admin-ajax.php) requests
			( ! is_admin() && $is_rest_route )    // REST requests only
		) {
			return '';
		}

		$global_settings        = delicious_recipes_get_global_settings();
		$enableRecipeSubmission = isset( $global_settings['enableRecipeSubmission']['0'] ) && 'yes' === $global_settings['enableRecipeSubmission']['0'] ? true : false;
		$enableGuestMode        = isset( $global_settings['enableGuestMode']['0'] ) && 'yes' === $global_settings['enableGuestMode']['0'] ? true : false;

		if ( $enableRecipeSubmission && $enableGuestMode ) {

			ob_start();
			$output = '<div id="dr-pro-submit-recipe" class="dr-guest-recipe-submission" data-rest-nonce="' . wp_create_nonce( 'wp_rest' ) . '" data-guest-mode="' . true . '">' . ob_get_clean() . '</div>';
			return $output;
		} else {
			ob_start();
			echo '<div class="delicious-recipes-error-msg">' . esc_html__( 'Recipe submission is not enabled.', 'delicious-recipes-pro' ) . '</div>';
			return ob_get_clean();
		}
	}

	/**
	 * Add Equipments listing shortcode.
	 *
	 * @param array $atts Shortcode attributes.
	 * @return string
	 */
	public static function recipe_equipments( $atts ) {

		$atts = shortcode_atts(
			array(
				'num_posts' => -1,
			),
			$atts,
			'dr_recipe_equipments'
		);

		// If REST_REQUEST is defined (by WordPress) and is a TRUE, then it's a REST API request.
		$is_rest_route = ( defined( 'REST_REQUEST' ) && REST_REQUEST );
		if (
			( is_admin() && ! $is_rest_route ) || // admin and AJAX (via admin-ajax.php) requests
			( ! is_admin() && $is_rest_route )    // REST requests only
		) {
			return '';
		}

		$global_settings    = delicious_recipes_get_global_settings();
		$enable_disclosure  = isset( $global_settings['enableDisclosureEquipment']['0'] ) && 'yes' === $global_settings['enableDisclosureEquipment']['0'] ? true : false;
		$disclosure_content = isset( $global_settings['affiliateDisclosure'] ) && $global_settings['affiliateDisclosure'] ? $global_settings['affiliateDisclosure'] : '';
		$per_row            = isset( $global_settings['equipmentPerRow'] ) && ! empty( $global_settings['equipmentPerRow'] ) ? $global_settings['equipmentPerRow'] : 3;
		$layout             = isset( $global_settings['equipmentLayout'] ) && ! empty( $global_settings['equipmentLayout'] ) ? $global_settings['equipmentLayout'] : 'list';
		$cat                = get_theme_mod( 'exclude_categories' );
		if ( $cat ) {
			$cat = array_diff( array_unique( $cat ), array( '' ) );
		}

		$args = array(
			'post_type'           => DELICIOUS_RECIPES_EQUIPMENT_POST_TYPE,
			'post_status'         => 'publish',
			'posts_per_page'      => -1 == $atts['num_posts'] ? $atts['num_posts'] : absint( $atts['num_posts'] ),
			'ignore_sticky_posts' => true,
			'category__not_in'    => $cat,
		);

		$recipe_equipments = new WP_Query( $args );
		$filters           = array();
		$sort_filters      = array(
			'latest'    => __( 'Latest', 'delicious-recipes-pro' ),
			'oldest'    => __( 'Oldest', 'delicious-recipes-pro' ),
			'most-used' => __( 'Most Popular', 'delicious-recipes-pro' ),
			'asc'       => __( 'A - Z', 'delicious-recipes-pro' ),
			'desc'      => __( 'Z - A', 'delicious-recipes-pro' ),
		);
		while ( $recipe_equipments->have_posts() ) {
			$recipe_equipments->the_post();
			// get the term_taxonomy of the post.
			$terms = get_the_terms( get_the_ID(), 'equipment-category' );
			if ( $terms ) {
				foreach ( $terms as $term ) {
					// check if the term is already in the filters array.
					$term_exists = false;
					foreach ( $filters as $filter ) {
						if ( $filter['term_id'] == $term->term_id ) {
							$term_exists = true;
							break;
						}
					}
					// if the term is not in the filters array, add it.
					if ( ! $term_exists ) {
						$filters[] = array(
							'term_id'   => $term->term_id,
							'term_name' => $term->name,
							'term_slug' => $term->slug,
						);
					}
				}
			}
		}

		ob_start();

		if ( $enable_disclosure && $disclosure_content ) {
			$data = array(
				'disclosure_content' => $disclosure_content,
			);

			delicious_recipes_pro_get_template( 'affiliate-disclosure.php', $data );
		}
		?>
		<div class="wpd-equipments-container">
			<div class="wpd-equipment-toolbar">
				<div class="wpd-filters-button-group">
					<button class="is-active" type="button" data-filter="*">
						<?php esc_html_e( 'ALL', 'delicious-recipes-pro' ); ?>
					</button>
					<?php
					foreach ( $filters as $filter ) {
						// Ensure term_name exists and is not empty.
						$term_name = isset( $filter['term_name'] ) ? $filter['term_name'] : '';
						?>
						<button type = 'button' data-filter = ".<?php echo esc_attr( $filter['term_slug'] ); ?>">
							<?php echo esc_html( str_replace( '-', ' ', strtoupper( $term_name ) ) ); ?>
						</button>
					<?php } ?>
				</div>
				<div class="wpd-actions-group">
					<div class="wpd-equipment-search">
						<button type="button" id="wpd-equipment-search-btn" class="wpd-equipment-search-btn">
							<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
								<path d="M17.5 17.5083L14.5834 14.5916M16.6667 9.59163C16.6667 13.5037 13.4954 16.675 9.58333 16.675C5.67132 16.675 2.5 13.5037 2.5 9.59163C2.5 5.67962 5.67132 2.5083 9.58333 2.5083C13.4954 2.5083 16.6667 5.67962 16.6667 9.59163Z" stroke="currentColor" stroke-width="1.66667" stroke-linecap="round" stroke-linejoin="round" />
							</svg>
						</button>
						<div class="wpd-equipment-search-field">
							<input type="text" class="wpd-equipment-search-input" placeholder="<?php esc_attr_e( 'Search Equipment', 'delicious-recipes-pro' ); ?>">
						</div>
					</div>
					<div class="wpd-equipment-sort">
						<label for="wpd-sort">
							<?php esc_html_e( 'Sort:', 'delicious-recipes-pro' ); ?>
						</label>
						<select id="wpd-sort" class="wpd-sort" name="wpd-sort">
							<?php foreach ( $sort_filters as $key => $value ) { ?>
								<option value="<?php echo esc_attr( $key ); ?>"><?php echo esc_html( $value ); ?></option>
							<?php } ?>
						</select>
					</div>
					<div class="wpd-equipment-layout-view">
						<button
							type="button"
							class="wpd-equipment-list-view <?php 'list' === $layout ? esc_attr_e( 'is-active', 'delicious-recipes-pro' ) : ''; ?>"
							data-layout="list"
						>
							<svg width="24" height="25" viewBox="0 0 24 25" fill="none" xmlns="http://www.w3.org/2000/svg">
								<path d="M4 10.9937C3.17 10.9937 2.5 11.6637 2.5 12.4937C2.5 13.3237 3.17 13.9937 4 13.9937C4.83 13.9937 5.5 13.3237 5.5 12.4937C5.5 11.6637 4.83 10.9937 4 10.9937ZM4 4.99365C3.17 4.99365 2.5 5.66365 2.5 6.49365C2.5 7.32365 3.17 7.99365 4 7.99365C4.83 7.99365 5.5 7.32365 5.5 6.49365C5.5 5.66365 4.83 4.99365 4 4.99365ZM4 16.9937C3.17 16.9937 2.5 17.6737 2.5 18.4937C2.5 19.3137 3.18 19.9937 4 19.9937C4.82 19.9937 5.5 19.3137 5.5 18.4937C5.5 17.6737 4.83 16.9937 4 16.9937ZM7 19.4937H21V17.4937H7V19.4937ZM7 13.4937H21V11.4937H7V13.4937ZM7 5.49365V7.49365H21V5.49365H7Z" fill="currentColor" />
							</svg>
						</button>
						<button
							type="button"
							class="wpd-equipment-grid-view <?php 'grid' === $layout ? esc_attr_e( 'is-active', 'delicious-recipes-pro' ) : ''; ?>"
							data-layout="grid"
						>
							<svg width="24" height="25" viewBox="0 0 24 25" fill="none" xmlns="http://www.w3.org/2000/svg">
								<path d="M4 8.49365H8V4.49365H4V8.49365ZM10 20.4937H14V16.4937H10V20.4937ZM4 20.4937H8V16.4937H4V20.4937ZM4 14.4937H8V10.4937H4V14.4937ZM10 14.4937H14V10.4937H10V14.4937ZM16 4.49365V8.49365H20V4.49365H16ZM10 8.49365H14V4.49365H10V8.49365ZM16 14.4937H20V10.4937H16V14.4937ZM16 20.4937H20V16.4937H16V20.4937Z" fill="currentColor" />
							</svg>
						</button>
					</div>
				</div>
			</div>
			<div class="wpd-equipments wpd-filter-grid" data-layout="<?php echo esc_attr( $layout ); ?>" data-items="<?php echo esc_attr( $per_row ); ?>">
			<?php
			while ( $recipe_equipments->have_posts() ) {
				$recipe_equipments->the_post();
				delicious_recipes_pro_get_template( 'equipments-grid.php' );
			}
			?>
			</div>
			<div class="wpd-equipment-no-results" style="display: none;">
				<p><?php esc_html_e( 'No equipment found!', 'delicious-recipes-pro' ); ?></p>
			</div>
		</div>
		<?php
		wp_reset_postdata();
		return ob_get_clean();
	}

	/**
	 * Add Affiliate Disclosure shortcode.
	 *
	 * @return string
	 */
	public static function affiliate_disclosure() {
		// If REST_REQUEST is defined (by WordPress) and is a TRUE, then it's a REST API request.
		$is_rest_route = ( defined( 'REST_REQUEST' ) && REST_REQUEST );
		if (
			( is_admin() && ! $is_rest_route ) || // admin and AJAX (via admin-ajax.php) requests
			( ! is_admin() && $is_rest_route )    // REST requests only
		) {
			return '';
		}

		$global_settings    = delicious_recipes_get_global_settings();
		$disclosure_content = isset( $global_settings['affiliateDisclosure'] ) && $global_settings['affiliateDisclosure'] ? $global_settings['affiliateDisclosure'] : '';

		if ( ! $disclosure_content ) {
			return;
		}

		$data = array(
			'disclosure_content' => $disclosure_content,
		);

		delicious_recipes_pro_get_template( 'affiliate-disclosure.php', $data );
	}

	/**
	 * Add My Recipes shortcode.
	 */
	public static function my_recipes() {
		ob_start();
		echo '<div id="dr-pro-urlist" data-rest-nonce="' . wp_create_nonce( 'wp_rest' ) . '"></div>';
		return ob_get_clean();
	}

	/**
	 * Add Favorite Recipes shortcode.
	 */
	public static function favorite_recipes() {
		ob_start();
		delicious_recipes_get_template( 'account/tab-content/wishlist.php' );
		return ob_get_clean();
	}

	/**
	 * Add Browse Recipes shortcode.
	 */
	public static function browse_recipes() {
		ob_start();
		delicious_recipes_get_template( 'account/tab-content/browse.php' );
		return ob_get_clean();
	}

	/**
	 * Add Edit Profile shortcode.
	 */
	public static function edit_profile() {
		ob_start();
		delicious_recipes_get_template( 'account/tab-content/account.php' );
		return ob_get_clean();
	}

	/**
	 * Add Login Page shortcode.
	 */
	public static function login_page() {
		ob_start();
		$global_toggles = delicious_recipes_get_global_toggles_and_labels();

		if ( ! is_user_logged_in() ) {
			// After password reset, add confirmation message.
			if ( ! empty( $_GET['password-reset'] ) ) {
				?>
				<div class="delicious-recipes-success-msg"><?php esc_html_e( 'Your Password has been updated successfully. Please Log in to continue.', 'delicious-recipes-pro' ); ?></div>
				<?php
			}

			if ( isset( $_GET['action'] ) && 'lost-pass' == $_GET['action'] ) {
				// Get lost password form.
				self::lost_password();
			} elseif ( isset( $_GET['register'] ) && $global_toggles['enable_user_registration'] ) {
				// Get user registration.
				delicious_recipes_get_template( 'account/form-registration.php' );
			} else {
				// Get user login.
				delicious_recipes_get_template( 'account/form-login.php' );
			}
		} else {
			// change the URL to the dashboard page.
			wp_redirect( delicious_recipes_get_page_permalink_by_id( delicious_recipes_get_dashboard_page_id() ) );
		}
		return ob_get_clean();
	}
}
