<?php

/**
 * Check if WooCommerce is active
 **/
if ( !class_exists( 'WooCommerce' ) ) {
	return;
}

/**
 * WooCommerce Grid / List Toggle Class
 **/
if ( ! class_exists( 'Utech_WC_List_Grid' ) ) {

	class Utech_WC_List_Grid {

		public function __construct() {
			// Hooks
			add_action( 'wp' , array( $this, 'setup_grid_list_view_button' ) , 20);
		}

		// Setup
		function setup_grid_list_view_button() {
			if ( is_shop() || is_product_category() || is_product_tag() || is_product_taxonomy() ) {
				add_action( 'wp_enqueue_scripts', array( $this, 'utech_gridlist_setup_scripts_styles' ), 20);
				add_action( 'wp_enqueue_scripts', array( $this, 'utech_gridlist_setup_scripts_script' ), 20);
				add_action( 'utech_girdlist_view_toggle', array( $this, 'utech_gridlist_toggle_button' ), 30);
			}
		}

		// styles
		function utech_gridlist_setup_scripts_styles() {
			wp_enqueue_style( 'utech-woo-grid-list', UTECH_ROOT_URI . '/woocommerce/assets/css/woo-list-grid.css', array(), UTECH_VERSION );
			wp_enqueue_style( 'dashicons' );
		}

		// Scripts
		function utech_gridlist_setup_scripts_script() {
			wp_enqueue_script( 'cookie', UTECH_ROOT_URI . '/woocommerce/assets/js/jquery.cookie.min.js', array('jquery'), UTECH_VERSION );
			wp_enqueue_script( 'grid-list-scripts', UTECH_ROOT_URI . '/woocommerce/assets/js/jquery.gridlistview.min.js', array('jquery'), UTECH_VERSION );
			add_action( 'wp_footer', array( $this, 'utech_gridlist_set_default_view' ) );
		}

		// Toggle button
		function utech_gridlist_toggle_button() {

			$grid_view = __( 'Grid view', 'utech' );
			$list_view = __( 'List view', 'utech' );

			$output = sprintf( 
				'<nav class="gridlist__view__toggle">
					<a href="#" id="grid" title="%1$s"><span class="dashicons dashicons-grid-view"></span> <em>%1$s</em></a>
					<a href="#" id="list" title="%2$s"><span class="dashicons dashicons-exerpt-view"></span> <em>%2$s</em></a>
				</nav>',
				$grid_view,
				$list_view 
			);

			echo apply_filters( 'utech_gridlist_toggle_button_output', $output, $grid_view, $list_view );
		}

		// Set Default Active
		function utech_gridlist_set_default_view() {
			$default = get_theme_mod( 'wc_glt_default_format', 'grid' );
			?>
				<script>
				if ( 'function' == typeof(jQuery) ) {
					jQuery(document).ready(function($) {
						if ($.cookie( 'gridcookie' ) == null) {
							$( 'ul.products' ).addClass( '<?php echo esc_attr($default); ?>' );
							$( '.gridlist__view__toggle #<?php echo esc_attr($default); ?>' ).addClass( 'active' );
						}
					});
				}
				</script>
			<?php
		}

	}

	$Utech_WC_List_Grid = new Utech_WC_List_Grid();
}

