<?php
/**
 * Shortcode attributes
 * @var $data
 * @var $posts_per_page
 * @var $orderby
 * @var $pagination
 */
if (!function_exists('yolo_shortcode_product_masonry')) {

    function yolo_shortcode_product_masonry($atts)
    {
        global $woocommerce_loop, $woocommerce;
        wp_enqueue_script('yolo-vendor-isotope');
        wp_enqueue_script('yolo-loadmore');
        wp_enqueue_script('yolo_product_masonry');
        if (is_front_page() || is_home()) {
            $paged = (get_query_var('paged')) ? get_query_var('paged') : ((get_query_var('page')) ? get_query_var('page') : 1);
        } else {
            $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
        }
        extract(shortcode_atts(array(
            'per_page'      => '12',
            'columns'       => '2',
            'orderby'       => 'date',
            'order'         => 'asc',
            'ms_align'      => 'center',
            'pagination'    => 'page_num',
            'show_hide'     => 'true',
            'category'      => ''
        ), $atts));
        ob_start();
        ?>
        <div class="product-masonry masonry">
            <?php
            $ordering_args = $woocommerce->query->get_catalog_ordering_args($orderby, $order);
            $meta_query = $woocommerce->query->get_meta_query();
            $args = array(
                'post_type' => 'product',
                'post_status' => 'publish',
                'ignore_sticky_posts' => 1,
                'orderby' => $ordering_args['orderby'],
                'order' => $ordering_args['order'],
                'posts_per_page' => $per_page,
                'meta_query' => $meta_query,
                'paged' => $paged
            );

            if (!empty($category) && $category != 'all') {
                $args['tax_query'] = array(
                    array(
                        'taxonomy' => 'product_cat',
                        'terms' => array_map('sanitize_title', explode(',', $category)),
                        'field' => 'term_id',
                        'operator' => 'IN'
                    )
                );
            }

            if (isset($ordering_args['meta_key'])) {
                $args['meta_key'] = $ordering_args['meta_key'];
            }

            ob_start();
            $products = new WP_Query($args);
            $woocommerce_loop['columns'] = $columns;

            if ($products->have_posts()) : ?>
                <div class="masonry-filters">
                    <ul data-option-key="filter" class="ms-<?php echo esc_attr($ms_align); ?>">
                        <li>
                            <a class="selected" href="#" data-option-value="*"><?php echo __('All', 'yolo-kidzone') ?></a>
                        </li>
                        <?php
                        if (!empty($category) && $category != 'all') {
                            $category_arr = array_filter(explode(',', $category));
                            foreach ((array)$category_arr as $cat):
                                if ($cat == 'all')
                                    continue;

                                $category = get_term_by('id', $cat, 'product_cat');
                                ?>
                                <li>
                                    <a href="#"
                                       data-option-value=".<?php echo 'mansonry-filter-' . $category->slug ?>"><?php echo esc_html($category->name); ?></a>
                                </li>
                                <?php
                            endforeach;
                        } else {
                            if ($product_categories = get_terms('product_cat')) {

                                foreach ((array)$product_categories as $product_category) {
                                    ?>
                                    <li>
                                        <a href="#"
                                           data-option-value=".<?php echo 'mansonry-filter-' . $product_category->slug ?>"><?php echo esc_html($product_category->name); ?></a>
                                    </li>
                                    <?php
                                }
                            }
                        }
                        ?>
                        <?php if( $show_hide == 'true' ) {?>
                            <li class="bt-order"><?php echo esc_html_e('Sort by', 'yolo-kidzone'); ?></li>
                        <?php }?>
                    </ul>
                </div>

                <?php if( $show_hide == 'true' ) {?>
                    <div class="isotope-sort ms-<?php echo esc_attr($ms_align); ?>">
                        <ul class="list-sort">
                            <li data-sort-by="title" class="active"><?php echo esc_html_e('Title','yolo-kidzone');?></li>
                            <li data-sort-by="price"><?php echo esc_html_e('Price','yolo-kidzone');?></li>
                            <li data-sort-by="onsale"><?php echo esc_html_e('Onsale','yolo-kidzone');?></li>
                        </ul>
                        <div class="asc-desc">
                            <select class="select-asc-desc" name="asc-desc">
                                <option value="true" <?php if($order == 'asc'){echo 'selected="selected"';}?>><?php echo esc_html_e('ASC','yolo-kidzone');?></option>
                                <option value="false" <?php if($order == 'desc'){echo 'selected="selected"';}?>><?php echo esc_html_e('DESC','yolo-kidzone');?></option>
                            </select>
                        </div>
                    </div>
                <?php }?>
                <div class="shop-container">
                    <div class="yolo-row infinite-scroll"
                         data-paginate="<?php if (isset($pagination) && $pagination == 'infinite_scroll') {
                             echo 'infinite_scroll';
                         } ?>">
                        <ul class="products masonry-container grid yolo-row <?php if (isset($pagination) && $pagination == 'infinite_scroll') {
                            echo 'masonry-wrap infinite-scroll-wrap';
                        } ?>">
                            <?php while ($products->have_posts()) : $products->the_post();
                                global $product, $post; ?>

                                <?php
                                // Store loop count we're currently on
                                if (empty($woocommerce_loop['loop']))
                                    $woocommerce_loop['loop'] = 0;

                                // Store column count for displaying the grid
                                if (empty($woocommerce_loop['columns']))
                                    $woocommerce_loop['columns'] = apply_filters('loop_shop_columns', 4);

                                // Ensure visibility
                                if (!$product || !$product->is_visible())
                                    return;

                                // Increase loop count
                                $woocommerce_loop['loop']++;

                                // Extra post classes
                                $classes = array();
                                $classes[] = 'loadmore-item masonry-item yolo-md-' . (12 / $columns) . '  yolo-sm-6 yolo-xs-12 yolo-product-item infinite-scroll-item';
                                $cat_class = array();
                                if (is_object_in_taxonomy($post->post_type, 'product_cat')) {
                                    foreach ((array)get_the_terms($post->ID, 'product_cat') as $cat) {
                                        if (empty($cat->slug))
                                            continue;
                                        $cat_class[] = 'mansonry-filter-' . $cat->slug;
                                    }
                                }
                                $cat_class = implode(' ', $cat_class);
                                $classes[] = $cat_class;
                                ?>
                                <li <?php post_class($classes); ?>>
                                    <?php do_action('woocommerce_before_shop_loop_item'); ?>
                                    <div class="yolo-product-inner">
                                        <div class="woo-thumbnail">
                                            <?php
                                            /**
                                             * woocommerce_before_shop_loop_item_title hook
                                             *
                                             * @hooked woocommerce_show_product_loop_sale_flash - 10
                                             * @hooked woocommerce_template_loop_product_thumbnail - 10
                                             */
                                            do_action('woocommerce_before_shop_loop_item_title');
                                            ?>
                                            <div class="yolo-product-meta">
                                                <div class="rating">
                                                    <?php do_action('yolo_rating'); ?>
                                                </div>
                                                <div class="entry-cart-meta">
                                                    <?php

                                                    /**
                                                     * woocommerce_after_shop_loop_item hook
                                                     *
                                                     * @hooked woocommerce_template_loop_add_to_cart - 10
                                                     */
                                                    do_action('woocommerce_after_shop_loop_item');

                                                    ?>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="yolo-product-footer clearfix">
                                            <h3><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h3>
                                            <?php
                                            /**
                                             * woocommerce_after_shop_loop_item_title hook
                                             *
                                             * @hooked woocommerce_template_loop_rating - 5
                                             * @hooked woocommerce_template_loop_price - 10
                                             */
                                            do_action('woocommerce_after_shop_loop_item_title');
                                            ?>
                                        </div>
                                    </div>
                                </li>

                            <?php endwhile; // end of the loop. ?>

                        </ul>
                    </div>
                </div>
            <?php if (1 < $products->max_num_pages): ?>
                <div class="loadmore-action">
                    <?php if ($pagination == 'loadmore') : ?>
                        <a href="#" class="btn-loadmore btn-primary"
                           title="<?php _e('Load More', 'yolo-kidzone') ?>"><?php _e('Load More', 'yolo-kidzone') ?></a>
                    <?php endif; ?>
                    <div class="loadmore-loading" style="display: block;">
                        <div class="fade-loading"><i class="fa fa-refresh fa-spin"></i></div>
                    </div>
                </div>
                <div class="<?php echo 'yolo_' . esc_attr($pagination); ?>"
                     style="<?php if ($pagination == 'page_num') {
                         echo 'display: block;';
                     } else {
                         echo 'display:none;';
                     } ?>">
                    <?php yolo_pagination(array(), $products) ?>
                </div>
            <?php endif; ?>
                <script type="text/javascript">
                    jQuery(document).ready(function ($) {

                        /*Click filter*/
                        $('.bt-order').click(function(){
                            $('.isotope-sort').slideToggle(300);
                            $(this).toggleClass('active');
                        });

                        var show_hide = <?php echo esc_attr($show_hide);?>;
                        // init Isotope
                        var $container = $('.masonry-container').isotope({
                            itemSelector: '.masonry-item',
                            layoutMode: 'fitRows',
                            getSortData: {
                                title: '.yolo-product-footer h3 a',
                                price: function (itemElem) {
                                    var weight = $(itemElem).find('.price ins .amount').text();
                                    var weight2 = $(itemElem).find('.price .amount').text();
                                    if (weight) {
                                        weight = parseFloat(weight.replace(/\$/g, ''));
                                    } else if (weight2) {
                                        weight2 = parseFloat(weight2.replace(/\$/g, ''));
                                        weight = weight2;
                                    } else {
                                        weight = 0;
                                    }
                                    return weight;
                                },
                                onsale: function (itemElem) {
                                    var onsale = $(itemElem).find('.onsale').text();
                                    return onsale;
                                }
                            }
                        });

                        if(show_hide == true){
                            var sortByValue = '';
                            // bind sort button click
                            $('.isotope-sort .list-sort li').click(function () {
                                var selected = $('.select-asc-desc option[selected="selected"]').val();
                                if(selected == 'false'){
                                    selected = false;
                                }
                                sortByValue = $(this).attr('data-sort-by');
                                $('.list-sort li').removeClass('active');
                                $(this).addClass('active');
                                $container.isotope({
                                    sortBy: sortByValue,
                                    sortAscending: selected
                                });
                            });
                            /* select asc or desc*/
                            $('.select-asc-desc').change(function(){
                                var selected = $(this).val();
                                $(this).find('option').removeAttr('selected');
                                $('.select-asc-desc option').each(function(){
                                    if(selected == $(this).val()){
                                        $(this).attr('selected','selected');
                                    }
                                });
                                if(selected == 'false'){
                                    selected = false;
                                }
                                $container.isotope({
                                    sortBy: sortByValue,
                                    sortAscending: selected
                                });
                            });
                            /* default*/
                            var default_selected = $('.select-asc-desc option[selected="selected"]').val();
                            if(default_selected == 'false'){
                                default_selected = false;
                            }
                            $container.isotope({
                                sortAscending: default_selected
                            });
                        }
                    });
                </script>
            <?php endif;

            woocommerce_reset_loop();
            wp_reset_query();

            $return = ob_get_clean();
            echo $return;
            $woocommerce->query->remove_ordering_args();
            ?>
        </div>
        <?php
        return ob_get_clean();
    }

    add_shortcode('yolo_product_masonry', 'yolo_shortcode_product_masonry');

}
?>