<?php
namespace BricksUltimate\Elements;

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

use BricksUltimate\Helpers;

class SlimGallery extends \Bricks\Element {
	public $category = 'ultimate';
	public $name 	= 'bu-slim-gallery';
	public $icon 	= 'ti-image';
	public $scripts = ['buSlimGallery'];

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

	// Set builder controls
	public function set_controls() {
		$this->controls['source'] = [
			'type'      => 'select',
			'label'     => esc_html__('Source', 'bricksultimate'),
			'options'   => [
				'media' => esc_html__('WP Media', 'bricksultimate'),
				'wc'  	=> esc_html__('WooCommerce Gallery', 'bricksultimate'),
			],
			'default' 	=> 'media',
		];

		$this->controls['items'] = [
			'type' 		=> 'image-gallery',
			'required' 	=> [ 'source', '=', 'media' ],
			'unsplash' 	=> false
		];

		$this->controls['exlFeatImg'] = [
			'tab' 		=> 'content',
			'type'      => 'checkbox',
			'label'     => esc_html__('Exclude featured image', 'bricksultimate'),
			'reset' 	=> true,
			'required' 	=> ['source', '=', 'wc']
		];

		$this->controls['limit'] = [
			'type' 		=> 'number',
			'label' 	=> esc_html__('Show images', 'bricksultimate'),
			'unitless' 	=> true,
			'placeholder' => 5,
			'hasDynamicData' => true
		];

		$this->controls['imageW'] = [
			'type' 		=> 'number',
			'label' 	=> esc_html__('Image width', 'bricksultimate'),
			'description' 	=> esc_html__('For lightbox', 'bricksultimate'),
			'unitless' 	=> true,
			'placeholder' => 1600
		];

		$this->controls['sepOpen'] = [
			'type'     => 'separator',
		];

		// Get breakpoints for "Sources" control
		$breakpoints        = \Bricks\Breakpoints::$breakpoints;
		$breakpoint_options = [];

		foreach ( $breakpoints as $index => $breakpoint ) {
			$breakpoint_options[ $breakpoint['key'] ] = isset( $breakpoint['base'] ) ? $breakpoint['label'] . ' (' . esc_html__( 'Base breakpoint', 'bricks' ) . ')' : $breakpoint['label'];
		}

		if ( ! \Bricks\Breakpoints::$is_mobile_first ) {
			$breakpoint_options = array_reverse( $breakpoint_options );
		}

		// Underscorce prefix to prevent conflict with user-created custom breakpoint
		$breakpoint_options['_custom'] = esc_html__( 'Custom', 'bricks' );

		$this->controls['bpRowHeight'] = [
			//'label'         => esc_html__('Row height', 'bricksultimate'),
			'type'          => 'repeater',
			'titleProperty' => 'breakpoint',
			//'placeholder'   => esc_html__('Row height', 'bricksultimate'),
			//'description'   => esc_html__('Only work on page load', 'bricksultimate'),
			'fields'        => [
				'breakpoint' => [
					'label'       => esc_html__( 'Breakpoint', 'bricks' ),
					'type'        => 'select',
					'options'     => $breakpoint_options,
					'placeholder' => esc_html__( 'Select', 'bricks' ),
				],
				'media'      => [
					'label'       => esc_html__( 'Custom breakpoint', 'bricksultimate' ),
					'type'        => 'text',
					'required'    => [ 'breakpoint', '=', '_custom' ],
				],
				'rowHeight' => [
					'type' 		=> 'number',
					'label' 	=> esc_html__('Row height', 'bricksultimate'),
					'unitless' 	=> true,
					'placeholder' => 180
				]
			],
		];

		$this->controls['sepClose'] = [
			'type'     => 'separator',
		];

		$this->controls['lastRow'] = [
			'type'      => 'select',
			'label'     => esc_html__('Last row', 'bricksultimate'),
			'options'   => [
				'justify' 		=> esc_html__('Justify', 'bricksultimate'),
				'nojustify'  	=> esc_html__('Not Justify', 'bricksultimate'),
				'left'  		=> esc_html__('Left', 'bricksultimate'),
				'right'  		=> esc_html__('Right', 'bricksultimate'),
				'center'  		=> esc_html__('Center', 'bricksultimate'),
				'hide'  		=> esc_html__('Hide', 'bricksultimate'),
			],
			'default' => 'justify',
			'inline' 	=> true
		];

		$this->controls['gap'] = [
			'type' 		=> 'number',
			'label' 	=> esc_html__('Gap', 'bricksultimate'),
			'unitless' 	=> true,
			'placeholder' => 5
		];

		$this->controls['altText'] = [
			'type' 				=> 'text',
			'label' 			=> esc_html__('Alt Text', 'bricksultimate'),
			'hasDynamicData' 	=> true,
			'placeholder' 		=> esc_html__('Alternative Text', 'bricksultimate')
		];

		$this->controls['showCaption'] = [
			'type' 		=> 'checkbox',
			'label' 	=> esc_html__('Show caption', 'bricksultimate'),
			'description' 	=> esc_html__('on lightbox', 'bricksultimate'),
		];

		$this->controls['showThumbs'] = [
			'type' 		=> 'checkbox',
			'label' 	=> esc_html__('Show thumbs in lightbox', 'bricksultimate'),
		];

		$this->controls['thumbW'] = [
			'type' 		=> 'number',
			'label' 	=> esc_html__('Thumbs width', 'bricksultimate'),
			'unitless' 	=> true,
			'placeholder' => 240,
			'required' => ['showThumbs', '=', true]
		];

		$this->controls['sep'] = [
			'type' 		=> 'separator',
			'label' 	=> esc_html__('More button', 'bricksultimate'),
		];

		$this->controls['moreText'] = [
			'type' 		=> 'text',
			'label' 	=> esc_html__('More text', 'bricksultimate'),
			'placeholder' 	=> esc_html__('See ##more##+ photos', 'bricksultimate'),
		];

		$selector = '.btn-dynamic';

		$this->controls['btnWidth'] = [
			'type' 		=> 'number',
			'label' 	=> esc_html__('Width', 'bricksultimate'),
			'units' 	=> true,
			'placeholder' => '100%',
			'css' => [
				[
					'selector' => $selector,
					'property' => 'width'
				]
			]
		];

		$this->controls['btnHeight'] = [
			'type' 		=> 'number',
			'label' 	=> esc_html__('Height', 'bricksultimate'),
			'units' 	=> true,
			'placeholder' => '100%',
			'css' => [
				[
					'selector' => $selector,
					'property' => 'height'
				]
			]
		];

		$this->controls['btnBg'] = [
			'type' 		=> 'color',
			'label' 	=> esc_html__('Background color', 'bricksultimate'),
			'css' => [
				[
					'selector' => $selector,
					'property' => 'background-color'
				]
			]
		];

		$this->controls['btnTg'] = [
			'type' 		=> 'typography',
			'label' 	=> esc_html__('Typography', 'bricksultimate'),
			'css' => [
				[
					'selector' => $selector,
					'property' => 'font'
				]
			]
		];

		$this->controls['btnBrd'] = [
			'type' 		=> 'border',
			'label' 	=> esc_html__('Button border', 'bricksultimate'),
			'css' => [
				[
					'selector' => $selector,
					'property' => 'border'
				]
			]
		];

		$this->controls['btnPad'] = [
			'type' 		=> 'dimensions',
			'label' 	=> esc_html__('Button padding', 'bricksultimate'),
			'css' => [
				[
					'selector' => $selector,
					'property' => 'padding'
				]
			]
		];

		$this->controls['positionInfo'] = [
			'type'     => 'info',
			'content'  => esc_html__( 'Position', 'bricks' ),
		];

		$this->controls['top'] = [
			'label' => esc_html__( 'Top', 'bricks' ),
			'type'  => 'number',
			'units' => true,
			'css'   => [
				[
					'property' => 'top',
					'selector' => $selector,
				],
			],
		];

		$this->controls['right'] = [
			'label' => esc_html__( 'Right', 'bricks' ),
			'type'  => 'number',
			'units' => true,
			'css'   => [
				[
					'property' => 'right',
					'selector' => $selector,
				],
			],
		];

		$this->controls['bottom'] = [
			'label' => esc_html__( 'Bottom', 'bricks' ),
			'type'  => 'number',
			'units' => true,
			'css'   => [
				[
					'property' => 'bottom',
					'selector' => $selector,
				],
			],
		];

		$this->controls['left'] = [
			'label' => esc_html__( 'Left', 'bricks' ),
			'type'  => 'number',
			'units' => true,
			'css'   => [
				[
					'property' => 'left',
					'selector' => $selector,
				],
			],
		];

		$this->controls['transformBtn'] = [
			'label' => esc_html__( 'Transform', 'bricks' ),
			'type'  => 'text',
			'css'   => [
				[
					'property' => 'transform',
					'selector' => $selector,
				],
			],
			'placeholder' => 'translate(-50%, -50%)'
		];

		$this->controls['zIndex'] = [
			'label'       => esc_html__( 'Z-index', 'bricks' ),
			'type'        => 'number',
			'css'         => [
				[
					'property' => 'z-index',
					'selector' => $selector,
				],
			],
			'min'         => -999,
			'placeholder' => 0,
		];
	}

	// Enqueue element styles and scripts
	public function enqueue_scripts() {
		//if( bricks_is_builder() || bricks_is_builder_iframe() || bricks_is_builder_call() ){
			wp_enqueue_style( 'bu-flex-gallery-lg', Helpers::get_asset_url('css') . 'lightgallery.min.css', [], '2.7.0', 'all' );
			wp_enqueue_style( 'bu-lg-thumbnail', Helpers::get_asset_url('css') . 'lg-thumbnail.min.css', [], '2.7.0', 'all' );
			wp_enqueue_style( 'bu-slim-gallery', Helpers::get_asset_url('css') . 'buslimgallery.min.css', [], filemtime(Helpers::get_asset_path('css') . 'buslimgallery.min.css'), 'all' );
		//}

		wp_enqueue_script( 'bu-lg-thumbnail', Helpers::get_asset_url('js') . 'lg-thumbnail.min.js', [], '2.7.0', true );
		wp_enqueue_script( 'bu-flex-gallery-lg', Helpers::get_asset_url('js') . 'lightgallery.min.js', [], '2.0', true );
		wp_enqueue_script( 'bu-slim-gallery', Helpers::get_asset_url('js') . 'buslimgallery.min.js', ['jquery'], filemtime(Helpers::get_asset_path('js') . 'buslimgallery.min.js'), true );
	}

	// Render element HTML
	public function render() {
		$settings = $this->settings;

		if ( ! isset( $settings['source'] ) ) {
			return $this->render_element_placeholder( ['title' => esc_html__( 'Select the source for images.', 'bricksultimate' )] );
		}

		$image_ids = []; 
		$thumbW = Helpers::get_value( $settings, 'thumbW', 240);

		if ( $settings['source'] == 'media' ) {
			$items = isset( $settings['items'] ) ? $settings['items'] : false;
			$size = ! empty( $items['size'] ) ? $items['size'] : BRICKS_DEFAULT_IMAGE_SIZE;

			// Dynamic Data
			if ( ! empty( $items['useDynamicData'] ) ) {
				$items['images'] = [];

				$images = $this->render_dynamic_data_tag( $items['useDynamicData'], 'image' );

				if ( is_array( $images ) ) {
					foreach ( $images as $image_id ) {
						if( is_array( $image_id ) )
							$image_ids = array_keys( $image_id );
						else
							$image_ids[] = $image_id;
					}
				}
			} elseif ( $items && is_array( $items['images'] ) ) {
				foreach ( $items['images'] as $image_id ) {
					$image_ids[] = $image_id['id'];
				}
			}
		}

		//* get the woocommerce gallery
		elseif ( class_exists( 'WooCommerce' ) && $settings['source'] == 'wc' ) {
			global $porduct;

			$product_id = $this->post_id;

			$object = \Bricks\Query::get_loop_object();
			if( is_object( $object ) ) {
				$product_id = $object->ID;
			}

			$product = wc_get_product( $product_id );

			if( $product === false ) {
				return $this->render_element_placeholder( ['title' => esc_html__( 'This is not a WooCommerce product.', 'bricksultimate' )] );
			}

			$featured_image_id = $product->get_image_id();
			$image_ids = array_unique( $product->get_gallery_image_ids() );

			if( $featured_image_id && empty( $settings['exlFeatImg']) ) {
				array_unshift( $image_ids, $featured_image_id );
			}
		} else {
			$image_ids = false;
		}

		if( $image_ids ) {
			$limit = bricks_render_dynamic_data( Helpers::get_value( $settings, 'limit', 5 ) );
			$count = count( $image_ids );
			$left = ( $count > $limit ) ? ( $count - $limit ) : false;

			$this->set_attribute( "_root", 'class', ['gallery-container-wrap'] );

			$rowHeights = ! empty( $settings['bpRowHeight'] ) ? $settings['bpRowHeight'] : false;

			$config = [
				'id' => $this->id,
				'gap' => Helpers::get_value($settings, 'gap', 5),
				'limit' => $limit,
				'hasDynamicImage' => $left === false ? "no" : "yes",
				'rowHeight' => ['base' => 180],
				'lastRow' => Helpers::get_value($settings, 'lastRow', 'justify'),
				'showThumbs' => ! empty( $settings['showThumbs'] ) ? 'yes' : 'no'
			];

			if ( is_array( $rowHeights ) && count( $rowHeights ) ) {
				foreach ( $rowHeights as $index => $rowHeight ) {
					$breakpoint_key = ! empty( $rowHeight['breakpoint'] ) ? $rowHeight['breakpoint'] : false;

					if ( ! $breakpoint_key ) {
						continue;
					}

					$breakpoint = $breakpoint_key ? \Bricks\Breakpoints::get_breakpoint_by( 'key', $breakpoint_key ) : false;

					if ( ! empty( $breakpoint['width'] ) && isset( $breakpoint['base'] ) ) {
						$config['rowHeight'][ 'base' ] = $rowHeight['rowHeight'] ?? 180;
					}

					if ( ! empty( $breakpoint['width'] ) && ! isset( $breakpoint['base'] ) ) {
						$config['rowHeight'][ $breakpoint['width'] ] = $rowHeight['rowHeight'] ?? 180;
					}

					// Set 'media' attribute from custom media query
					if ( $breakpoint_key === '_custom' && ! empty( $rowHeight['media'] ) ) {
						$config['rowHeight'][ $rowHeight['media'] ] = $rowHeight['rowHeight'] ?? 180;
					}
				}
			}

			foreach( $image_ids as $key => $image_id ) {
				$caption = wp_get_attachment_caption( $image_id ) ?? ( ! empty( $settings['altText'] ) ?  bricks_render_dynamic_data( $settings['altText'] ) : false );
				$img = wp_get_attachment_image_src( $image_id, 'full' );
				$imageW = Helpers::get_value($settings, 'imageW', $img[1]);
				$thumbW = Helpers::get_value($settings, 'thumbW', 240);
				$config['images'][$key] = [
					'src' => esc_url( $img[0] ) . '?auto=format&fit=crop&w=' . $imageW . '&q=80'
				];

				if( ! empty( $settings['showThumbs'] ) ) {
					$config['images'][$key]['thumb'] = esc_url( $img[0] ) . '?auto=format&fit=crop&w=' . $thumbW . '&q=80';
				}

				if( ! empty( $settings['showCaption']) && $caption ) {
					$config['images'][$key]['subHtml'] = $caption;
				}
			}

			$this->set_attribute( "_root", 'data-config', wp_json_encode( $config ) );

			echo "<{$this->tag} {$this->render_attributes('_root')} itemscope>";

			echo "<div class=\"gallery-container gallery-dynamic-thumbnails\" id=\"gallery-{$this->id}\">";

			foreach( $image_ids as $index => $image_id ) {
				$data = wp_get_attachment_metadata( $image_id );

				if( ! $data ) {
					continue;
				}

				if( $index >= $limit )
					break;

				$alt = wp_get_attachment_caption( $image_id ) ?? ( ! empty( $settings['altText'] ) ?  bricks_render_dynamic_data( $settings['altText'] ) : false );
				$img = wp_get_attachment_image_src( $image_id, 'full' );

				$this->set_attribute( "slim-gallery-img-$index", 'class', ['gallery-item'] );
				$this->set_attribute( "slim-gallery-img-$index", 'data-lg-size', esc_attr( $img[1] ) . '-' . esc_attr( $img[2] ) );
				$this->set_attribute( "slim-gallery-img-$index", 'data-index', $index );
				$this->set_attribute( "slim-gallery-img-$index", 'data-src', esc_url( $img[0] ) );

				if( ! empty( $settings['showCaption']) && $alt ) {
					$this->set_attribute( "slim-gallery-img-$index", 'data-sub-html', wp_kses_post( $alt ) );
				}

				$this->set_attribute( "slim-gallery-img-$index", 'href', esc_url( $img[0] ) );

				echo "<a {$this->render_attributes( "slim-gallery-img-$index" )}>";
				?>
					<img class="img-responsive" src="<?php echo esc_url( $img[0] ); ?>" alt="<?php echo wp_kses_post( $alt ); ?>"  srcset="<?php echo esc_attr( wp_get_attachment_image_srcset( $image_id ) ); ?>"/>
				<?php
				$moreText = Helpers::get_value( $settings, 'moreText');
				if( $left && $moreText && ($index + 1) == $limit ) {
					$moreText = str_replace('##more##', $left, $moreText );
					echo "<button type=\"button\" class=\"button btn-dynamic\">{$moreText}</button>";
				}

				echo "</a>";
			}

			echo "</div></{$this->tag}>";
		} else {
			return $this->render_element_placeholder( ['title' => esc_html__( 'Upload images.', 'bricksultimate' )] );
		}
	}
}