<?php

/**
 * Modules | Slider Swiper
 *
 * @package Dotspice
 * @version 1.3.0
 */


if (defined('DOTSPICE_SLIDER_SWIPER_ENABLE') && DOTSPICE_SLIDER_SWIPER_ENABLE) {

	/**
	 * Slider Swiper | Admin | Post Type
	 */
	function dotspice_ss_post_type($post_types)
	{
		$post_types[] = array(
			'post_type'          => 'slider-swiper',
			'menu_name'          => esc_html__('Sliders', 'dotspice'),
			'singular_name'      => esc_html__('Slider', 'dotspice'),
			'multiple_name'      => esc_html__('Sliders', 'dotspice'),
			'show_in_menu'       => 'theme-settings',
			'public'             => false,
			'publicly_queryable' => false,
			'menu_icon'          => 'dashicons-images-alt',
			'supports'           => array('title')
		);

		return $post_types;
	}
	add_filter('dotspice_cpt', 'dotspice_ss_post_type');


	/**
	 * Slider Swiper | Admin | Scortcode
	 */
	function dotspice_ss_get_shortcode($post_id)
	{
		if (!empty($post_id)) {
			$shortcode = '[slider-swiper id="' . $post_id . '"]';

			echo '<span class="shortcode wp-ui-highlight"><input type="text"'
				. ' onfocus="this.select();" readonly="readonly"'
				. ' value="' . esc_attr($shortcode) . '"'
				. ' class="large-text code" /></span>';
		}
	}


	/**
	 * Slider Swiper | Admin | After Title
	 */
	function dotspice_ss_add_shortcode_after_title($post)
	{
		if ($post->post_type === 'slider-swiper') {
			dotspice_ss_get_shortcode($post->ID);
		}
	}
	add_action('edit_form_after_title', 'dotspice_ss_add_shortcode_after_title');


	/**
	 * Slider Swiper | Admin | Post Type Columns
	 */
	function dotspice_ss_add_columns($columns)
	{
		$columns = array_slice($columns, 0, 2, true) + array('shortcode' => __('Shortcode', 'dotspice')) + array_slice($columns, 2, count($columns) - 2, true);

		if (isset($columns['pur'])) {
			unset($columns['pur']);
		}

		return $columns;
	}
	add_filter('manage_slider-swiper_posts_columns', 'dotspice_ss_add_columns', 99);

	function dotspice_ss_manage_columns($column_name, $post_id)
	{
		if ($column_name == 'shortcode') {
			dotspice_ss_get_shortcode($post_id);
		}
		return $column_name;
	}
	add_filter('manage_slider-swiper_posts_custom_column', 'dotspice_ss_manage_columns', 10, 2);


	/**
	 * Slider Swiper | Shortcode
	 */
	function dotspice_ss_shortcode($atts)
	{
		if (is_feed()) {
			return '[slider-swiper]';
		}
		if (!class_exists('acf_pro')) {
			return '[slider-swiper 404 "Advanced Custom Fields PRO"]';
		}

		$atts = shortcode_atts(array(
			'id' => 0
		), $atts);
		$query_error_message = false;

		// Post
		$post_ID = (int) $atts['id'];
		$post    = get_post($post_ID);

		if (empty($post_ID)) {
			return '[slider-swiper 404 "ID"]';
		}
		if (empty($post)) {
			return '[slider-swiper 404 "post"]';
		}
		if ($post->post_status != 'publish') {
			return '[slider-swiper post_status "' . esc_attr($post->post_status) . '"]';
		}
		if ($post->post_type != 'slider-swiper') {
			return '[slider-swiper post_type "' . esc_attr($post->post_type) . '"]';
		}

		// Slider
		$slider_type  = get_field('slider_type', $post_ID);
		$slides_field = ($slider_type != 'default') ? '_' . $slider_type : '';
		$slides       = get_field('slides' . $slides_field, $post_ID);
		$classes      = array('swiper-slider', 'swiper-container', $post->post_name, 'type-' . $slider_type);
		$slide_ID     = 'swiper-' . $post->post_name;

		if (!is_array($slides) || count($slides) <= 0) {
			return '[slider-swiper 404 "slides"]';
		}

		// Settings
		$settings = get_field('settings', $post_ID);
		$params   = array(
			'slidesPerView' => !empty($settings['per_view']) ? (float) $settings['per_view'] : 1,
			'spaceBetween'  => !empty($settings['space_between']) ? (int) $settings['space_between'] : 0,
			'loop'          => !empty($settings['loop']) ? (bool) $settings['loop'] : false,
			'speed'         => !empty($settings['speed']) ? (int) $settings['speed'] : 300,
			'loopAdditionalSlides' => 5
		);

		// Settings | Autoplay
		if (!empty($settings['autoplay'])) {
			$params['autoplay'] = array(
				'delay' => (int) $settings['autoplay'],
			);
		}

		// Settings | Effect
		$effect_field     = ($params['slidesPerView'] > 1) ? 'effect_multiple' : 'effect';
		$params['effect'] = !empty($settings[$effect_field]) ? esc_attr($settings[$effect_field]) : 'slide';

		// Settings | Breakpoints
		if ($params['slidesPerView'] > 1) {
			$classes[] = 'grid';
			$per_view  = $params['slidesPerView'];
			$per_view_lg = !empty($settings['per_view_lg']) ? (float) $settings['per_view_lg'] : 1;
			$per_view_md = !empty($settings['per_view_md']) ? (float) $settings['per_view_md'] : 1;
			$per_view_sm = !empty($settings['per_view_sm']) ? (float) $settings['per_view_sm'] : 1;

			$params['slidesPerView'] = $per_view_sm;
			$params['breakpoints'] = array(
				'576' => array(
					'slidesPerView' => $per_view_md,
				),
				'768' => array(
					'slidesPerView' => $per_view_lg,
				),
				'992' => array(
					'slidesPerView' => $per_view,
				),
			);

			// Hidden elems Fix
			$params['observer'] = true;
			$params['observeParents'] = true;
		}

		// Settings | Navigation
		if (!empty($settings['navigation'])) {
			$params['navigation'] = array(
				'nextEl' => '.' . esc_attr($slide_ID) . '-button-next',
				'prevEl' => '.' . esc_attr($slide_ID) . '-button-prev'
			);
		}

		// Settings | Scrollbar
		if (!empty($settings['scrollbar']) && !$settings['loop']) {
			$params['scrollbar'] = array(
				'el'        => '.' . esc_attr($slide_ID) . '-scrollbar',
				'draggable' => true
			);
		}

		// Settings | Pagination
		if (!empty($settings['pagination']) && $settings['pagination'] != 'none') {
			$params['pagination'] = array(
				'el'        => '.' . esc_attr($slide_ID) . '-pagination',
				'clickable' => true,
				'type'      => esc_attr($settings['pagination'])
			);
		}

		// Settings | Auto Height
		if (!in_array($slider_type, array('default', 'custom'))) {
			$params['autoHeight'] = true;
		}

		ob_start();
?>
		<div class="swiper-box">
			<div id="<?php echo esc_attr($slide_ID); ?>" class="<?php echo implode(' ', $classes); ?>">
				<div class="swiper-wrapper">
					<?php
					$count   = 1;
					$add_css = '';

					switch ($slider_type) {


							// Posts
						case 'post':
							$args = array(
								'post_type'      => 'post',
								'post_status'    => 'publish',
								'posts_per_page' => get_field('per_page', $post_ID),
							);

							// Taxonomies
							if ($slides_type == 'taxonomy') {
								$slides_tax = !empty($slides['taxonomy']) ? $slides['taxonomy'] : array();

								$args['tax_query'] = array(
									array(
										'taxonomy' => 'category',
										'field'    => 'term_id',
										'terms'    => wp_parse_id_list($slides_tax),
									),
								);
							}

							// Custom
							if ($slides_type == 'custom') {
								$slides_posts     = !empty($slides['custom']) ? $slides['custom'] : array();
								$args['post__in'] = wp_parse_id_list($slides_posts);
								$args['orderby']  = 'post__in';
							}

							$query = new WP_Query($args);

							if ($query->have_posts()) {
								while ($query->have_posts()) : $query->the_post();
					?><div class="swiper-slide slide slide-<?php echo esc_attr($count); ?>"><?php
																									get_template_part('templates/content');
																									?></div><?php

														$count++;
													endwhile;
												} else {
													$query_error_message = 'posts';
												}

												wp_reset_postdata();
												break;


												// Products
											case 'product':
												if (class_exists('woocommerce')) {
													$slides_type = !empty($slides['type']) ? $slides['type'] : '';
													$args        = array(
														'post_type'      => esc_attr($slider_type),
														'posts_per_page' => get_field('per_page', $post_ID),
														'post_status'    => 'publish',
													);

													// Featured
													if ($slides_type == 'featured') {
														$args['post__in'] = wp_parse_id_list(wc_get_featured_product_ids());
													}

													// Best Selling
													if ($slides_type == 'best_selling') {
														$args['meta_key'] = 'total_sales';
														$args['order']    = 'DESC';
														$args['orderby']  = 'meta_value_num';
													}

													// Taxonomies
													if ($slides_type == 'taxonomy') {
														$slides_tax = !empty($slides['taxonomy']) ? $slides['taxonomy'] : array();

														$args['tax_query'] = array(
															array(
																'taxonomy' => 'product_cat',
																'field'    => 'term_id',
																'terms'    => wp_parse_id_list($slides_tax),
															),
														);
													}

													// Custom
													if ($slides_type == 'custom') {
														$slides_posts     = !empty($slides['custom']) ? $slides['custom'] : array();
														$args['post__in'] = wp_parse_id_list($slides_posts);
													}

													// Sort
													if (!empty($args['post__in'])) {
														$args['orderby']  = 'post__in';
													}

													$query = new WP_Query($args);

													if ($query->have_posts()) {
														while ($query->have_posts()) : $query->the_post();
														?><div class="swiper-slide slide slide-<?php echo esc_attr($count); ?>"><?php
																										wc_get_template_part('content', 'product');
																										?></div><?php

															$count++;
														endwhile;
													} else {
														$query_error_message = 'products';
													}

													wp_reset_postdata();
												}
												break;


												// Product Categories
											case 'product_cat':
												if (class_exists('woocommerce')) {
													$slides_type = !empty($slides['type']) ? $slides['type'] : '';
													$args        = array(
														'taxonomy'   => array('product_cat'),
														'number'     => get_field('per_page', $post_ID),
														'hide_empty' => false
													);

													// Taxonomies
													if ($slides_type == 'custom') {
														$slides_tax = !empty($slides['taxonomy']) ? $slides['taxonomy'] : array();

														$args['include'] = wp_parse_id_list($slides_tax);
														$args['orderby'] = 'include';
													}

													$categories = get_terms($args);

													if (!empty($categories)) {
														foreach ($categories as $category) {
															?><div class="swiper-slide slide slide-<?php echo esc_attr($count); ?>"><?php
																										wc_get_template('content-product_cat.php', array('category' => $category));

																										$count++;
																										?></div><?php
														}
													}
												}
												break;


												// Default | Custom
											default:
												foreach ($slides as $slide) :
															?>
								<div class="swiper-slide slide slide-<?php echo esc_attr($count); ?>">
									<?php get_template_part('includes/modules/slider-swiper/templates/template', $slider_type, $slide); ?>
								</div>
					<?php

													if (!empty($slide['bg_image']) || !empty($slide['bg_color'])) {
														$add_css .= '#' . esc_attr($slide_ID) . ' .slide-' .  esc_attr($count) . '{';
														$add_css .= !empty($slide['bg_image']) ? 'background-image: url("' . $slide['bg_image'] . '");' : '';
														$add_css .= !empty($slide['bg_color']) ? 'background-color: ' . $slide['bg_color'] . ';' : '';
														$add_css .= '}';
													}

													$count++;
												endforeach;
												break;
										}
					?>
				</div>
			</div>

			<?php
			// Disable slider, when count of slides < slidesPerView
			if (isset($params['breakpoints']['992']['slidesPerView'])) {
				if (intval($params['breakpoints']['992']['slidesPerView']) > ($count - 1)) {
					$params['loop'] = false;
					$settings['navigation'] = false;
				}
			}
			?>

			<?php
			if (!empty($settings['navigation'])) :
				$navigation_btn = !empty($settings['navigation_btn']) ? $settings['navigation_btn'] : 'default';
				$btn_left       = '';
				$btn_right      = '';
				$btn_style      = false;

				switch ($navigation_btn) {
					case 'none':
						break;

					case 'default':
						$btn_left  = 'slider-left';
						$btn_right = 'slider-right';
						$btn_style = false;
						break;

					default:
						$btn_data  = explode('-', $navigation_btn);
						$btn_left  = $btn_data[0] . '-left';
						$btn_right = $btn_data[0] . '-right';

						if (isset($btn_data[1])) {
							$btn_left  .= '-' . $btn_data[1];
							$btn_right .= '-' . $btn_data[1];
						}
						if (isset($btn_data[2])) {
							$btn_left  .= '-' . $btn_data[2];
							$btn_right .= '-' . $btn_data[2];
						}
						break;
				}

			?>
				<div class="container">
					<div class="swiper-button swiper-button-prev <?php echo esc_attr($slide_ID); ?>-button-prev"><?php echo (!empty($btn_left)) ? dotspice_get_svg_icon($btn_left, 'html', array('style' => $btn_style)) : ''; ?></div>
					<div class="swiper-button swiper-button-next <?php echo esc_attr($slide_ID); ?>-button-next"><?php echo (!empty($btn_right)) ? dotspice_get_svg_icon($btn_right, 'html', array('style' => $btn_style)) : ''; ?></div>
				</div>
			<?php
			endif;
			?>

			<?php if (!empty($settings['scrollbar']) && !$settings['loop']) : ?>
				<div class="swiper-scrollbar <?php echo esc_attr($slide_ID); ?>-scrollbar"></div>
			<?php endif; ?>

			<?php if (!empty($settings['pagination']) && $settings['pagination'] != 'none') : ?>
				<div class="swiper-pagination <?php echo esc_attr($slide_ID); ?>-pagination"></div>
			<?php endif; ?>
		</div>
<?php
		$slider_html = ob_get_clean();

		// Check WP_Query
		if (!empty($query_error_message)) {
			return '[slider-swiper 404 "' . esc_attr($query_error_message) . '"]';
		}

		// Enqueue Scripts
		wp_enqueue_script('swiper-bundle', get_template_directory_uri() . '/includes/modules/slider-swiper/js/swiper-bundle.min.js', array('jquery'), '', true);

		// Enqueue Dynamic Scripts
		add_action('wp_footer', function () use ($slide_ID, $params) {
			wp_add_inline_script('swiper-bundle', 'new Swiper( "#' . esc_attr($slide_ID) . '" , ' . json_encode($params) . ');');
		});

		// Enqueue Styles
		wp_enqueue_style('swiper-bundle', get_template_directory_uri() . '/includes/modules/slider-swiper/css/swiper-bundle.min.css', array(), null);

		// Enqueue Dynamic Styles
		if (!empty($add_css)) {
			wp_add_inline_style('swiper-bundle', dotspice_minify_css($add_css));
		}


		// Output
		return $slider_html;
	}
	add_shortcode('slider-swiper', 'dotspice_ss_shortcode');
}
