<?php
/**
 * Manager blocks callback
 */

if ( ! function_exists( 'wcv_render_block_store_total_sales' ) ) {
    /**
     * Render store total sales
     *
     * @param array $atts the block attributes.
     *
     * @version 1.8.7
     * @since   1.8.7
     */
    function wcv_render_block_store_total_sales( $atts = array() ) {

        $vendor_id   = wcv_get_store_vendor_id();
        $total_sales = 0;
		if ( ! $vendor_id ) {
			return;
		}
		$total_sales = WCVendors_Pro_Vendor_Controller::get_vendor_sales_count( $vendor_id );

		$args = array(
			'vendor_id'            => $vendor_id,
			'total_sales'          => $total_sales,
			'title'                => $atts['title'],
			'label'                => $atts['label'],
			'display_before_label' => $atts['numberBeforeLabel'],
			'show_label'           => $atts['showLabel'],
		);

		wc_get_template(
			'vendor-total-sale.php',
			$args,
			'wc-vendors/front/',
			WCV_PRO_ABSPATH_TEMPLATES . 'front/'
		);
    }
}

if ( ! function_exists( 'wcv_render_block_store_contact' ) ) {
    /**
     * Render store contact
     *
     * @param array $atts the block attributes.
     *
     * @version 1.8.7
     * @since   1.8.7
     */
    function wcv_render_block_store_contact( $atts = array() ) {

        $vendor_id = wcv_get_store_vendor_id();
        if ( ! $vendor_id ) {
			return;
		}

		$vendor_shop = WCV_Vendors::get_vendor_shop_name( $vendor_id );

		$user            = get_user_by( 'id', $vendor_id );
		$vendor_settings = array_map(
			function( $a ) {
				return $a[0];
			},
			get_user_meta( $vendor_id )
		);

		$args = array(
			'vendor_id'                                 => $vendor_id,
			'vendor_settings'                           => $vendor_settings,
			'user'                                      => $user,
			'vendor_shop'                               => $vendor_shop,
			'title'                                     => $atts['title'],
			'contact_text'                              => $atts['contactText'],
			'show_opening_hours'                        => $atts['showOpeningHours'],
			'show_contact_text'                         => $atts['showContactText'],
			'show_shop_name'                            => $atts['showShopName'],
			'show_phone_number'                         => $atts['showPhone'],
			'show_email_address'                        => $atts['showEmailAddress'],
			'show_hours_after'                          => $atts['showOpeningHoursAfter'],
			'cc_admin'                                  => $atts['ccAdmin'],
			'required_quick_contact_form_subject'       => $atts['requiredQuickContactFormSubject'],
			'required_quick_contact_form_message'       => $atts['requiredQuickContactFormMessage'],
			'required_quick_contact_form_email_address' => $atts['requiredQuickContactFormEmailAddress'],
			'show_shop_url'                             => $atts['showShopUrl'],
			'show_quick_contact_form'                   => $atts['showQuickContactForm'],
		);

		wc_get_template(
			'vendor-quick-contact.php',
			$args,
			'wc-vendors/front/',
			WCV_PRO_ABSPATH_TEMPLATES . 'front/'
		);
    }
}

if ( ! function_exists( 'wcv_render_block_store_categories' ) ) {
	/**
	 * Render store categories
	 *
	 * @param array $atts the block attributes.
	 *
	 * @version 1.8.7
	 * @since   1.8.7
	 */
	function wcv_render_block_store_categories( $atts = array() ) {
		global $wp_query, $post;

		$vendor_id          = wcv_get_store_vendor_id();
		$title              = isset( $atts['title'] ) ? $atts['title'] : '';
		$count              = isset( $atts['showCount'] ) ? $atts['showCount'] : false;
		$hierarchical       = isset( $atts['showHierarchical'] ) ? $atts['showHierarchical'] : false;
		$show_children_only = isset( $atts['showChildrenOnly'] ) ? $atts['showChildrenOnly'] : false;
		$dropdown           = isset( $atts['showAsDropdown'] ) ? $atts['showAsDropdown'] : false;
		$orderby            = isset( $atts['orderBy'] ) ? $atts['orderBy'] : 'order';
		$hide_empty         = isset( $atts['hideEmpty'] ) ? $atts['hideEmpty'] : false;
		$show_globally      = isset( $atts['showOnStore'] ) ? $atts['showOnStore'] : false;
		$dropdown_args      = array( 'hide_empty' => $hide_empty );
		$list_args          = array(
			'show_count'   => $count,
			'hierarchical' => $hierarchical,
			'taxonomy'     => 'product_cat',
			'hide_empty'   => $hide_empty,
		);

		// Menu Order.
		$list_args['menu_order'] = ( 'order' === $orderby ) ? 'asc' : 'title';

		if ( ! $vendor_id && ! $show_globally ) {
			return;
		}

		$vendor_categories = WCVendors_Pro_Vendor_Controller::get_categories( $vendor_id );

		// Only show vendor categories.
		$list_args['include']           = array_keys( $vendor_categories );
		$list_args['vendor_categories'] = $vendor_categories;

		// Setup Current Category.
		$current_cat   = false;
		$cat_ancestors = array();

		if ( is_tax( 'product_cat' ) ) {
			$current_cat   = $wp_query->queried_object;
			$cat_ancestors = get_ancestors( $current_cat->term_id, 'product_cat' );
		} elseif ( is_singular( 'product' ) ) {
			$product_category = wc_get_product_terms( $post->ID, 'product_cat', apply_filters( 'wcvendors-pro_product_categories_widget_product_terms_args', array( 'orderby' => 'parent' ) ) );

			if ( ! empty( $product_category ) ) {
				$current_cat   = end( $product_category );
				$cat_ancestors = get_ancestors( $current_cat->term_id, 'product_cat' );
			}
		}

		// Show Siblings and Children Only.
		if ( $show_children_only && $current_cat ) {
			$top_level       = get_terms(
				'product_cat',
				array(
					'fields'       => 'ids',
					'parent'       => 0,
					'hierarchical' => true,
					'hide_empty'   => false,
				)
			);
			$direct_children = get_terms(
				'product_cat',
				array(
					'fields'       => 'ids',
					'parent'       => $current_cat->term_id,
					'hierarchical' => true,
					'hide_empty'   => false,
				)
			);
			$siblings        = array();

			if ( $cat_ancestors ) {
				foreach ( $cat_ancestors as $ancestor ) {
					$ancestor_siblings = get_terms(
						'product_cat',
						array(
							'fields'       => 'ids',
							'parent'       => $ancestor,
							'hierarchical' => false,
							'hide_empty'   => false,
						)
					);
					$siblings          = array_merge( $siblings, $ancestor_siblings );
				}
			}

			if ( $hierarchical ) {
				$include = array_merge( $top_level, $cat_ancestors, $siblings, $direct_children, array( $current_cat->term_id ) );
			} else {
				$include = $direct_children;
			}

			$dropdown_args['include'] = implode( ',', $include );
			$list_args['include']     = implode( ',', $include );

			if ( empty( $include ) ) {
				return;
			}
		} elseif ( $show_children_only ) {
			$dropdown_args['depth']        = 1;
			$dropdown_args['child_of']     = 0;
			$dropdown_args['hierarchical'] = 1;
			$list_args['depth']            = 1;
			$list_args['child_of']         = 0;
			$list_args['hierarchical']     = 1;
		}
		echo '<div class="wcv wcv_block-store-categories">';
		echo '<h2 class="wcv_block-store_categories__title">' . esc_html( $atts['title'] ) . '</h2>';
		// Dropdown.
		if ( $dropdown ) {
			$dropdown_defaults = array(
				'show_count'         => $count,
				'hierarchical'       => $hierarchical,
				'show_uncategorized' => 0,
				'include'            => array_keys( $vendor_categories ),
				'orderby'            => $orderby,
				'id'                 => 'vendor_category',
				'name'               => 'vendor_category',
				'selected'           => $current_cat ? $current_cat->slug : '',
			);

			$dropdown_args = wp_parse_args( $dropdown_args, $dropdown_defaults );

			// Stuck with this until a fix for https://core.trac.wordpress.org/ticket/13258.
			wc_product_dropdown_categories( apply_filters( 'wcvendors_pro_product_categories_widget_dropdown_args', $dropdown_args ) );

			global $wp;
			$current_page = home_url( $wp->request );

			wc_enqueue_js(
				"
				jQuery( '.dropdown_product_cat' ).change( function() {
					if ( jQuery(this).val() != '' ) {
						var this_page = '';
						var current_page  = '" . esc_js( $current_page ) . "';
						if ( current_page.indexOf( '?' ) > 0 ) {
							this_page = current_page + '&vendor_category=' + jQuery(this).val();
						} else {
							this_page = current_page + '?vendor_category=' + jQuery(this).val();
						}
						location.href = this_page;
					}
				});
			"
			);

			// List.
		} else {
			$list_args['walker']                     = new WCV_Store_Cat_List_Walker();
			$list_args['title_li']                   = '';
			$list_args['pad_counts']                 = 1;
			$list_args['show_option_none']           = __( 'No store categories exist.', 'wcvendors-pro' );
			$list_args['current_category']           = $current_cat ? $current_cat->term_id : '';
			$list_args['current_category_ancestors'] = $cat_ancestors;

			echo '<ul class="store-categories">';
			wp_list_categories( apply_filters( 'wcvendors-pro_store_categories_widget_args', $list_args ) );
			echo '</ul>';
		}
		echo '</div>';
	}
}

if ( ! function_exists( 'wcv_render_block_store_search' ) ) {
	/**
	 * Render store search
	 *
	 * @param array $atts the block attributes.
	 *
	 * @version 1.8.7
	 * @since   1.8.7
	 */
	function wcv_render_block_store_search( $atts = array() ) {
		global $store_search_form_index;

		$vendor_id = wcv_get_store_vendor_id();
		if ( ! $vendor_id ) {
			return;
		}

		if ( empty( $store_search_form_index ) ) {
			$store_search_form_index = 0;
		}

		$title = isset( $atts['title'] ) ? $atts['title'] : '';
		$args  = array(
			'vendor_id' => $vendor_id,
			'index'     => $store_search_form_index++,
			'title'     => $title,
		);
		ob_start();
		wc_get_template(
			'vendor-searchform.php',
			$args,
			'wc-vendors/front/',
			WCV_PRO_ABSPATH_TEMPLATES . 'front/'
		);
		$form = apply_filters( 'get_wcv_store_search_form', ob_get_clean() );

		echo $form; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
	}
}

if ( ! function_exists( 'wcv_render_block_store_recent_products' ) ) {
	/**
	 * Render store recent products
	 *
	 * @param array $atts the block attributes.
	 *
	 * @version 1.8.7
	 * @since   1.8.7
	 */
	function wcv_render_block_store_recent_products( $atts = array() ) {

		$vendor_id = wcv_get_store_vendor_id();

		if ( ! $vendor_id ) {
			return;
		}
		$title          = isset( $atts['title'] ) ? $atts['title'] : __( 'Recent Products', 'wcvendors-pro' );
		$number         = isset( $atts['number'] ) ? $atts['number'] : 5;
		$show_excerpt   = isset( $atts['showExcerpt'] ) ? $atts['showExcerpt'] : false;
		$show_ratings   = isset( $atts['showRating'] ) ? $atts['showRating'] : false;
		$show_image     = isset( $atts['showImage'] ) ? $atts['showImage'] : false;
		$excerpt_length = isset( $atts['excerptLength'] ) ? $atts['excerptLength'] : 20;
		$image_size     = isset( $atts['imageSize'] ) ? $atts['imageSize'] : 'thumbnail';

		$product_args = array(
			'numberposts' => $number,
			'order'       => 'desc',
			'orderby'     => 'date',
			'post_status' => 'publish',
		);
		$products     = WCVendors_Pro_Vendor_Controller::get_products_by_id( $vendor_id, $product_args );

		$args = array(
			'show_image'     => $show_image,
			'show_excerpt'   => $show_excerpt,
			'show_ratings'   => $show_ratings,
			'excerpt_length' => $excerpt_length,
			'image_size'     => $image_size,
			'products'       => $products,
			'title'          => $title,
		);

		wc_get_template(
			'vendor-recent-products.php',
			$args,
			'wc-vendors/front/',
			WCV_PRO_ABSPATH_TEMPLATES . 'front/'
		);
	}
}

if ( ! function_exists( 'wcv_render_block_store_short_description' ) ) {
	/**
	 * Render store short description
	 *
	 * @param array $atts the block attributes.
	 *
	 * @version 1.8.7
	 * @since   1.8.7
	 */
	function wcv_render_block_store_short_description( $atts = array() ) {

		$vendor_id = wcv_get_store_vendor_id();

		if ( ! $vendor_id ) {
			return;
		}

		$short_description = get_user_meta( $vendor_id, 'pv_shop_description', true );
		$title             = isset( $atts['title'] ) ? $atts['title'] : __( 'Short Description', 'wcvendors-pro' );
		$heading           = isset( $atts['heading'] ) ? $atts['heading'] : __( 'Short Description', 'wcvendors-pro' );
		$show_heading      = isset( $atts['showHeading'] ) ? $atts['showHeading'] : false;
		$args              = array(
			'short_description' => $short_description,
			'title'             => $title,
			'heading'           => $heading,
			'show_heading'      => $show_heading,
		);

		wc_get_template(
			'vendor-short-description.php',
			$args,
			'wc-vendors/front/',
			WCV_PRO_ABSPATH_TEMPLATES . 'front/'
		);
	}
}

if ( ! function_exists( 'wcv_render_block_store_ratings' ) ) {
	/**
	 * Render store ratings
	 *
	 * @param array $atts the block attributes.
	 *
	 * @version 1.8.7
	 * @since   1.8.7
	 */
	function wcv_render_block_store_ratings( $atts = array() ) {

		global $post;

		if ( ! is_woocommerce() ) {
			return;
		}

		$vendor_id = wcv_get_store_vendor_id();

		if ( ! isset( $vendor_id ) ) {
			return;
		}

		$number            = isset( $atts['number'] ) ? $atts['number'] : 5;
		$show_customer     = isset( $atts['showCustomer'] ) ? $atts['showCustomer'] : false;
		$show_date         = isset( $atts['showDate'] ) ? $atts['showDate'] : false;
		$show_product      = isset( $atts['showProduct'] ) ? $atts['showProduct'] : false;
		$show_comment      = isset( $atts['showComment'] ) ? $atts['showComment'] : false;
		$title             = isset( $atts['title'] ) ? $atts['title'] : __( 'Store Ratings', 'wcvendors-pro' );
		$show_rating_title = isset( $atts['showRatingTitle'] ) ? $atts['showRatingTitle'] : false;

		$vendor_shop     = urldecode( get_query_var( 'vendor_shop' ) );
		$vendor_id       = WCV_Vendors::get_vendor_id( $vendor_shop );
		$vendor_feedback = WCVendors_Pro_Ratings_Controller::get_vendor_feedback( $vendor_id, $number );

		$args = array(
			'vendor_id'         => $vendor_id,
			'vendor_feedback'   => $vendor_feedback,
			'title'             => $title,
			'show_customer'     => $show_customer,
			'show_date'         => $show_date,
			'show_product'      => $show_product,
			'show_comment'      => $show_comment,
			'number'            => $number,
			'show_rating_title' => $show_rating_title,
		);

		wc_get_template(
			'vendor-store-ratings.php',
			$args,
			'wc-vendors/front/',
			WCV_PRO_ABSPATH_TEMPLATES . 'front/'
		);
	}
}

if ( ! function_exists( 'wcv_render_block_store_social_media' ) ) {
	/**
	 * Render store social media
	 *
	 * @param array $atts the block attributes.
	 *
	 * @version 1.8.7
	 * @since   1.8.7
	 */
	function wcv_render_block_store_social_media( $atts = array() ) {

		$vendor_id = wcv_get_store_vendor_id();

		if ( ! $vendor_id ) {
			return;
		}

		$show_heading    = isset( $atts['showHeading'] ) ? $atts['showHeading'] : false;
		$title           = isset( $atts['title'] ) ? $atts['title'] : __( 'Social Media', 'wcvendors-pro' );
		$heading         = isset( $atts['heading'] ) ? $atts['heading'] : __( 'Like us on social media', 'wcvendors-pro' );
		$icon_size       = isset( $atts['iconSize'] ) ? $atts['iconSize'] : 'sm';
		$social_args     = array(
			'facebook'  => isset( $atts['showFacebook'] ) ? $atts['showFacebook'] : false,
			'twitter'   => isset( $atts['showTwitter'] ) ? $atts['showTwitter'] : false,
			'instagram' => isset( $atts['showInstagram'] ) ? $atts['showInstagram'] : false,
			'pinterest' => isset( $atts['showPinterest'] ) ? $atts['showPinterest'] : false,
			'youtube'   => isset( $atts['showYoutube'] ) ? $atts['showYoutube'] : false,
			'linkedin'  => isset( $atts['showLinkedin'] ) ? $atts['showLinkedin'] : false,
			'snapchat'  => isset( $atts['showSnapchat'] ) ? $atts['showSnapchat'] : false,
			'telegram'  => isset( $atts['showTelegram'] ) ? $atts['showTelegram'] : false,
		);
		$hidden          = array();
		$social_settings = wcv_get_social_media_settings();
		foreach ( $social_settings as $key => $setting ) {
			if ( in_array( $key, $social_args, true ) && ! $social_args[ $key ] ) {
				$hidden[] = $key;
			}
		}

		$args = array(
			'vendor_id'    => $vendor_id,
			'title'        => $title,
			'show_heading' => $show_heading,
			'heading'      => $heading,
			'icon_size'    => $icon_size,
			'hidden'       => $hidden,
		);

		wc_get_template(
			'vendor-store-social-media.php',
			$args,
			'wc-vendors/front/',
			WCV_PRO_ABSPATH_TEMPLATES . 'front/'
		);
	}
}

if ( ! function_exists( 'wcv_render_block_store_map_address' ) ) {
	/**
	 * Render store map address
	 *
	 * @param array $atts the block attributes.
	 *
	 * @version 1.8.7
	 * @since   1.8.7
	 */
	function wcv_render_block_store_map_address( $atts = array() ) {

		$vendor_id = wcv_get_store_vendor_id();

		if ( ! $vendor_id ) {
			return;
		}

		$vendor_settings = array_map(
			function ( $a ) {
					return $a[0];
			},
			get_user_meta( $vendor_id )
		);

		$args = array(
			'address_line1'        => isset( $vendor_settings['_wcv_store_address1'] ) ? $vendor_settings['_wcv_store_address1'] : '',
			'city'                 => isset( $vendor_settings['_wcv_store_city'] ) ? $vendor_settings['_wcv_store_city'] : '',
			'state'                => isset( $vendor_settings['_wcv_store_state'] ) ? $vendor_settings['_wcv_store_state'] : '',
			'post_code'            => isset( $vendor_settings['_wcv_store_postcode'] ) ? $vendor_settings['_wcv_store_postcode'] : '',
			'title'                => isset( $atts['title'] ) ? $atts['title'] : __( 'Store Map and Address', 'wcvendors-pro' ),
			'hide_address'         => isset( $atts['hideAddress'] ) ? $atts['hideAddress'] : false,
			'hide_map'             => isset( $atts['hideMap'] ) ? $atts['hideMap'] : false,
			'show_address_heading' => isset( $atts['showAddressHeading'] ) ? $atts['showAddressHeading'] : false,
			'address_heading'      => isset( $atts['addressHeading'] ) ? $atts['addressHeading'] : __( 'Address', 'wcvendors-pro' ),
			'show_map_heading'     => isset( $atts['showMapHeading'] ) ? $atts['showMapHeading'] : false,
			'map_heading'          => isset( $atts['mapHeading'] ) ? $atts['mapHeading'] : __( 'Map', 'wcvendors-pro' ),
			'map_height'           => isset( $atts['mapHeight'] ) ? $atts['mapHeight'] : '300px',
			'map_width'            => isset( $atts['mapWidth'] ) ? $atts['mapWidth'] : '300px',
			'zoom_level'           => isset( $atts['zoomLevel'] ) ? $atts['zoomLevel'] : 15,
			'maps_api_key'         => isset( $atts['apiKey'] ) ? $atts['apiKey'] : get_option( 'wcvendors_pro_google_maps_api_key' ),
			'vendor_settings'      => $vendor_settings,
		);
		wc_get_template(
			'vendor-store-map-address.php',
			$args,
			'wc-vendors/front/',
			WCV_PRO_ABSPATH_TEMPLATES . 'front/'
		);
	}
}

if ( ! function_exists( 'wcv_render_block_store_price_filter' ) ) {
	/**
	 * Render store price filter
	 *
	 * @param array $atts the block attributes.
	 *
	 * @version 1.8.7
	 * @since   1.8.7
	 */
	function wcv_render_block_store_price_filter( $atts = array() ) {

		$vendor_id = wcv_get_store_vendor_id();

		if ( ! $vendor_id ) {
			return;
		}
		$min_price = wcv_get_vendor_product_min_price( $vendor_id );
		$max_price = wcv_get_vendor_product_max_price( $vendor_id );

		if ( is_null( $min_price ) || is_null( $max_price ) ) {
			return;
		}

		if ( $min_price === $max_price ) {
			return;
		}

		$args = array(
			'vendor_id'         => $vendor_id,
			'title'             => isset( $atts['title'] ) ? $atts['title'] : __( 'Price Filter', 'wcvendors-pro' ),
			'rail_color'        => isset( $atts['railColor'] ) ? $atts['railColor'] : '#eaeaea',
			'track_color'       => isset( $atts['trackColor'] ) ? $atts['trackColor'] : '#eaeaea',
			'handle_color'      => isset( $atts['handleColor'] ) ? $atts['handleColor'] : '#f58220',
			'show_apply_button' => isset( $atts['showApplyButton'] ) ? $atts['showApplyButton'] : false,
			'min_price'         => $min_price,
			'max_price'         => $max_price,

		);

		wc_get_template(
			'vendor-store-price-filter.php',
			$args,
			'wc-vendors/front/',
			WCV_PRO_ABSPATH_TEMPLATES . 'front/'
		);
	}
}

if ( ! function_exists( 'wcv_render_block_store_attributes_filter' ) ) {
	/**
	 * Render store attributes filter
	 *
	 * @param array $atts the block attributes.
	 *
	 * @version 1.9.0
	 * @since   1.9.0
	 */
	function wcv_render_block_store_attributes_filter( $atts = array() ) {

		$vendor_id = wcv_get_store_vendor_id();

		if ( ! $vendor_id ) {
			return;
		}

		$selected_attributes = isset( $atts['selectedAttributes'] ) ? $atts['selectedAttributes'] : array();
		$attributes          = wcv_get_vendor_store_product_attributes( $vendor_id, $selected_attributes );

		if ( ! $attributes || empty( $attributes ) ) {
			return;
		}

		$args = array(
			'vendor_id'  => $vendor_id,
			'title'      => isset( $atts['title'] ) ? $atts['title'] : __( 'Attributes Filter', 'wcvendors-pro' ),
			'attributes' => $attributes,
		);

		wc_get_template(
			'vendor-store-attributes-filter.php',
			$args,
			'wc-vendors/front/',
			WCV_PRO_ABSPATH_TEMPLATES . 'front/'
		);
	}
}

if ( ! function_exists( 'wcv_render_block_store_ratings_filter' ) ) {
	/**
	 * Render store ratings filter
	 *
	 * @param array $atts the block attributes.
	 *
	 * @version 1.8.7
	 * @since   1.8.7
	 */
	function wcv_render_block_store_ratings_filter( $atts = array() ) {

		$vendor_id = wcv_get_store_vendor_id();

		if ( ! $vendor_id ) {
			return;
		}

		$ratings = wcv_get_vendor_product_ratings( $vendor_id );

		$args = array(
			'vendor_id'        => $vendor_id,
			'title'            => isset( $atts['title'] ) ? $atts['title'] : __( 'Ratings Filter', 'wcvendors-pro' ),
			'show_count'       => isset( $atts['showCount'] ) ? $atts['showCount'] : false,
			'show_as_dropdown' => isset( $atts['showAsDropdown'] ) ? $atts['showAsDropdown'] : false,
			'ratings'          => $ratings,
		);

		wc_get_template(
			'vendor-store-ratings-filter.php',
			$args,
			'wc-vendors/front/',
			WCV_PRO_ABSPATH_TEMPLATES . 'front/'
		);
	}
}
