<?php

namespace PeggiCore\CPT\Shortcodes\ProductCategory;

use PeggiCore\Lib;

class ProductCategory implements Lib\ShortcodeInterface
{
    private $base;

    function __construct()
    {
        $this->base = 'qodef_product_category';

        add_action('vc_before_init', array($this, 'vcMap'));

        //Product id filter
        add_filter('vc_autocomplete_qodef_product_category_category_callback', array(&$this, 'productCategoryAutocompleteSuggester',), 10, 1);

        //Product id render
        add_filter('vc_autocomplete_qodef_product_category_category_render', array(&$this, 'productCategoryAutocompleteRender',), 10, 1);
    }

    public function getBase()
    {
        return $this->base;
    }

    public function vcMap()
    {
        if (function_exists('vc_map')) {
            vc_map(
                array(
                    'name' => esc_html__('Select Product Category', 'peggi'),
                    'base' => $this->getBase(),
                    'category' => esc_html__('by PEGGI', 'peggi'),
                    'icon' => 'icon-wpb-product-category extended-custom-icon',
                    'allowed_container_element' => 'vc_row',
                    'params' => array(
                        array(
                            'type' => 'autocomplete',
                            'param_name' => 'category',
                            'heading' => esc_html__('Selected Product Category', 'peggi'),
                            'settings' => array(
                                'sortable' => true,
                                'unique_values' => true
                            ),
                            'admin_label' => true,
                            'save_always' => true,
                            'description' => esc_html__('If you left this field empty then product ID will be of the current page', 'peggi')
                        ),
                        array(
                            'type' => 'attach_image',
                            'param_name' => 'category_image',
                            'heading' => esc_html__('Category Image', 'peggi')
                        ),
                        array(
                            'type'       => 'dropdown',
                            'param_name' => 'category_image_size',
                            'heading'    => esc_html__( 'Image Size', 'peggi' ),
                            'value'      => array(
                                esc_html__( 'Default', 'peggi' )        => '',
                                esc_html__( 'Original', 'peggi' )       => 'full',
                                esc_html__( 'Square', 'peggi' )         => 'peggi_qodef_square',
                                esc_html__( 'Landscape', 'peggi' )      => 'peggi_qodef_landscape',
                                esc_html__( 'Portrait', 'peggi' )       => 'peggi_qodef_portrait',
                                esc_html__( 'Medium', 'peggi' )         => 'medium',
                                esc_html__( 'Large', 'peggi' )          => 'large'
                            )
                        ),
                        array(
                            'type'       => 'dropdown',
                            'param_name' => 'title_tag',
                            'heading'    => esc_html__('Title Tag', 'peggi'),
                            'value'      => array_flip(peggi_select_get_title_tag(true, array('p' => 'p', 'span' => 'span'))),
                            'description'=> esc_html__('Set title tag for category title element', 'peggi'),
                        ),
                        array(
                            'type'       => 'textfield',
                            'param_name' => 'custom_link',
                            'heading'    => esc_html__('Custom Link', 'peggi'),
                            'save_always'=> true
                        ),
                        array(
                            'type'       => 'dropdown',
                            'param_name' => 'custom_link_target',
                            'heading'    => esc_html__( 'Custom Link Target', 'peggi' ),
                            'value'      => array_flip( peggi_select_get_link_target_array() ),
                            'dependency' => Array( 'element' => 'image_behavior', 'value' => array( 'custom-link' ) )
                        ),
                        array(
                            'type'       => 'dropdown',
                            'param_name' => 'skin',
                            'heading'    => esc_html__('Category Info Skin', 'peggi'),
                            'value'      => array(
                                esc_html__('Default', 'peggi') => '',
                                esc_html__('Light', 'peggi') => 'light-skin',
                            )
                        )
                    )
                )
            );
        }
    }

    /**
     * Renders shortcodes HTML
     *
     * @param $atts array of shortcode params
     * @param $content string shortcode content
     * @return string
     */
    public function render($atts, $content = null)
    {
        $args = array(
            'category'           => '',
            'category_image'     => '',
            'category_image_size'=> 'full',
            'skin'               => '',
            'title_tag'          => 'span',
            'custom_link'        => '',
            'custom_link_target' => '_self'
        );

        $params = shortcode_atts($args, $atts);
        extract($params);

        $params['category_image_size'] = ! empty( $params['category_image_size'] ) ? $params['category_image_size'] : $args['category_image_size'];
        $params['title_tag'] = !empty($params['title_tag']) ? $params['title_tag'] : $args['title_tag'];
        $params['custom_link_target'] = ! empty( $params['custom_link_target'] ) ? $params['custom_link_target'] : $args['custom_link_target'];

        $html = $html = peggi_select_get_woo_shortcode_module_template_part( 'templates/product-category', 'product-category', '', $params );

        return $html;
    }

    /**
     * Filter product category
     *
     * @param $query
     *
     * @return array
     */
    public function productCategoryAutocompleteSuggester($query)
    {
        global $wpdb;

        $post_meta_infos = $wpdb->get_results($wpdb->prepare("SELECT a.slug AS slug, a.name AS product_category_title
					FROM {$wpdb->terms} AS a
					LEFT JOIN ( SELECT term_id, taxonomy  FROM {$wpdb->term_taxonomy} ) AS b ON b.term_id = a.term_id
					WHERE b.taxonomy = 'product_cat' AND a.name LIKE '%%%s%%'", stripslashes($query)), ARRAY_A);

        $results = array();
        if (is_array($post_meta_infos) && !empty($post_meta_infos)) {
            foreach ($post_meta_infos as $value) {
                $data = array();
                $data['value'] = $value['slug'];
                $data['label'] = ((strlen($value['product_category_title']) > 0) ? esc_html__('Category', 'peggi') . ': ' . $value['product_category_title'] : '');
                $results[] = $data;
            }
        }

        return $results;

    }

    /**
     * Find product category
     * @since 4.4
     *
     * @param $query
     *
     * @return bool|array
     */
	public function productCategoryAutocompleteRender( $query ) {
		$query = trim( $query['value'] ); // get value from requested
		if ( ! empty( $query ) ) {
			
			$product_category = get_term_by( 'name', $query, 'product_cat' );
			if ( is_object( $product_category ) ) {
				$product_category_slug  = $product_category->slug;
				$product_category_title = $product_category->name;
				
				$product_category_title_display = '';
				if ( ! empty( $product_category_title ) ) {
					$product_category_title_display = esc_html__( 'Category', 'peggi' ) . ': ' . $product_category_title;
				}
				
				$data          = array();
				$data['value'] = $product_category_slug;
				$data['label'] = $product_category_title_display;
				
				return ! empty( $data ) ? $data : false;
			}
			
			return false;
		}
		
		return false;
	}
}