<?php
/**
 * Gallery Block
 *
 * @package StrategyBlocks
 *
 * @param array  $attributes  The block's attributes.
 * @param string $content     The block's inner content (unused here).
 * @param object $block       The block object (contains anchor, etc.).
 */

use StrategyBlocks\Utility;

$id            = $attributes['anchor'] ?? '';
$gallery       = $attributes['gallery'] ?? [];
$layout        = $attributes['layout'] ?? 'grid';
$columns       = isset( $attributes['columns'] ) ? (int) $attributes['columns'] : 3;
$spacing       = $attributes['spacing'] ?? 'md';
$aspect_ratio  = $attributes['aspectRatio'] ?? '16-9';
$image_size    = $attributes['imageSize'] ?? 'medium';
$sorting       = $attributes['sorting'] ?? false;
$lightbox      = $attributes['lightbox'] ?? true;
$show_title    = $attributes['showTitle'] ?? false;
$show_desc     = $attributes['showDesc'] ?? false;
$button_style  = $attributes['primary'] ?? 'primary';

$class_name = implode(
	' ',
	array_filter(
		[
			'lg-block',
			'lg-block__gallery--native',
			Utility\get_block_style_classes( $attributes ),
			Utility\get_visibility_classes( $attributes ),
		]
	)
);

$gallery_class = implode(
	' ',
	array_filter(
		[
			'gallery',
			'gallery--' . $layout,
			'gallery--ratio-' . $aspect_ratio,
			'grid' === $layout ? 'gallery--columns gallery--columns-' . $columns : '',
			$lightbox ? 'gallery--lightbox' : '',
		]
	)
);

$component_classes = array(
	'overlay'   => null,
	'text'      => null,
);
$wp_classes = explode( ' ', trim( Utility\get_native_wp_classes( $attributes ) ) );
foreach ( $wp_classes as $class ) {
	if ( false !== strpos( $class, 'text-color' ) ) {
		$component_classes['text'] = $class;
	} else if ( false !== strpos( $class, 'bg-color' ) ) {
		$component_classes['overlay'] = $class;
	} else {
		$class_name .= ' ' . $class;
	}
}

$design_classes = array(
	'overlay'   => $component_classes['overlay'] ?? 'bg-color-secondary',
	'text'      => $component_classes['text'] ?? 'text-color-primary',
);

$image_class = 'gallery__image';

$sizes = Utility\get_image_sizes();

$aspect_ratio_array = explode( '-', $aspect_ratio );
$aspect_ratio_x = intval( $aspect_ratio_array[0] );
$aspect_ratio_y = intval( $aspect_ratio_array[1] );

$placeholder_width = (int) $sizes[ $image_size ]['width'];
$placeholder_height = (int) ( $aspect_ratio_y * $placeholder_width / $aspect_ratio_x );

$categories = array();
$images = [];
if ( ! empty( $gallery ) ) {
	foreach ( $gallery as $image_id ) {
		$image = array(
			'id'           => $image_id,
			'title'        => get_the_title( $image_id ),
			'description'  => get_post_field( 'post_content', $image_id ) ?? '',
			'categories'   => get_the_terms( $image_id, 'media-categories' ) ?? [],
		);

		if ( ! empty( $image['categories'] ) ) {
			foreach ( $image['categories'] as $category ) {
				if ( ! in_array( $category->name, $categories ) ) {
					$categories[] = $category->name;
				}
			}
		}

		$images[] = $image;

	}
}
$use_placeholder = empty( $gallery );

$gallery_item_classes = [
	'gallery__item',
	'gallery__item--gap-' . $spacing,
	'masonry' == $layout ? 'gallery__item--sizer-' . $columns : '',
	$lightbox ? 'gallery--lightbox' : '',
];

$animations = Utility\get_animation_data( $attributes );

do_action( 'lg_block_gallery_before' );
?>

<div
	<?php
	if ( $id ) {
		echo 'id="' . esc_attr( $id ) . '"';
	}
	?>
	class="<?php echo esc_attr( $class_name ); ?>"
	<?php
	if ( $animations ) {
		echo 'data-animation="' . esc_attr( $animations ) . '"';
	}
	?>
>
	<?php if ( $sorting && 0 < count( $categories ) ) : ?>
		<div class="gallery__sorting">
			<?php foreach ( $categories as $category ) : ?>
				<button
					class="gallery__sorting__button btn btn-<?php echo esc_attr( $button_style ); ?>"
					data-category="<?php echo esc_attr( strtolower( $category ) ); ?>"
				><?php echo esc_html( $category ); ?></button>
			<?php endforeach; ?>
		</div>
	<?php endif; ?>

	<div class="<?php echo esc_attr( $gallery_class ); ?>">
		<?php if ( 'masonry' == $layout ) : ?>
			<div class="gallery__item--sizer gallery__item--sizer-<?php echo esc_attr( $columns ); ?>"></div>
		<?php endif; ?>

		<?php
		if ( ! empty( $images ) ) {
			foreach ( $images as $index => $image ) {
				$additional_classes = [];

				if ( ! empty( $image['categories'] ) && is_array( $image['categories'] ) ) {
					foreach ( $image['categories'] as $category ) {
						$additional_classes[] = 'category-' . $category->slug;
					}
				}

				$gallery_item_class = implode( ' ', array_filter( array_merge( $gallery_item_classes, $additional_classes ) ) );
				$show_text          = $show_title || $show_desc;
				$full_image         = $lightbox ? wp_get_attachment_image_src( $image['id'], 'full' ) : null;
				$image_html         = wp_get_attachment_image( $image['id'], $image_size, false, [ 'class' => 'gallery__image-img' ] );

				$render_text = function () use ( $image, $show_title, $show_desc, $design_classes ) {
					if ( ! $show_title && ! $show_desc ) {
						return '';
					};
					ob_start();
					?>
					<div class="gallery__image__text <?php echo esc_attr( $design_classes['text'] ); ?>">
						<?php if ( $show_title ) : ?>
							<span class="gallery__image__text--title"><?php echo esc_html( $image['title'] ); ?></span>
						<?php endif; ?>
						<?php if ( $show_desc ) : ?>
							<span class="gallery__image__text--desc"><?php echo esc_html( $image['description'] ); ?></span>
						<?php endif; ?>
					</div>
					<?php
					return ob_get_clean();
				};
				$text_container  = '';
				if ( 'masonry' !== $layout || $lightbox ) {
					$text_container = '<div class="gallery__image__text--container"><div class="gallery__image__text ' . esc_attr( $design_classes['text'] ) . '"><div class="gallery__image__overlay ' . esc_attr( $design_classes['overlay'] ) . '"></div>' . ( $show_text ? $render_text() : '' ) . '</div></div>';
				}
				?>
				<div class="<?php echo esc_attr( $gallery_item_class ); ?>">
					<?php if ( $lightbox && $full_image ) : ?>
						<a href="<?php echo esc_url( $full_image[0] ); ?>"
						   class="<?php echo esc_attr( $image_class ); ?>"
						   data-pswp-width="<?php echo esc_attr( $full_image[1] ); ?>"
						   data-pswp-height="<?php echo esc_attr( $full_image[2] ); ?>"
						   target="_blank"
						>
							<?php echo wp_kses_post( $image_html ); ?>
						</a>
						<?php echo 'masonry' === $layout ? ( $show_text ? wp_kses_post( $render_text() ) : '' ) : wp_kses_post( $text_container ); ?>
					<?php else : ?>
						<div class="<?php echo esc_attr( $image_class ); ?>">
							<?php echo wp_kses_post( $image_html ); ?>
						</div>
						<?php echo 'masonry' === $layout ? ( $show_text ? wp_kses_post( $render_text() ) : '' ) : wp_kses_post( $text_container ); ?>
					<?php endif; ?>
				</div>
				<?php
			}
		} else {
			for ( $i = 0; $i < 12; $i++ ) {
				$width  = $placeholder_width;
				$height = $placeholder_height;

				$item_class        = 'gallery__item gallery__item--gap-' . $spacing;
				$placeholder_class = 'gallery__image-img gallery__image-placeholder';

				if ( 'masonry' === $layout ) {
					$sizer_class = 'gallery__item--sizer-' . $columns;
					$item_class .= ' ' . $sizer_class;

					$mod = intdiv( $i, $columns ) % 2;
					if ( $i % $columns % 2 === $mod ) {
						$height /= 2;
						$placeholder_class .= ' gallery__image-placeholder-2';
					} else {
						$placeholder_class .= ' gallery__image-placeholder-1';
					}

					$height = (int) $height;
				}
				?>
				<div class="<?php echo esc_attr( $item_class ); ?>">
					<div class="<?php echo esc_attr( $image_class ); ?>">
						<div class="<?php echo esc_attr( $placeholder_class ); ?>"></div>
					</div>
				</div>
				<?php
			}
		}
		?>
	</div>
	<?php if ( is_array( $gallery ) && count( $gallery ) > 12 ) : ?>
		<div class="gallery__pagination">
			<a class="btn btn-<?php echo esc_attr( $button_style ); ?>">Show More</a>
		</div>
	<?php endif; ?>
</div>

<?php do_action( 'lg_block_gallery_after' ); ?>
