<?php
// Exit if accessed directly
if (!defined('ABSPATH'))
    exit;

if (class_exists("WPBakeryShortCode")) {
// Element Class 
class NB_Element_Brands_By_Category extends WPBakeryShortCode {
     
    // Element Init
    function __construct() {
        add_action( 'init', array( $this, 'vc_mapping' ) );
        add_shortcode( 'netbase_brands_by_category', array( $this, 'shortcode_brands_by_category' ) );
    }
     
    // Element Mapping
    public function vc_mapping() {
         
        // Stop all if VC is not enabled
        if ( !defined( 'WPB_VC_VERSION' ) ) {
            return;
        }
        if ( class_exists( 'WooCommerce' ) ) {
            $args = array(
                    'type' => 'post',
                    'child_of' => 0,
                    'parent' => '',
                    'orderby' => 'parent',
                    'order' => 'ASC',
                    'hide_empty' => false,
                    'hierarchical' => 1,
                    'exclude' => '',
                    'include' => '',
                    'number' => '',
                    'taxonomy' => 'product_cat',
                    'pad_counts' => false,
            );
            $categories = get_categories( $args );
            $product_categories_dropdown[] = array(
                    'label' => 'All categories',
                    'value' => '',
            );
            $this->getCategoryChildsFull( 0, 0, $categories, 0, $product_categories_dropdown );
                
            $attributes_tax = wc_get_attribute_taxonomies();
            $attributes = array();
            foreach ( $attributes_tax as $attribute ) {
                $attributes[ $attribute->attribute_label ] = $attribute->attribute_name;
            }
        }
         
        // Map the block with vc_map()
        vc_map( array(
            'name'        => esc_html__( 'NB - Get Brands by Category Product', 'nb-fw' ),
            'base'        => 'netbase_brands_by_category',
            'icon' => 'icon-wpb-wp',
            'category' => __('Netbase Elements', 'nb-fw'),
            'description' => esc_html__( 'Display heading.', 'nb-fw' ),

            'params'      => array(
                array(
                        'type'          => 'textfield',
                        'heading'       => esc_html__( 'Block title', 'nb-fw' ),
                        'param_name'    => 'title',
                        'admin_label'   => true,
                        'value'         => '',
                        'description'   => ''
                    ),

                array(
                            'type' => 'dropdown',
                            'heading' => esc_html__( 'Category', 'nb-fw' ),
                            'value' => $product_categories_dropdown,
                            'param_name' => 'category',
                            'admin_label'   => true,
                            'save_always' => true,
                            'description' => esc_html__( 'Product category list', 'nb-fw' ),

                ),
                array(
                        'type' => 'textfield',
                        'heading' => esc_html__( 'Show Per page', 'nb-fw' ),
                        'value' => 12,
                        'save_always' => true,
                        'admin_label'   => true,
                        'param_name' => 'per_page',
                        'description' => esc_html__( 'How many brand to show on the page', 'nb-fw' ),
                    ),
                array(
                        'type' => 'dropdown',
                        'heading' => esc_html__( 'Columns', 'nb-fw' ),
                        'value' => array(
                            '1' => '1',
                            '2' => '2',
                            '3' => '3',
                            '4' => '4',                            
                            '6' => '6',
                        ),
                        'std' => '6',
                        'param_name' => 'column',
                        'admin_label'   => true,
                        'save_always' => true,                       
                        
                    ),
                
                array(
                        'type' => 'dropdown',
                        'heading' => __('Item Align', 'nb-fw'),
                        'param_name' => 'item_align',                        
                        'value' => array(
                                'Center' => 'text-center',
                                'Right' => 'text-right',
                                'Left' => 'text-left',
                                
                        ),
                        'std' => 'text-center',
                        'save_always' => true,                            
                ),                
            )
        ) );                               
        
    }     
     
    // Element HTML
    public function shortcode_brands_by_category($atts, $content = null)
    {
        $html = $attr_parent = '';

        // Extract shortcode parameters.
        extract(
            shortcode_atts(
                array(
                    'title'         => '',                    
                    'per_page'  => '',
                    'column'   => 6,
                    'category' => '',
                    'item_align' => 'text-center',
                ),
                $atts
            )
        );

        $id = uniqid('netbase_custom_css_');
        $classes = array();

        switch ($column) {
            case '1':
                $classes[] = 'vc_col-md-12';
                break;
            case '2':
                $classes[] = 'vc_col-md-6';
                break;
            case '3':
                $classes[] = 'vc_col-md-4 vc_col-sm-3 vc_col-xs-6';
                break;
            case '4':
                $classes[] = 'vc_col-md-3 vc_col-sm-3 vc_col-xs-6';
                break;
            case '6':
                $classes[] = 'vc_col-md-2 vc_col-sm-3 vc_col-xs-6';
                break;
            default:
                $classes[] = 'vc_col-md-2 vc_col-sm-3 vc_col-xs-6';
                break;
        }
        if($item_align){
             $classes[] = $item_align;
        }

        $per_page = absint($per_page);        

        $ipage=0;        
        $brandids = $this->getBrandsList($category); 
        
        ob_start();

        foreach ($brandids as  $brands) {
            if($brands):
                if((isset($per_page) && $per_page !=0 && $ipage < $per_page) || (isset($per_page) && $per_page ==0)){
                    $brand_thumb_id = get_woocommerce_term_meta($brands, 'brands_thumbnail', true);
                    $slug = get_term_by('id', $brands, 'nbproduct_brand');                            
                    ?>
                    <div class="brand-item <?php echo esc_attr( implode( ' ', $classes ) ) ; ?>">
                        <a href="<?php echo get_term_link($slug->slug, 'nbproduct_brand'); ?>">
                           <img src="<?php echo wp_get_attachment_image_url($brand_thumb_id) ?>" alt="brand" />
                        </a>
                    </div>

            <?php                        
                $ipage++;
                }
                    
            endif;
        }           

        $html .= '<div id="' . esc_attr($id) . '" class="nb-fw list-brands row ">' . ob_get_clean() . '</div>';
        
        // End HTML code.
        wp_reset_postdata();
        return apply_filters('netbase_shortcode_brands_by_category', force_balance_tags($html));
    }

    public function getBrandsList($category){
        $product_list = array();        
        global $post, $product;
        $args = array( 
                    'post_type' => 'product',                    
                    'product_cat' => $category,
                    'post_status'           => 'publish',
                    'ignore_sticky_posts'  => 1, 
                    'posts_per_page'       => -1
        );
        $query_post = new WP_Query( $args );

        if( $query_post->have_posts() ){
            while( $query_post->have_posts() ){
                $query_post->the_post();
                $product_list[] = $post->ID;
            }
        }
        
        $brand_list = array();
         
        if($product_list){

            foreach ($product_list as $product_id){
                if($product_id){
                    $product_list_brand[] = wp_get_post_terms($product_id, 'nbproduct_brand', array("fields" => "ids"));
                }                
            }
            if($product_list_brand){
                $return_array_data = array();
                  foreach($product_list_brand as $args_index=>$args_data){
                    if(is_array($args_data) || is_object($args_data)){
                    $return_array_data = array_merge($return_array_data,$args_data);
                    }
                }                     
            }

            $brand_list =  array_unique($return_array_data);            
            
        }
        return $brand_list;
        
    }
    protected function getCategoryChildsFull( $parent_id, $pos, $array, $level, &$dropdown ) {
            for ( $i = $pos; $i < count( $array ); $i ++ ) {
                if ( $array[ $i ]->category_parent == $parent_id ) {
                    $name = str_repeat( '- ', $level ) . $array[ $i ]->name;
                    $value = $array[ $i ]->slug;
                    $dropdown[] = array(
                        'label' => $name,
                        'value' => $value,
                    );
                    $this->getCategoryChildsFull( $array[ $i ]->term_id, $i, $array, $level + 1, $dropdown );
                }
            }
        }
     
} // End Element Class
 
 
// Element Class Init
new NB_Element_Brands_By_Category(); 
}
