<?php

namespace WooSwatches;

use function WooSwatchesPro\is_license_valid;

defined( 'ABSPATH' ) || exit;

class Term_Meta {

	private $taxonomy;
	private $post_type;
	private $fields = array();

	public function __construct( $taxonomy, $post_type, $fields ) {
		$this->taxonomy  = $taxonomy;
		$this->post_type = $post_type;
		$this->fields    = $fields;

		add_action( "{$this->taxonomy}_add_form_fields", array( $this, 'add_fields' ) );
		add_action( "{$this->taxonomy}_edit_form_fields", array( $this, 'edit_fields' ) );
		add_action( 'created_term', array( $this, 'save_fields' ), 10, 3 );
		add_action( 'edit_term', array( $this, 'save_fields' ), 10, 3 );

		// Columns
		add_filter( "manage_edit-{$this->taxonomy}_columns", array( $this, 'taxonomy_columns' ) );
		add_filter( "manage_{$this->taxonomy}_custom_column", array( $this, 'taxonomy_column_preview' ), 10, 3 );
	}

	public function add_fields() {
		$this->generate_attr_fields();
	}

	public function edit_fields( $term ) {
		$this->generate_attr_fields( $term );
	}

	public function generate_attr_fields( $term = false ) {
		$curr_screen = get_current_screen();

		if ( ( $curr_screen->post_type == $this->post_type ) && ( $curr_screen->taxonomy == $this->taxonomy ) ) {
			self::form_fields( $this->fields, $term );
		}
	}

	public function save_fields( $term_id, $id = '', $taxonomy = '' ) {
		if ( $taxonomy == $this->taxonomy ) {
			foreach ( $this->fields as $field ) {

				if ( ! is_pro_active() ) {
					$pro_fields = ['isdu_c', '_shw_tlp', '_tlp_txt'];
					if ( in_array( $field['id'], $pro_fields ) ) continue;
				}

				foreach ( $_POST as $post_key => $post_value ) {
					if ( $field['id'] == $post_key ) {
						switch ( $field['type'] ) {
							case 'text':
							case 'color':
								$post_value = esc_html( $post_value );
								break;
							case 'url':
								$post_value = esc_url( $post_value );
								break;
							case 'image':
								$post_value = absint( $post_value );
								break;
							case 'select':
							case 'select2':
								$post_value = sanitize_key( $post_value );
								break;
							case 'checkbox':
								$post_value = sanitize_key( $post_value );
								break;
						}
						update_term_meta( $term_id, $field['id'], $post_value );
					}
				}
			}
		}
	}

	public function taxonomy_columns( $columns ) {
		$new_columns = array();

		if ( isset( $columns['cb'] ) ) {
			$new_columns['cb'] = $columns['cb'];
		}

		$new_columns['gs-meta-preview'] = '';

		if ( isset( $columns['cb'] ) ) {
			unset( $columns['cb'] );
		}

		// if ( woo_variation_swatches()->is_pro() ) {
		// $columns[ 'wvs-meta-group' ] = esc_html__( 'Group', 'woo-variation-swatches' );
		// }

		return array_merge( $new_columns, $columns );
	}

	public function taxonomy_column_preview( $columns, $column, $term_id ) {
		if ( 'gs-meta-preview' !== $column ) {
			return $columns;
		}

		$attribute = Helpers::get_attribute_taxonomy( $this->taxonomy );

		$attribute_type = $attribute->attribute_type;

		$this->preview( $attribute_type, $term_id, $this->fields );

		return $columns;
	}

	public function preview( $attribute_type, $term_id, $fields ) {
		$meta_key = $fields[0]['id'];

		$this->color_preview( $attribute_type, $term_id, $meta_key );
		$this->image_preview( $attribute_type, $term_id, $meta_key );
	}

	public function color_preview( $attribute_type, $term_id, $key ) {
		if ( 'color' === $attribute_type ) {
			$primary_color   = sanitize_hex_color( get_term_meta( $term_id, $key, true ) );

			if ( is_pro_active() && is_license_valid() ) {
				
				$is_dual_color   = wc_string_to_bool( get_term_meta( $term_id, 'is_dual_color', true ) );
				$secondary_color = sanitize_hex_color( get_term_meta( $term_id, 'secondary_color', true ) );

				if ( $is_dual_color ) {
					$angle = '-45deg';
					printf( '<div class="gs-preview gs-color-preview gs-dual-color-preview" style="background: linear-gradient(%3$s, %1$s 0%%, %1$s 50%%, %2$s 50%%, %2$s 100%%);"></div>', esc_attr( $secondary_color ), esc_attr( $primary_color ), esc_attr( $angle ) );
				} else {
					printf( '<div class="gs-preview gs-color-preview" style="background-color:%s;"></div>', esc_attr( $primary_color ) );
				}

			} else {

				printf( '<div class="gs-preview gs-color-preview" style="background-color:%s;"></div>', esc_attr( $primary_color ) );

			}
		}
	}

	public function image_preview( $attribute_type, $term_id, $key ) {
		if ( 'image' == $attribute_type ) {
			$attachment_id = absint( get_term_meta( $term_id, $key, true ) );
			$image         = wp_get_attachment_image_src( $attachment_id, 'thumbnail' );

			if ( is_array( $image ) ) {
				printf( '<img src="%s" alt="" width="%d" height="%d" class="gs-preview gs-image-preview" />', esc_url( $image[0] ), $image[1], $image[2] );
			}
		}
	}

	public static function form_fields( $fields, $term ) {
		if ( empty( $fields ) ) {
			return;
		}

		foreach ( $fields as $field ) {
			$field['id'] = esc_html( $field['id'] );

			if ( ! $term ) {
				$field['value'] = isset( $field['default'] ) ? $field['default'] : '';
			} else {
				$field['value'] = get_term_meta( $term->term_id, $field['id'], true );
			}

			$field['size']        	= isset( $field['size'] ) ? $field['size'] : '40';
			$field['required']    	= ( isset( $field['required'] ) and $field['required'] == true ) ? ' aria-required="true"' : '';
			$field['placeholder'] 	= ( isset( $field['placeholder'] ) ) ? ' placeholder="' . $field['placeholder'] . '" data-placeholder="' . $field['placeholder'] . '"' : '';
			$field['desc']        	= ( isset( $field['desc'] ) ) ? $field['desc'] : '';
			$field['dependency']  	= ( isset( $field['dependency'] ) ) ? $field['dependency'] : array();
			$field['disabled'] 		= ( isset( $field['is_pro_field'] ) && $field['is_pro_field'] ) ? 'disabled' : '';

			self::top_part( $field, $term );

			switch ( $field['type'] ) {
				case 'text':
				case 'url':
					ob_start();
					?>
					<input <?php echo esc_attr($field['disabled']); ?> name="<?php echo esc_attr($field['id']); ?>" id="<?php echo esc_attr($field['id']); ?>" type="<?php echo esc_attr($field['type']); ?>" value="<?php echo esc_attr($field['value']); ?>" size="<?php echo esc_attr($field['size']); ?>" <?php echo esc_attr($field['required']) . esc_attr($field['placeholder']); ?>>
					<?php
					echo ob_get_clean();
					break;

				case 'image':
					ob_start();

					?>
					<div class="gs-meta-image-wrapper">
						<div class="image-preview">
							<img data-placeholder="<?php echo esc_url( self::placeholder_img_src() ); ?>" src="<?php echo esc_url( self::get_img_src( $field['value'] ) ); ?>" width="60px" height="60px"/>
						</div>
						<div class="button-wrapper">
							<input type="hidden" id="<?php echo esc_attr($field['id']); ?>" name="<?php echo esc_attr($field['id']); ?>" value="<?php echo esc_attr( $field['value'] ); ?>"/>
							<button type="button" class="gs_upload_image_button button button-primary button-small"><?php esc_html_e( 'Upload / Add image', 'gs-woo-variation' ); ?></button>
							<button type="button" style="<?php echo( empty( $field['value'] ) ? 'display:none' : '' ); ?>" class="gs_remove_image_button button button-danger button-small"><?php esc_html_e( 'Remove image', 'gs-woo-variation' ); ?></button>
						</div>
					</div>
				
					<?php
					echo ob_get_clean();
					break;

				case 'color':
					ob_start();
					?>
					<input <?php echo esc_attr($field['disabled']); ?> name="<?php echo esc_attr($field['id']); ?>" id="<?php echo esc_attr($field['id']); ?>" type="text" class="gs-color-picker" value="<?php echo esc_attr($field['value']); ?>" data-default-color="<?php echo esc_attr($field['value']); ?>" size="<?php echo esc_attr($field['size']); ?>" <?php echo esc_attr($field['required']) . esc_attr($field['placeholder']); ?>>
					<?php
					echo ob_get_clean();
					break;

				case 'select':
				case 'select2':
					$field['options']  = isset( $field['options'] ) ? $field['options'] : array();
					$field['multiple'] = isset( $field['multiple'] ) ? ' multiple="multiple"' : '';
					$css_class = ( $field['type'] == 'select2' ) ? 'wc-enhanced-select' : '';

					ob_start();
					?>
					<select <?php echo esc_attr($field['disabled']); ?> name="<?php echo esc_attr($field['id']); ?>" id="<?php echo esc_attr($field['id']); ?>" class="<?php echo esc_attr($css_class); ?>" <?php echo esc_attr($field['multiple']); ?>>
						<?php
						foreach ( $field['options'] as $key => $option ) {
							echo '<option' . selected( $field['value'], $key, false ) . ' value="' . esc_attr($key) . '">' . esc_html($option) . '</option>';
						}
						?>
					</select>
					<?php
					echo ob_get_clean();
					break;

				case 'text':
				case 'url':
					ob_start();
					?>
					<input <?php echo esc_attr($field['disabled']); ?> name="<?php echo esc_attr($field['id']); ?>" id="<?php echo esc_attr($field['id']); ?>" type="<?php echo esc_attr($field['type']); ?>" value="<?php echo esc_attr($field['value']); ?>" size="<?php echo esc_attr($field['size']); ?>" <?php echo esc_attr($field['required']) . esc_attr($field['placeholder']); ?>>
					<?php
					echo ob_get_clean();
					break;

				case 'checkbox':
					ob_start();
					?>
					<label for="<?php echo esc_attr( $field['id'] ); ?>">
						<input <?php echo esc_attr($field['disabled']); ?> name="<?php echo esc_attr($field['id']); ?>" id="<?php echo esc_attr($field['id']); ?>" <?php checked( $field['value'], 'yes' ); ?> type="<?php echo esc_attr($field['type']); ?>" value="yes" <?php echo esc_attr($field['required']) . esc_attr($field['placeholder']); ?>>
						<?php echo $field['label']; ?>
					</label>
					<?php
					echo ob_get_clean();
					break;
			}

			self::bottom_part( $field, $term );

			?>
			<style>
				.form-field.gs--pro-field {
					user-select: none;
					position: relative;
				}
				.form-field.gs--pro-field:after {
					content: "";
					position: absolute;
					top: 0;
					left: 0;
					width: 100%;
					height: 100%;
				}
				.form-field.gs--pro-field strong {
					color: #e92f7b;
					font-size: 12px;
					font-weight: 700;
					text-transform: uppercase;
					display: inline-block;
					margin-left: 5px;
					padding: 2px 5px;
					background: #f9f9f9;
					border: 1px solid #e92f7b;
					border-radius: 3px;
					position: relative;
					top: -1px;
					line-height: 1;
					box-shadow: 0 0 2px rgba(0,0,0,0.1);
				}
			</style>
			<?php
		}
	}

	public static function top_part( $field, $term ) {
		
		$depends = empty( $field['dependency'] ) ? '' : "data-gs-dependency='" . wc_esc_json( wp_json_encode( $field['dependency'] ) ) . "'";
		$pro_class = ( isset( $field['is_pro_field'] ) && $field['is_pro_field'] ) ? 'gs--pro-field' : '';
		$field_classes = array( 'form-field', esc_attr( $field['id'] ), empty( $field['required'] ) ? '' : 'form-required', $pro_class );

		ob_start();
		if ( ! $term ) {
			?>
		<div <?php echo $depends; ?> class="<?php echo esc_attr( implode(' ', $field_classes) ); ?>">
			<?php if ( $field['type'] !== 'checkbox' ) { ?>
				<label for="<?php echo esc_attr( $field['id'] ); ?>"><?php echo $field['label']; ?></label>
				<?php
			}
		} else {
			?>
			<tr <?php echo $depends; ?> class="<?php echo esc_attr( implode(' ', $field_classes) ); ?>">
				<th scope="row">
					<label for="<?php echo esc_attr( $field['id'] ); ?>"><?php echo $field['label']; ?></label>
				</th>
				<td>
				<?php
		}
			echo ob_get_clean();
	}

	private static function bottom_part( $field, $term ) {
		ob_start();
			if ( ! $term ) { ?>
					<p><?php echo $field['desc']; ?></p>
				</div>
			<?php } else { ?>
						<p class="description"><?php echo $field['desc']; ?></p>
					</td>
				</tr>
			<?php
		}
		echo ob_get_clean();
	}

	private static function get_img_src( $thumbnail_id = false ) {
		if ( ! empty( $thumbnail_id ) ) {
			$image = wp_get_attachment_thumb_url( $thumbnail_id );
		} else {
			$image = self::placeholder_img_src();
		}

		return $image;
	}

	private static function placeholder_img_src() {
		return untrailingslashit( GS_WOO_SWATCHES_PLUGIN_URI . '/assets/img/placeholder.png' );
	}

}
