<?php
class NBT_Color_Swatches_Frontend {
	/**
	 * Class constructor.
	 */
	public function __construct() {

		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
		add_action('woocommerce_before_add_to_cart_form', array($this, 'is_single_product') );
		add_filter('woocommerce_is_attribute_in_product_name', array($this, 'woocommerce_is_attribute_in_product_name'), 20, 2 );

		add_filter( 'body_class', array($this, 'nbt_body_classes'), 10, 1 );
	}
	
	public function nbt_body_classes( $classes ) {
		global $post, $pm_settings;

		if(isset($post) && get_post_meta($post->ID, '_color_swatches', true) == 'on'){
			$classes[] = 'has-color_swatches';
		}
	     
	    return $classes;  
	}
	
	public function woocommerce_is_attribute_in_product_name($attribute, $name){
		return false;
	}
	public function is_single_product(){
		global $product;
		
		if(get_post_meta($product->get_id(), '_color_swatches', true) == 'on'){
			add_filter( 'woocommerce_dropdown_variation_attribute_options_html', array( $this, 'get_swatch_html' ), 100, 2 );
			add_filter( 'nbtcs_swatch_html', array( $this, 'swatch_html' ), 5, 4 );
			add_filter( 'nbtcs_swatch_html_custom', array( $this, 'custom_swatch_html' ), 5, 3 );
		}
	}
	/**
	 * Enqueue scripts and stylesheets
	 */
	public function enqueue_scripts() {
		if( !defined('PREFIX_NBT_SOL') ){
			wp_enqueue_style( 'frontend-nbtcs', NBT_CS_URL . 'assets/css/frontend.css'  );
			wp_enqueue_script( 'frontend-nbtcs', NBT_CS_URL . 'assets/js/frontend.js', null, null, true );
			wp_localize_script( 'frontend-nbtcs', 'nbt_solutions', array(
				'ajax_url' => admin_url( 'admin-ajax.php' )
			));		
		}

	}

	/**
	 * Filter function to add swatches bellow the default selector
	 *
	 * @param $html
	 * @param $args
	 *
	 * @return string
	 */
	public function get_swatch_html( $html, $args ) {
		global $product;

		$swatch_css = '';
		$settings = get_option('color-swatches_settings');
		if( $settings ) {
			$width_swatches = $settings['wc_'.NBT_Solutions_Color_Swatches::$plugin_id.'_width'];

			if( $width_swatches ) {
				$width_swatches_lineheight = $width_swatches - 1;
				$swatch_css .= "width: {$width_swatches}px; height: {$width_swatches}px;line-height:{$width_swatches_lineheight}px;";
			}
		}
		$args['swatch_css'] = $swatch_css;


		

		if(preg_match('/< *select[^>]*id *= *["\']?([^"\']*)/i', $html, $matches)){

			$attr_id = trim($matches[1]);

			/* If have custom attributes */
			$swatch_types = NBT_Solutions_Color_Swatches::$types;
			$attr         = NBT_Solutions_Color_Swatches::get_tax_attribute( $attr_id );
			if($_cs_type = get_post_meta($product->get_id(), '_cs_type', TRUE)) {
				$_cs_type = $_cs_type[$attr_id];

	
				
				$get_attributes = $product->get_attributes( 'edit' );
				if( isset($get_attributes[$attr_id]) ){
					$_attribute = $get_attributes[$attr_id];


					$attribute = $_cs_type['type'];

					if ( $_attribute->is_taxonomy() && ( $attribute_taxonomy = $_attribute->get_taxonomy_object() ) ) :
						$terms = $_attribute->get_terms();
						//$attribute = $attribute_taxonomy->attribute_type;
					else :
						

						$value_array = $_attribute->get_options();
						$array = array();

						foreach ($value_array as $key => $value) {
							$array[] = array(
								'term_id' => $key,
								'taxonomy' => $attr_id,
								'name' => trim($value),
								'slug' => trim($value),
								'is_taxonomy' => false
							);
						}
						$terms = json_decode(json_encode($array), FALSE);
						$attr = new stdClass();
						$attr->attribute_type = $attribute;
						$attr->attribute_name = $attr_id;


						$selected = isset( $_REQUEST[ 'attribute_' . $attr_id ] ) ? wc_clean( stripslashes( urldecode( $_REQUEST[ 'attribute_' . $attr_id ] ) ) ) : '';

						$args = array('selected' => $selected);
					endif;

					$args['style'] = $_cs_type['style'];


					$class     = "variation-selector variation-select-{$attribute}";
					$swatches  = '';

					$args['attribute'] = $attribute;
					if ( array_key_exists( $attribute, $swatch_types ) ) {
						
						if($attribute == 'radio'){
							$swatches .= '<ul class="swatches-radio">';
						}

						$i = 0;
						$args['data_alt'] = $_cs_type;
						foreach ( $terms as $term ) {
							$args['key'] = $i;
							$swatches .= apply_filters( 'nbtcs_swatch_html', '', $term, $attr, $args );
							$i++;
						}

						if($attribute == 'radio'){
							$swatches .= '</ul>';
						}

					}


				}

			}else{

				// Return if this is normal attribute
				if ( empty( $attr ) ) {
					return $html;
				}

				if ( ! array_key_exists( $attr->attribute_type, $swatch_types ) ) {
					return $html;
				}

				$options   = $args['options'];
				$attribute = $args['attribute'];
				$class     = "variation-selector variation-select-{$attr->attribute_type}";
				$swatches  = '';

				if ( empty( $options ) && ! empty( $product ) && ! empty( $attribute ) ) {
					$attributes = $product->get_variation_attributes();
					$options    = $attributes[$attribute];
				}



				if ( array_key_exists( $attr->attribute_type, $swatch_types ) ) {

					if ( ! empty( $options ) && $product && taxonomy_exists( $attribute ) ) {
						// Get terms if this is a taxonomy - ordered. We need the names too.
						$terms = wc_get_product_terms( $product->get_id(), $attribute, array( 'fields' => 'all' ) );


						if($attr->attribute_type == 'radio'){
							$swatches .= '<ul class="swatches-radio">';
						}
						$i = 0;
						foreach ( $terms as $term ) {
							if ( in_array( $term->slug, $options ) ) {
								$swatches .= apply_filters( 'nbtcs_swatch_html', '', $term, $attr, $args );
							}
							$i++;
						}
						if($attr->attribute_type == 'radio'){
							$swatches .= '</ul>';
						}
					}
				}
			}
		}

				if ( ! empty( $swatches ) ) {
					$class .= ' hidden';

					$swatches = '<div class="nbtcs-swatches" data-attribute_name="attribute_' . esc_attr( $attribute ) . '" data-cs_name="'. strtolower( $_attribute->get_name() ) .'">' . $swatches . '</div>';
					$html     = '<div class="' . esc_attr( $class ) . '">' . $html . '</div>' . $swatches;
				}
		return $html;
	}

	/**
	 * Print HTML of a single swatch
	 *
	 * @param $html
	 * @param $term
	 * @param $attr
	 * @param $args
	 *
	 * @return string
	 */
	public function swatch_html( $html, $term, $attr, $args ) {

		$selected = sanitize_title( $args['selected'] ) == $term->slug ? ' selected' : '';
		$checked = $args['selected'] == $term->slug ? ' checked' : '';
		$name     = esc_html( apply_filters( 'woocommerce_variation_option_name', $term->name ) );


		$style = '';
		if(isset($args['style']) && isset(NBT_Solutions_Color_Swatches::get_style()[$args['style']])){
			$style = $args['style'];
		}


		switch ( $args['attribute'] ) {
			case 'color':
				$color = get_term_meta( $term->term_id, 'color', true );
				if(isset($args['data_alt']['value']) && $args['data_alt']['value']){
					$color = $args['data_alt']['value'][$args['key']];
				}
				list( $r, $g, $b ) = sscanf( $color, "#%02x%02x%02x" );
				$html = sprintf(
					'<span class="%s swatch swatch-color swatch-%s%s" style="background-color:%s;color:%s;%s" title="%s" data-value="%s">%s</span>',
					$style,
					esc_attr( $term->slug ),
					$selected,
					esc_attr( $color ),
					"rgba($r,$g,$b,0.5)",
					$args['swatch_css'],
					esc_attr( $name ),
					esc_attr( $term->slug ),
					$name
				);
				break;

			case 'image':
				$image = get_term_meta( $term->term_id, 'image', true );
				if(isset($args['data_alt']['value']) && $args['data_alt']['value']){
					$image = $args['data_alt']['value'][$args['key']];
				}
				$image = $image ? wp_get_attachment_image_src( $image ) : '';
				$image = $image ? $image[0] : WC()->plugin_url() . '/assets/images/placeholder.png';
				$html  = sprintf(
					'<span class="%s swatch swatch-image swatch-%s%s" title="%s" data-value="%s" style="%s"><img src="%s" alt="%s">%s</span>',
					$style,
					esc_attr( $term->slug ),
					$selected,
					esc_attr( $name ),
					esc_attr( $term->slug ),
					$args['swatch_css'],
					esc_url( $image ),
					esc_attr( $name ),
					esc_attr( $name )
				);
				break;

			case 'radio':
				if(!isset($term->is_taxonomy)){
					$name = $term->slug;
				}
				$label = get_term_meta( $term->term_id, 'radio', true );
				$label = $label ? $label : $name;
				$html  = sprintf(
					'<li><input type="radio" name="nbt_cs_%s" value="%s" id="%s_%d"%s>
					<label for="%s_%d" class="swatch swatch-radio" title="%s" data-value="%s"> %s</label><div class="check %s"></div></li>',
					$attr->attribute_name,
					esc_attr( $name ),
					$attr->attribute_name,
					$term->term_id,
					$checked,
					$attr->attribute_name,
					$term->term_id,
					esc_attr( $term->slug ),
					esc_attr( $name ),
					esc_attr( $term->name ),
					$style
				);
				break;
			case 'label':
				if(!isset($term->is_taxonomy)){
					$name = $term->slug;

				}
				$label = get_term_meta( $term->term_id, 'radio', true );
				$label = $label ? $label : $name;
				$html  = sprintf(
					'<span class="swatch swatch-text %s" title="%s" data-value="%s" style="%s">%s</span>',
					$style,
					esc_attr( $name ),
					esc_attr( $name ),
					$args['swatch_css'],
					esc_attr( $term->name )
				);
				break;
		}
		return $html;
	}
}
new NBT_Color_Swatches_Frontend();