<?php
namespace BricksUltimate\Elements;

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

use BricksUltimate\Helpers;

class ImageMedia extends \Bricks\Element {
	public $category 		= 'ultimate';
	public $name 			= 'bu-image';
	public $icon 			= 'ti-image';
	public $tag 			= 'div';

	// Return localized element label
	public function get_label() {
		return esc_html__( '(BU)Image Attachment', 'bricksultimate' );
	}

	// Set builder controls
	public function set_controls() {
		$this->controls['size'] = [
			'tab' 		=> 'content',
			'type'      => 'select',
			'label'     => esc_html__('Resolution', 'bricksultimate'),
			'options'   => $this->control_options['imageSizes'],
			'default'   => 'large',
		];

		$this->controls['aspectRatio'] = [
			'tab' 		=> 'content',
			'type'      => 'text',
			'label'     => esc_html__('Image aspect ratio', 'bricksultimate'),
			'placeholder'   => '16:9',
			'hasDynamicData' => false,
			'inline' 	=> true,
		];

		$this->controls['minWidth'] = [
			'tab' 		=> 'content',
			'type'      => 'number',
			'label'     => esc_html__('Image min width(px)', 'bricksultimate'),
			'unit' 		=> 'px',
			'min' 		=> 0,
			'max' 		=> 10000,
			'step' 		=> 1,
			'css' 		=> [
				[
					'selector' 	=> '.bu-image-item',
					'property' 	=> 'min-width'
				]
			]
		];

		$this->controls['link'] = [
			'tab'         => 'content',
			'label'       => esc_html__( 'Link to', 'bricks' ),
			'type'        => 'select',
			'options'     => [
				'lightbox'   => esc_html__( 'Lightbox', 'bricks' ),
				'attachment' => esc_html__( 'Attachment Page', 'bricks' ),
				'media'      => esc_html__( 'Media File', 'bricks' ),
			],
			'inline'      => true,
			'placeholder' => esc_html__( 'None', 'bricks' ),
		];

		$this->controls['lightboxImageSize'] = [
			'tab'         => 'content',
			'label'       => esc_html__( 'Lightbox image size', 'bricks' ),
			'type'        => 'select',
			'options'     => $this->control_options['imageSizes'],
			'placeholder' => esc_html__( 'Full', 'bricks' ),
			'required'    => [ 'link', '=', 'lightbox' ],
		];

		$this->controls['selector'] = [
			'tab'   => 'content',
			'label' => esc_html__( 'Outer container selector', 'Lightbox' ),
			'type'  => 'text',
			'placeholder' => '.brxe-container',
			'required' => [ 'link', '=', 'lightbox' ],
			'description' => esc_html__('Need for gallery slider in lightbox', 'bricksultimate')
		];

		$this->controls['alt'] = [
			'tab'   => 'content',
			'label' => esc_html__( 'Show alt', 'Lightbox' ),
			'type'  => 'checkbox',
			'required' => [ 'link', '=', 'lightbox' ],
		];

		$this->controls['caption'] = [
			'tab'   => 'content',
			'label' => esc_html__( 'Show caption', 'Lightbox' ),
			'type'  => 'checkbox',
			'required' => [ 'link', '=', 'lightbox' ],
		];

		$this->controls['thumbnails'] = [
			'tab'   => 'content',
			'label' => esc_html__( 'Show thumbnails', 'Lightbox' ),
			'type'  => 'checkbox',
			'required' => [ 'link', '=', 'lightbox' ],
		];

		$this->controls['thumbnailsRight'] = [
			'tab'   => 'content',
			'label' => esc_html__( 'Show thumbnails at right side', 'Lightbox' ),
			'type'  => 'checkbox',
			'required' => [ 'thumbnails', '=', true ],
		];
	}

	// Enqueue element styles and scripts
	public function enqueue_scripts() {
		//wp_enqueue_style( 'bu-image-attachment', Helpers::get_asset_url('css') . 'buimgattch.min.css', [], filemtime(Helpers::get_asset_path('css') . 'buimgattch.min.css'), 'all' );

		if( ! empty( $this->settings['link'] ) && $this->settings['link'] == 'lightbox' && $this->is_frontend ) {
			wp_enqueue_style( 'bu-flex-gallery-lg', Helpers::get_asset_url('css') . 'lightgallery.min.css', [], '2.7.0', 'all' );

			if( isset( $this->settings['thumbnails'] ) ) {
				wp_enqueue_style( 'bu-lg-thumbnail', Helpers::get_asset_url('css') . 'lg-thumbnail.min.css', [], '2.7.0', 'all' );
				wp_enqueue_script( 'bu-lg-thumbnail', Helpers::get_asset_url('js') . 'lg-thumbnail.min.js', [], '2.7.0', true );
			}
			
			wp_enqueue_script( 'bricks-lg', Helpers::get_asset_url('js') . 'lightgallery.min.js', [], '2.7.0', true );
			wp_enqueue_script( 'bu-image-attachment-lb', Helpers::get_asset_url('js') . 'buimageattachment.min.js', [], filemtime(Helpers::get_asset_path('js') . 'buimageattachment.min.js'), 'all' );
		}
	}

	// Render element HTML
	public function render() {
		$settings = $this->settings;
		$attachmentId = $this->post_id;
		$thumbSize = Helpers::get_value( $settings, 'size', 'large' );
		$img = wp_get_attachment_image_src( $attachmentId, $thumbSize );

		if( empty( $img ) ) {
			if( has_post_thumbnail( $this->post_id ) ) {
				$attachmentId = get_post_thumbnail_id( $this->post_id );
				$imageMeta = wp_get_attachment_metadata( $attachmentId );
				$width = ! empty( $imageMeta['sizes'][$thumbSize]['width'] ) ? $imageMeta['sizes'][$thumbSize]['width'] : 800;
				$height = ! empty( $imageMeta['sizes'][$thumbSize]['height'] ) ? $imageMeta['sizes'][$thumbSize]['height'] : 600;
				$img = [ get_the_post_thumbnail_url( $this->post_id, $thumbSize ), $width, $height ];
			} elseif( ( get_post_type( $this->post_id ) == 'product' || \BricksUltimate\DynamicData\ProviderUltimate::getOrderItem() ) && class_exists('WooCommerce') ) {
				$item = \BricksUltimate\DynamicData\ProviderUltimate::getOrderItem();
				$product = is_a( $item, '\WC_Order_Item_Product' ) ? $item->get_product() : wc_get_product( $this->post_id );

				if ( $product && $product->get_image_id() ) {
					$attachmentId = $product->get_image_id();
					$img = wp_get_attachment_image_src( $attachmentId, $thumbSize );
				} elseif ( $product && $product->get_parent_id() ) {
					$parent_product = wc_get_product( $product->get_parent_id() );
					if ( $parent_product ) {
						$attachmentId = $parent_product->get_image_id();
						$img = wp_get_attachment_image_src( $attachmentId, $thumbSize );
					}
				}

				if( empty( $img ) ) {
					$attachmentId = get_option( 'woocommerce_placeholder_image', 0 );
					if( $attachmentId && absint( $attachmentId ) > 0 ) {
						$img = wp_get_attachment_image_src( $attachmentId, $thumbSize );
					} else{
						return;
					}
				}
			} elseif( Helpers::isBricksBuilderActive() ) {
				$img = [ \Bricks\Builder::get_template_placeholder_image(), 800, 600 ];
			} else {
				return $this->render_element_placeholder( [ 'title' => sprintf( esc_html__( 'Image ID (%s) no longer exist. Please select another image.', 'bricks' ), $attachmentId ) ] );
			}
		}

		$link_to 	= ! empty( $settings['link'] ) ? $settings['link'] : false;
		$selector = isset( $settings['selector'] ) ? esc_attr( $settings['selector'] ) : false;
		$showThumbs = isset( $settings['thumbnails'] ) ? 'yes' : "no";
		$showThumbsRight = isset( $settings['thumbnailsRight'] ) ? 'yes' : "no";
		$aspect_ratio = isset( $settings['aspectRatio'] ) ? esc_attr( $settings['aspectRatio'] ) : "16:9";
		$aspect_ratio = explode(":", $aspect_ratio);
		$aspect_ratio = ($aspect_ratio[1] / $aspect_ratio[0]);
		$aspect_ratio = number_format($aspect_ratio * 100, 2) . "%";
		$alt 		= esc_attr(get_post_meta($attachmentId, '_wp_attachment_image_alt', true));

		if ( $link_to === 'lightbox' ) {
			$lightbox_image_size = ! empty( $settings['lightboxImageSize'] ) ? $settings['lightboxImageSize'] : 'full';
			$lightbox_image      = wp_get_attachment_image_src( $attachmentId, $lightbox_image_size );
			$lightbox_image      = ! empty( $lightbox_image ) && is_array( $lightbox_image ) ? $lightbox_image : [ wp_get_attachment_image_url($attachmentId, 'full'), 800, 600 ];
			$caption = isset( $settings['caption'] ) ? '<p class="bu-lb-caption">' . wp_get_attachment_caption( $attachmentId ) . '</p>' : false;

			$this->set_attribute( "bu-image-item", 'data-src', $lightbox_image[0] );
			$this->set_attribute( "bu-image-item", 'data-width', $lightbox_image[1] );
			$this->set_attribute( "bu-image-item", 'data-sub-html', ( $alt && isset( $settings['alt'] ) ? "<h4>{$alt}</h4>" : '' ) . $caption );
			$this->set_attribute( "_root", 'data-selector', $selector );
			$this->set_attribute( "_root", 'data-lb-thumbnails', $showThumbs );
			$this->set_attribute( "_root", 'data-lb-thumbs-right', $showThumbsRight );
			
			$this->set_attribute( "bu-image-attachment", 'href', $lightbox_image[0] );
			$this->set_attribute( "bu-image-attachment", 'itemprop', "contentUrl" );

			$link_tag = 'a';
		} elseif ( $link_to === 'attachment' ) {
			$link_tag = 'a';
			$this->set_attribute( "bu-image-attachment", 'itemprop', "contentUrl" );
			$this->set_attribute( "bu-image-attachment", 'href', get_permalink( $attachmentId ) );
			$this->set_attribute( "bu-image-attachment", 'target', "_blank" );
		} elseif ( $link_to === 'media' ) {
			$link_tag = 'a';

			$this->set_attribute( "bu-image-attachment", 'itemprop', "contentUrl" );
			$this->set_attribute( "bu-image-attachment", 'href', esc_url( wp_get_attachment_image_url( $attachmentId, 'full' ) ) );
			$this->set_attribute( "bu-image-attachment", 'target', "_blank" );
		} else {
			$link_tag = 'div';
		}

		$this->set_attribute( '_root', 'itemtype', "http://schema.org/ImageGallery");
		echo "<{$this->tag} {$this->render_attributes('_root')} itemscope>";

		$image_classes = [ 'bu-image-attachment', 'css-filter' ];

		if ( $this->lazy_load() ) {
			$image_classes[] = 'bricks-lazy-hidden';
			$this->set_attribute( "bu-image-attachment", 'data-style', "background-image: url({$img[0]})" );
		} else {
			$this->set_attribute( "bu-image-attachment", 'style', "background-image: url({$img[0]})" );
		}

		$this->set_attribute( "bu-image-attachment", 'width', $img[1] );
		$this->set_attribute( "bu-image-attachment", 'height', $img[2] );
		$this->set_attribute( "bu-image-attachment", 'class', $image_classes );

		$this->set_attribute( "bu-image-item", 'class', "bu-image-item" );
		$this->set_attribute( "bu-image-item", 'itemprop', "associatedMedia" );
		$this->set_attribute( "bu-image-item", 'itemtype', "http://schema.org/ImageObject" );
		$this->set_attribute( "bu-image-item", 'style', "padding-bottom: {$aspect_ratio}" );

		echo "<figure {$this->render_attributes( "bu-image-item" )}><{$link_tag} {$this->render_attributes( "bu-image-attachment" )}>";
		$this->set_attribute( "bu-image", 'width', esc_attr( $img[1] ) );
		$this->set_attribute( "bu-image", 'height', esc_attr( $img[2] ) );
		$this->set_attribute( "bu-image", 'alt', $alt );
		$this->set_attribute( "bu-image", 'src', esc_url( $img[0] ) );
		echo "<img {$this->render_attributes('bu-image', true)}>";
		//* close markup
		echo "</{$link_tag}></figure>";
		echo "</{$this->tag}>";
	}
}