<?php
namespace BricksUltimate\Admin;

class ProductSwatchesMetabox {
	function __construct() {
		if ( ! function_exists( 'wc_get_attribute_taxonomies' ) ) {
			return;
		}

		$attribute_taxonomies = wc_get_attribute_taxonomies();
		if( $attribute_taxonomies ) {
			foreach ( $attribute_taxonomies as $key => $value ) {
				add_action( 'pa_' . $value->attribute_name .'_add_form_fields', array ( $this, 'add_product_swatches_fields' ), 10 );
				add_action( 'created_pa_' . $value->attribute_name, array ( $this, 'updated_swatches_data' ), 10 );
				add_action( 'pa_' . $value->attribute_name .'_edit_form_fields', array ( $this, 'edit_product_swatches_fields' ), 10, 2 );
				add_action( 'edited_pa_' . $value->attribute_name, array ( $this, 'updated_swatches_data' ), 999 );

				add_filter( 'manage_edit-pa_' . $value->attribute_name . '_columns', [ $this, 'bu_product_attributes_add_swatches_column' ], 15 );
				add_filter( 'manage_pa_' . $value->attribute_name . '_custom_column', [ $this, 'bu_product_attributes_swatches_column_content' ], 15, 3 );
			}
		}

		add_action('admin_enqueue_scripts', [$this, 'enqueue_scripts']);
	}

	public function bu_product_attributes_add_swatches_column( $columns ) {
		$arr = array_slice( $columns, 0, 2 );
		$arr['swatch'] = esc_html__('Swatches', 'bricksultimate');
    	
    	return array_merge( $arr, $columns );
	}

	public function bu_product_attributes_swatches_column_content( $content, $column_name, $term_id ) {
		if ( $column_name === 'swatch' ) {
			$color = get_term_meta( $term_id, 'bu_swatches_color', true );
			$attachment_id = get_term_meta($term_id, 'bu_swatches_img_id', true);
			$image = get_term_meta( $term_id, 'bu_swatches_img_url', true );
			if ( $color ) {
				$content = "<div class=\"bu-attr-peview color\" style=\"background-color: " . esc_attr( $color ) . "\"></div>";
			} elseif ( $image ) {
				$attachment_path = get_attached_file( $attachment_id );
				$ext = pathinfo( $attachment_path, PATHINFO_EXTENSION );
				if( $ext == 'svg' && class_exists('Bricks\Helpers')) {
					$svg = \Bricks\Helpers::file_get_contents( $attachment_path );
					if ( $svg ) {
						$content = "<div class=\"bu-attr-peview image\">". \Bricks\Element::render_svg( $svg, ['class' => 'swatch-svg'] ). "</div>";
					}
				} else {
					$content = "<div class=\"bu-attr-peview image\"><img src='". esc_url( $image ) . "'></div>";
				}
			}
		}

		return $content;
	}

	function enqueue_scripts() {
		global $pagenow;
		if( $pagenow == "edit-tags.php" || $pagenow == "term.php" || ( isset( $_GET['taxonomy']) && strstr( $_GET['taxonomy'], 'pa_' ) ) ) {
			wp_enqueue_style( 'coloris', \BricksUltimate\Helpers::get_asset_url('css') . 'coloris.min.css', [], '1.0', "all" );
			wp_enqueue_script( 'coloris', \BricksUltimate\Helpers::get_asset_url('js') . 'coloris.min.js', [], '1.0', true );
			wp_enqueue_media();
			wp_enqueue_script( 'bu-upload-media', \BricksUltimate\Helpers::get_asset_url('js') . 'upload-media.min.js', array(), "1.5", true );
		}
	}

	public function add_product_swatches_fields( $taxonomy ) {
		?>
		<div class="swatches-form-wrap">
			<h2>Configure Swatches</h2>
			<div class="form-field term-colors">
				<label for="term-colors" style="margin-bottom: 4px;">Color</label>
				<div class="clr-field">
					<button type="button" aria-labelledby="clr-open-label"></button>
					<input type="text" name="swatch_color" class="coloris swatch_color" value="" placeholder="select color">
				</div>
			</div>
			<div class="form-field busw-term-image term-image">
				<label for="term-image" style="margin-bottom: 4px;">Image/SVG File</label>
				<div class="bu-upload-preview-wrap"></div>
				<div class="bu-upload-btns">
					<button class="bu-button bu-upload-btn"><?php esc_html_e( 'Upload', 'bricksultimate' ); ?></button>
					<button class="bu-button bu-remove-btn"><?php esc_html_e( 'Remove', 'bricksultimate' ); ?></button>
					<input type="hidden" class="bu-upload-input-url" name="term_image_url" value="" />
					<input type="hidden" class="bu-upload-input-id" name="term_image_id" value="" />
				</div>
			</div>
			<div class="form-field term-label">
				<input type="checkbox" name="swatch_label"> <label for="term-term-label" style="margin-left: 4px; display: inline-block;">Do not use images from the variations</label>
			</div>
		</div>
		<?php
		echo $this->loadCSS();
	}

	public function edit_product_swatches_fields( $term, $taxonomy ) {
		$swatch_color = get_term_meta($term->term_id, 'bu_swatches_color', true);
		$attachment_id = get_term_meta($term->term_id, 'bu_swatches_img_id', true);
		$attachment_url = $ext = '';
		if ( $attachment_id ) {
			$attachment_path = get_attached_file( $attachment_id );
			$ext = pathinfo( $attachment_path, PATHINFO_EXTENSION );
			$attachment_url = wp_get_attachment_url( $attachment_id );
		}

		$swatch_label = get_term_meta($term->term_id, 'bu_show_swatch_label', true);
		?>
		<tr class="form-field ">
			<td colspan="2">
				<div class="swatches-form-wrap">
					<h2>Configure Swatches</h2>
					<div class="term-colors">
						<label for="term-colors" style="margin-bottom: 4px;">Color</label>
						<div class="clr-field" style="color: <?php echo $swatch_color; ?>">
							<button type="button" aria-labelledby="clr-open-label"></button>
							<input type="text" name="swatch_color" class="coloris swatch_color" value="<?php echo $swatch_color; ?>" placeholder="select color">
						</div>
					</div>
					<div class="busw-term-image term-image">
						<label for="term-image" style="margin-bottom: 4px;">Image/SVG File</label>
						<div class="bu-upload-preview-wrap">
							<?php if ( ! empty( $attachment_url ) ) : ?>
								<?php 
									if( $ext == 'svg' && class_exists('Bricks\Helpers') ) :
										$svg = \Bricks\Helpers::file_get_contents( $attachment_path );
										if ( $svg ) {
											echo \Bricks\Element::render_svg( $svg, ['class' => 'swatch-svg'] );
										}
								?>
								<?php else: ?>
								<img src="<?php echo esc_url( $attachment_url ); ?>">
								<?php endif; ?>
							<?php endif; ?>
						</div>
						<div class="bu-upload-btns">
							<button class="bu-button bu-upload-btn"><?php esc_html_e( 'Upload', 'bricksultimate' ); ?></button>
							<button class="bu-button bu-remove-btn<?php echo ( ! empty( $attachment_url ) ) ? ' bu-active' : ''; ?>"><?php esc_html_e( 'Remove', 'bricksultimate' ); ?></button>
							<input type="hidden" class="bu-upload-input-url" name="term_image_url" value="<?php echo $attachment_url; ?>" />
							<input type="hidden" class="bu-upload-input-id" name="term_image_id" value="<?php echo $attachment_id; ?>" />
						</div>
					</div>

					<div class="form-field term-label">
						<input type="checkbox" name="swatch_label" <?php checked( "disabled", $swatch_label, true );?>> <label for="term-term-label" style="margin-left: 4px; display: inline-block;">Do not use images from the variations</label>
					</div>
				</div>
			</td>
		</tr>
		<?php
		echo $this->loadCSS();
	}

	public function updated_swatches_data( $term_id ) {
		if( isset( $_POST['swatch_color'] ) ) {
			update_metadata(
				'term',
				$term_id,
				'bu_swatches_color',
				$_POST['swatch_color']
			);
		}

		if( isset( $_POST['term_image_url'] ) ) {
			update_metadata(
				'term',
				$term_id,
				'bu_swatches_img_url',
				$_POST['term_image_url']
			);
		}

		if( isset( $_POST['term_image_id'] ) ) {
			update_metadata(
				'term',
				$term_id,
				'bu_swatches_img_id',
				$_POST['term_image_id']
			);
		}

		if ( ! isset( $_POST[ 'swatch_label' ] ) ) { // phpcs:ignore
			delete_metadata(
				'term',
				$term_id,
				'bu_show_swatch_label'
			);
		} else {
			update_metadata(
				'term',
				$term_id,
				'bu_show_swatch_label',
				"disabled"
			);
		}
	}

	public function loadCSS() {
		?>
		<style type="text/css">
			.swatches-form-wrap {
				background: #fff; 
				padding: 10px 25px 25px; 
				margin-bottom: 10px;
			}
			.term-colors > label {
				display: block;
			}

			.busw-term-image {
				margin: 15px 0;
			}

			.bu-upload-btns {
				margin: 10px 0 0;
				display: flex;
			}
			.form-field .bu-button {
				background-color: #efeff0;
				border: none;
				border-radius: 4px;
				display: inline-flex;
				align-items: center;
				box-sizing: border-box;
				padding: 0 15px;
				height: 35px;
				outline: 0!important;
				color: #444;
				text-decoration: none;
				text-transform: uppercase;
				white-space: nowrap;
				font-weight: 600;
				font-size: 12px;
				line-height: 1;
				transition: .2s all ease-in-out;
			}

			.form-field .bu-remove-btn {
				display: none;
				background-color: #f50523;
				color: #fff;
			}

			.form-field .bu-remove-btn.bu-active {
				display: block;
			}

			.form-field .bu-button:first-child {
				margin-right: 6px;
			}

			.form-field .bu-button:hover {
				background-color: #dedede;
			}

			.form-field .bu-remove-btn:hover {
				background-color: #de0621;
			}

			.bu-upload-preview-wrap {
				display: flex;
				flex-wrap: wrap;
			}

			.bu-upload-preview-wrap img,
			.bu-upload-preview-wrap object,
			.bu-upload-preview-wrap svg {
				border: 1px solid #e7e7e7;
				border-radius: 4px;
				display: inline-block;
				margin: 10px 0 5px;
				padding: 5px;
				max-width: 180px;
				max-height: 180px;
				object-fit: contain;
			}

			#swatch,
			.image {
				text-align: center;
			}

			.swatch.column-swatch {
				vertical-align: middle;
			}

			.color {
				border-radius: 50px;
				margin: 0 auto;
				width: 25px;
				height: 25px;
			}

			.image {
				max-width: 50px;
				max-height: 50px;
				margin: 0 auto;
				width: 100%;
			}

			.column-swatch .image img {
				width: 100%;
			}

            svg.swatch-svg {
                width: 50px;
                height: auto;
            }

			.clr-field {
				display: inline-block;
				position: relative;
				color: transparent;
			}

			.clr-field button {
				position: absolute;
				width: 35px;
				height: 100%;
				left: 0;
				top: 50%;
				transform: translateY(-50%);
				margin: 0;
				padding: 0;
				border: 0;
				color: inherit;
				text-indent: -1000px;
				white-space: nowrap;
				overflow: hidden;
				pointer-events: none;
			}
			.form-field .clr-field input {
				background-color: #efeff0;
				width: 185px;
				height: 42px;
				padding: 0 10px;
				padding-inline-start: 45px;
				border: 2px solid #efeff0;
				border-radius: 4px;
				font-family: inherit;
				font-size: inherit;
				font-weight: inherit;
				box-sizing: border-box;
			}

			.form-field .clr-field:hover input,
			.form-field .clr-field input:focus,
			.form-field .clr-field input:active {
				border: 2px solid #efeff0;
			}

			.swatch_color::placeholder {
				font-weight: 600;
				font-size: 12px;
				text-transform: uppercase;
			}
		</style>
		<?php
	}
}