<?php

class EL_DiviGalleryExtended extends DiviExtension {

	/**
	 * The gettext domain for the extension's translations.
	 *
	 * @since 1.0.0
	 *
	 * @var string
	 */
	public $gettext_domain = 'divi-gallery-extended';

	/**
	 * The extension's WP Plugin name.
	 *
	 * @since 1.0.0
	 *
	 * @var string
	 */
	public $name = 'divi-gallery-extended';

	/**
	 * The extension's version
	 *
	 * @since 1.0.0
	 *
	 * @var string
	 */
	public $version = ELICUS_DIVI_GALLERY_EXTENDED_VERSION;

	/**
	 * DGE_DiviGalleryExtended constructor.
	 *
	 * @param string $name
	 * @param array  $args
	 */
	public function __construct( $name = 'divi-gallery-extended', $args = array() ) {
		$this->plugin_dir     = plugin_dir_path( __FILE__ );
		$this->plugin_dir_url = plugin_dir_url( $this->plugin_dir );

		$this->_frontend_js_data = array(
			'ajaxurl'   => admin_url( 'admin-ajax.php' ),
			'ajaxnonce' => wp_create_nonce( 'elicus-divi-gallery-extended-nonce' ),
		);

		add_action( 'wp_enqueue_scripts', array( $this, 'dge_register_scripts' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'dge_fb_enqueue_scripts' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'dge_admin_enqueue_scripts' ) );

		parent::__construct( $name, $args );

		if ( is_admin() ) {
			require_once plugin_dir_path( __FILE__ ) . 'core/class-update.php';
		}

		$this->dge_register_taxonomies();
		$this->dge_update_term_count();

		add_action( 'init', array( $this, 'dge_load_plugin_textdomain' ) );
		add_filter( 'attachment_fields_to_edit', array( $this, 'dge_add_attachment_fields' ), 10, 2 );
		add_filter( 'attachment_fields_to_save', array( $this, 'dge_save_attachment_fields' ), 10, 2 );
		add_filter( 'bulk_actions-upload', array( $this, 'dge_add_bulk_edit_action' ) );
		add_action( 'admin_footer-upload.php', array( $this, 'dge_media_list_table' ) );
		add_filter( 'handle_bulk_actions-upload', array( $this, 'dge_media_bulk_edit' ), 10 , 3 );
		add_action( 'wp_ajax_dge_get_images', array( $this, 'dge_get_images' ) );
		add_action( 'wp_ajax_nopriv_dge_get_images', array( $this, 'dge_get_images' ) );

	}

	public function dge_register_scripts() {
		wp_register_script( 'elicus-isotope-script', "{$this->plugin_dir_url}scripts/isotope.pkgd.min.js", array('jquery'), '3.0.6', true );
		wp_register_script( 'elicus-images-loaded-script', "{$this->plugin_dir_url}scripts/imagesloaded.pkgd.min.js", array('jquery'), '4.1.4', true );
		wp_register_script( 'twbs-pagination-script', "{$this->plugin_dir_url}scripts/twbsPagination.min.js", array('jquery'), '1.4.2', true );
		wp_register_script( 'magnific-popup', "{$this->plugin_dir_url}scripts/magnific_popup.min.js", array('jquery'), '1.0.0', true );
		wp_register_style( 'magnific-popup', "{$this->plugin_dir_url}styles/magnific_popup.min.css", array(), '1.0.0' );

		wp_register_script( 'justified-gallery', "{$this->plugin_dir_url}scripts/justifiedGallery.min.js", array('jquery'), '1.0.0', true );
		wp_register_style( 'justified-gallery', "{$this->plugin_dir_url}styles/justifiedGallery.min.css", array(), '1.0.0' );
	}

	public function dge_fb_enqueue_scripts() {
		if ( et_core_is_fb_enabled() ) {
			wp_enqueue_script( 'elicus-isotope-script' );
			wp_enqueue_script( 'elicus-images-loaded-script' );
			wp_enqueue_script( 'twbs-pagination-script' );

			wp_enqueue_script( 'justified-gallery' );
			wp_enqueue_style( 'justified-gallery' );
		}
	}

	public function dge_admin_enqueue_scripts() {
		$current_screen = get_current_screen();
		if ( 'upload' === $current_screen->base ) {
			wp_enqueue_script( 'dge-inline-edit-script', "{$this->plugin_dir_url}scripts/inline-edit.min.js", array('jquery'), $this->version, false );
			wp_enqueue_style( 'dge-upload-style', "{$this->plugin_dir_url}styles/admin.min.css", array(), $this->version, false );
		}
	}

	public function dge_load_plugin_textdomain() {
		load_plugin_textdomain( 'divi-gallery-extended', false, dirname( plugin_basename( __DIR__ ) ) . '/languages/' );
	}

	public function dge_add_bulk_edit_action($actions) {
		unset( $actions['delete'] );
		$actions['edit'] = esc_html__( 'Edit', 'divi-gallery-extended' );
		$actions['delete'] = esc_html__( 'Delete permanently', 'divi-gallery-extended' );
		return $actions;
	}

	public function dge_media_list_table() {
		$modes = array( 'grid', 'list' );
		$mode  = get_user_option( 'media_library_mode', get_current_user_id() ) ? get_user_option( 'media_library_mode', get_current_user_id() ) : 'grid';
		// phpcs:ignore WordPress,NonceVerification,NoNonce.
		if ( isset( $_GET['mode'] ) && in_array( $_GET['mode'], $modes, true ) ) {
			// phpcs:ignore WordPress,NonceVerification,NoNonce.
			$mode = sanitize_text_field( wp_unslash( $_GET['mode'] ) );
		}
		if ( 'list' === $mode ) {
			require_once plugin_dir_path( __FILE__ ) . 'core/class-media-list-table.php';
			$media_list_table = new EL_Divi_Gallery_Extended_Media_List_Table();
			if ( $media_list_table->has_items() ) {
				$media_list_table->inline_edit();
			}
		}
	}

	public function dge_media_bulk_edit( $location, $doaction, $post_ids ) {
	
		if ( isset( $_REQUEST['dge_bulk_edit'] ) && 'edit' === $doaction ) {

			if ( ! isset( $_REQUEST['dge_bulk_edit_nonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_REQUEST['dge_bulk_edit_nonce'] ) ), 'bulkeditnonce' ) ) {
				return $location;
			}
			
			$post_data = $_REQUEST;

			if ( empty( $post_data ) ) {
				$post_data = &$_POST;
			}
		 
			if ( isset( $post_data['post_type'] ) && 'attachment' !== $post_data['post_type'] ) {
				return false;
			} else {
				$ptype = get_post_type_object( 'attachment' );
			}
		 
			if ( ! current_user_can( $ptype->cap->edit_posts ) ) {
				wp_die( esc_html__( 'Sorry, you are not allowed to edit attachments.' ) );
			}
			
			$reset = array(
				'caption',
				'description',
				'meta_input',
				'tax_input',
			);
		 
			foreach ( $reset as $field ) {
				if ( isset( $post_data[ $field ] ) && ( '' === $post_data[ $field ] || -1 == $post_data[ $field ] ) ) {
					unset( $post_data[ $field ] );
				}
			}
		 
			$tax_input = array();
			if ( isset( $post_data['tax_input'] ) ) {
				foreach ( $post_data['tax_input'] as $tax_name => $terms ) {
					if ( empty( $terms ) ) {
						continue;
					}
					if ( is_taxonomy_hierarchical( $tax_name ) ) {
						$tax_input[ $tax_name ] = array_map( 'absint', $terms );
					} else {
						$comma = _x( ',', 'tag delimiter' );
						if ( ',' !== $comma ) {
							$terms = str_replace( $comma, ',', $terms );
						}
						$tax_input[ $tax_name ] = explode( ',', trim( $terms, " \n\t\r\0\x0B," ) );
					}
				}
			}

			$meta_input = array();
			if ( isset( $post_data['meta_input'] ) ) {
				foreach ( $post_data['meta_input'] as $meta_key => $meta_value ) {
					if ( empty( trim( $meta_value ) ) ) {
						unset( $post_data['meta_input'][$meta_key] );
						continue;
					}
					$meta_input[$meta_key] = sanitize_text_field( $meta_value );
				}
				if ( ! empty( $meta_input ) ) {
					$post_data['meta_input'] = $meta_input;
				} else {
					unset($post_data['meta_input']);
				}
			}
		 
			$updated          = array();
			$skipped          = array();
			$locked           = array();
			$shared_post_data = $post_data;

			foreach ( $post_ids as $post_id ) {
				// Start with fresh post data with each iteration.
				$post_data = $shared_post_data;
		 
				$post_type_object = get_post_type_object( get_post_type( $post_id ) );
		 
				if ( ! isset( $post_type_object ) ||
					! current_user_can( 'edit_post', $post_id )
				) {
					$skipped[] = $post_id;
					continue;
				}
		 
				if ( wp_check_post_lock( $post_id ) ) {
					$locked[] = $post_id;
					continue;
				}
		 
				$post      = get_post( $post_id );
				$tax_names = get_object_taxonomies( $post );
				foreach ( $tax_names as $tax_name ) {
					$current_terms = array();
					$taxonomy_obj = get_taxonomy( $tax_name );
					if ( isset( $tax_input[ $tax_name ] ) && current_user_can( $taxonomy_obj->cap->assign_terms ) ) {
						$new_terms = $tax_input[ $tax_name ];
					} else {
						$new_terms = array();
					}
		 
					if ( $taxonomy_obj->hierarchical ) {
						$current_terms = (array) wp_get_object_terms( $post_id, $tax_name, array( 'fields' => 'ids' ) );
					} else {
						$current_terms = (array) wp_get_object_terms( $post_id, $tax_name, array( 'fields' => 'names' ) );
					}
		 
					$post_data['tax_input'][ $tax_name ] = array_merge( $current_terms, $new_terms );
				}

				$post_data['ID']        	 = $post_id;
				$post_data['post_type']      = $post->post_type;
				$post_data['post_mime_type'] = $post->post_mime_type;

				if ( isset( $post_data['caption'] ) && '' !== trim( $post_data['caption'] ) ) {
					$post_data['post_excerpt'] = $post_data['caption'];
				}

				if ( isset( $post_data['description'] ) && '' !== trim( $post_data['description'] ) ) {
					$post_data['post_content'] = $post_data['description'];
				}

		 		$updated[] = wp_update_post( $post_data );
			}
		   
			$done = array();
			$done['updated'] = count( $updated );
			$done['skipped'] = count( $skipped );
			$done['locked']  = count( $locked );
			$location        = add_query_arg( $done, $location );
		}

		return $location;
	}

	public function dge_add_attachment_fields( $form_fields, $post ) {
		if ( preg_match( "/image/", $post->post_mime_type ) ) {
			$attachment_categories 	= wp_get_object_terms( $post->ID, 'attachment-category', array( 'fields' => 'ids' ) );
			$attachment_categories 	= sanitize_text_field( implode( ',', $attachment_categories ) );
			$categories_checklist	= wp_terms_checklist(
				$post->ID,
				array(
					'taxonomy' => 'attachment-category',
					'echo' => false,
					'checked_ontop' => false,
				)
			);
			if ( $categories_checklist ) {
				$metafield = sprintf(
					'<div class="dge_attachment_metafield">
						<input type="hidden" class="dge_attachment_categories" name="attachments[%1$s][dge_attachment_categories]" value="%2$s" />
						<ul id="attachment-categorychecklist" data-wp-lists="list:attachment-category" class="categorychecklist form-no-clear">%3$s</ul>
					</div>',
					$post->ID,
					$attachment_categories,
					$categories_checklist
				);
			} else {
				$metafield = sprintf(
					'<div class="dge_attachment_metafield"><a href="%1$s">Create category</a></div>',
					esc_url( admin_url( 'edit-tags.php?taxonomy=attachment-category&post_type=attachment' ) )
				);
			}

			$form_fields['dge_attachment_categories'] = array(
				'label'	=> esc_html__( 'Attachment Category', 'divi-gallery-extended' ),
				'input' => 'html',
				'html'	=> $metafield,
				'show_in_edit' => false,
			);

			$attachment_link = esc_url_raw( get_post_meta( $post->ID, 'dge_attachment_link', true ) );

			$form_fields['dge_attachment_link'] = array(
				'label'	=> esc_html__( 'Custom Link', 'divi-gallery-extended' ),
				'input' => 'text',
				'value' => $attachment_link,
				'show_in_edit' => true,
			);
		}

		return $form_fields;
	}

	public function dge_save_attachment_fields( $post, $attachment ) {
	   	if ( isset( $attachment['dge_attachment_categories'] ) ) {
	   		if ( taxonomy_exists( 'attachment-category' ) ) {
	   			$categories = array_map( 'absint', preg_split( '/,+/', $attachment['dge_attachment_categories'] ) );
	   			wp_set_object_terms( $post['ID'], $categories, 'attachment-category', false );
	   		}
		}

		if ( isset( $attachment['dge_attachment_link'] ) ) {
			update_post_meta( $post['ID'], 'dge_attachment_link', esc_url_raw( $attachment['dge_attachment_link'] ) );
		}

		return $post;
	}

	public function dge_register_taxonomies() {
		$labels = array(
			'name'                       => esc_html_x( 'Media Categories', 'Taxonomy General Name', 'divi-gallery-extended' ),
			'singular_name'              => esc_html_x( 'Media Category', 'Taxonomy Singular Name', 'divi-gallery-extended' ),
			'menu_name'                  => esc_html__( 'Media Categories', 'divi-gallery-extended' ),
			'all_items'                  => esc_html__( 'All Media Categories', 'divi-gallery-extended' ),
			'parent_item'                => esc_html__( 'Parent Media Category', 'divi-gallery-extended' ),
			'parent_item_colon'          => esc_html__( 'Parent Media Category:', 'divi-gallery-extended' ),
			'new_item_name'              => esc_html__( 'New Media Category Name', 'divi-gallery-extended' ),
			'add_new_item'               => esc_html__( 'Add New Media Category', 'divi-gallery-extended' ),
			'edit_item'                  => esc_html__( 'Edit Media Category', 'divi-gallery-extended' ),
			'update_item'                => esc_html__( 'Update Media Category', 'divi-gallery-extended' ),
			'view_item'                  => esc_html__( 'View Media Category', 'divi-gallery-extended' ),
			'separate_items_with_commas' => esc_html__( 'Separate categories with commas', 'divi-gallery-extended' ),
			'add_or_remove_items'        => esc_html__( 'Add or remove categories', 'divi-gallery-extended' ),
			'choose_from_most_used'      => esc_html__( 'Choose from the most used', 'divi-gallery-extended' ),
			'popular_items'              => esc_html__( 'Popular Media Categories', 'divi-gallery-extended' ),
			'search_items'               => esc_html__( 'Search Media Categories', 'divi-gallery-extended' ),
			'not_found'                  => esc_html__( 'Not Found', 'divi-gallery-extended' ),
			'no_terms'                   => esc_html__( 'No Media Categories', 'divi-gallery-extended' ),
			'items_list'                 => esc_html__( 'Media Categories list', 'divi-gallery-extended' ),
			'items_list_navigation'      => esc_html__( 'Media Categories list navigation', 'divi-gallery-extended' ),
		);
		$args = array(
			'labels'                => $labels,
			'hierarchical'          => true,
			'public'                => false,
			'show_ui'               => true,
			'show_admin_column'     => true,
			'show_in_nav_menus'     => true,
			'show_tagcloud'         => true,
			'update_count_callback' => '_update_generic_term_count',
		);

		register_taxonomy( 'attachment-category', array( 'attachment' ), $args );
	}

	public function dge_update_term_count() {
		$terms = get_terms( array(
			'taxonomy' => 'attachment-category',
			'fields' => 'ids',
			'hide_empty' => false,
		) );
		if ( $terms && ! is_wp_error( $terms ) && ! empty( $terms ) ) {
			wp_update_term_count_now( $terms, 'attachment-category');
		}
	}

	public function dge_get_images() {
		if ( ! isset( $_POST['dge_get_images_nonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['dge_get_images_nonce'] ) ), 'elicus-divi-gallery-extended-nonce' ) ) {
			return;
		}

		if ( ! isset( $_POST['props'] ) ) {
			return;
		}

		$defaults = array(
			'number_of_images'   => 20,
			'offset_number'      => 0,
			'gallery_order_by'   => 'date',
			'gallery_order'      => 'DESC',
			'include_categories' => '',
			'image_size'         => 'medium',
			'enable_lightbox'    => 'on',
			'link_target'        => 'off',
			'enable_overlay'     => 'off',
			'overlay_icon'       => '',
			'show_title'         => 'off',
			'show_caption'       => 'off',
			'title_area'         => 'lightbox',
			'caption_area'       => 'lightbox',
			'zoom_icon'          => '',
			'link_icon'          => '',
			'title_level'        => 'h4',
			'page'               => 1,
			'total_pages'        => 1,
			'tax_query_field'    => 'term_id',
		);

		foreach ( $defaults as $key => $default ) {
			// phpcs:ignore ET.Sniffs.ValidatedSanitizedInput.InputNotSanitized
			if ( isset( $_POST['props'][$key] ) && et_()->includes( $_POST['props'][$key], '%' ) ) {
				// phpcs:ignore ET.Sniffs.ValidatedSanitizedInput.InputNotSanitized
				$prepared_value  = preg_replace( '/%([a-f0-9]{2})/', '%_$1', $_POST['props'][$key] );
				${$key} = preg_replace( '/%_([a-f0-9]{2})/', '%$1', trim( sanitize_text_field( wp_unslash( $prepared_value ) ) ) );
			} else {
				// phpcs:ignore ET.Sniffs.ValidatedSanitizedInput.InputNotSanitized
				${$key} = trim( sanitize_text_field( wp_unslash( et_()->array_get( $_POST['props'], $key, $default ) ) ) );	
			}
		}

		$processed_title_level = esc_html( $title_level );
		$valid_heading_tag 	   = array( 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' );
		if ( ! in_array( $processed_title_level, $valid_heading_tag, true ) ) {
			$processed_title_level = esc_html( 'h4' );
		}

		$number_of_images = absint( $number_of_images );
		$offset_number 	  = absint( $offset_number );
		$page 			  = absint( $page );
		$offset_number 	  = ( $number_of_images * ( $page - 1 ) ) + $offset_number;
		
		$args = array(
			'post_type'      => 'attachment',
			'posts_per_page' => $number_of_images,
			'post_status'    => 'any',
			'orderby'        => $gallery_order_by,
			'order'          => $gallery_order,
			'offset'		 => $offset_number,
			'post_mime_type' => 'image/jpeg,image/gif,image/jpg,image/png,image/webp',
		);

		if ( '' !== $include_categories ) {
			if ( 'slug' === $tax_query_field ) {
				$include_categories = array_map( 'sanitize_text_field', explode( ',', $include_categories ) );	
			} else {
				$include_categories = array_map( 'intval', explode( ',', $include_categories ) );	
			}
			$args['tax_query'] = array( array(
				'taxonomy' => 'attachment-category',
				'field'    => $tax_query_field,
				'terms'    => $include_categories,
				'operator' => 'IN',
			) );
		}

		$query = new WP_Query( $args );

		if ( $query->have_posts() ) {
			$image_ids = wp_list_pluck( $query->posts, 'ID' );

			if ( 'on' === $enable_overlay ) {
				$overlay_output = sprintf(
					'<span class="et_overlay et_pb_inline_icon" data-icon="%1$s"></span>',
					esc_attr( $overlay_icon )
				);
			}

			$gallery_items = '';
			$gallery_item_class = 'el_masonry_gallery_item_page_' . $page;
			$allowed_tags = array(
				'div' => array(
					'class' => true,
					'id' => true,
				),
				'p' => array(
					'class' => true,
					'id' => true,
				),
				'h1' => array(
					'class' => true,
					'id' => true,
				),
				'h2' => array(
					'class' => true,
					'id' => true,
				),
				'h3' => array(
					'class' => true,
					'id' => true,
				),
				'h4' => array(
					'class' => true,
					'id' => true,
				),
				'h5' => array(
					'class' => true,
					'id' => true,
				),
				'h6' => array(
					'class' => true,
					'id' => true,
				),
				'ul' => array(
					'class' => true,
					'id' => true,
				),
				'ol' => array(
					'class' => true,
					'id' => true,
				),
				'li' => array(
					'class' => true,
					'id' => true,
				),
				'a' => array(
					'href'  => true,
					'title' => true,
					'class' => true,
					'id' => true,
					'target' => true,
				),
				'abbr' => array(
					'title' => true,
				),
				'acronym' => array(
					'title' => true,
				),
				'b' => array(),
				'blockquote' => array(
					'cite' => true,
				),
				'cite' => array(),
				'code' => array(),
				'del'  => array(
					'datetime' => true,
				),
				'em' => array(),
				'i' => array(),
				'q' => array(
					'cite' => true,
				),
				's' => array(),
				'strike' => array(),
				'strong' => array(),
				'span' => array(
					'class'  => true,
					'id' => true,
				),
			);

			foreach ( $image_ids as $image_id ) {

				$image_link = get_post_meta( intval( $image_id ), 'dge_attachment_link', true );

				$title = '';
				if ( 'on' === $show_title && '' !== trim( wptexturize( get_the_title( $image_id ) ) ) ) {
					$title_text = wp_kses( get_the_title( $image_id ), $allowed_tags );
					if ( 'link' === $enable_lightbox && 'overlay' === $title_area ) {
						if ( '' !== $image_link ) {
							$abs_link = sprintf(
								'<a class="dge_abs_link" href="%1$s"%2$s></a>',
								esc_url( $image_link ),
								'on' === $link_target ? ' target="_blank"' : ''
							);
							$title_text .= $abs_link;
						}
					}
					$title = sprintf(
						'<%1$s class="el_masonry_gallery_item_title">%2$s</%1$s>',
						$processed_title_level,
						et_core_esc_previously( $title_text )
					);
				}
				$caption = '';
				if ( 'on' === $show_caption && '' !== trim( wp_get_attachment_caption( $image_id ) ) ) {
					$caption_text = wp_kses( wp_get_attachment_caption( $image_id ), $allowed_tags );
					if ( 'link' === $enable_lightbox && 'overlay' === $caption_area ) {
						if ( '' !== $image_link ) {
							$abs_link = sprintf(
								'<a class="dge_abs_link" href="%1$s"%2$s></a>',
								esc_url( $image_link ),
								'on' === $link_target ? ' target="_blank"' : ''
							);
							$caption_text .= $abs_link;
						}
					}
					$caption = sprintf(
						'<div class="el_masonry_gallery_item_caption">%1$s</div>',
						et_core_esc_previously( $caption_text )
					);
				}

				$title_and_caption = '';
				if ( '' !== $title || '' !== $caption ) {
					$title_and_caption = sprintf(
						'<div class="el_masonry_gallery_title_caption_wrapper">%1$s %2$s</div>',
						et_core_intentionally_unescaped( $title, 'html' ),
						et_core_intentionally_unescaped( $caption, 'html' )
					);
				}

				$categories    = get_the_terms( $image_id, 'attachment-category' );
				$image_classes = array( 
					"attachment-$image_size",
					"size-$image_size",
					"no-lazyload",
					"skip-lazy",
				);

				$image_atts = array();
				if ( $categories && ! is_wp_error( $categories ) && ! empty( $categories ) ) {
					$categories_ids = wp_list_pluck( $categories, 'term_id' );
					$categories 	= wp_list_pluck( $categories, 'slug' );
					$image_classes	= array_merge( 
						$image_classes,
						$categories
					);
					$image_atts['data-categories'] = implode( ',', $categories_ids );
				}

				$image_atts['class'] = implode( ' ', $image_classes );

				if ( 'on' === $enable_overlay && 'zoom_n_link' === $enable_lightbox ) {
					$overlay_link_icon = '';
					if ( ! empty( $image_link ) ) {
						$overlay_link_icon = sprintf(
							'<a class="dge-overlay-icon dge-overlay-link" href="%1$s" %3$s>%2$s</a>',
							esc_url( $image_link ),
							esc_attr( $link_icon ),
							'on' === $link_target ? ' target="_blank"' : ''
						);
					}
					$overlay_output = sprintf(
						'<span class="et_overlay dge-overlay-with-icons">
							<a class="dge-overlay-icon dge-overlay-lightbox" href="%3$s" data-mfp-src="%3$s">%1$s</a>
							%2$s
						</span>',
						esc_attr( $zoom_icon ),
						$overlay_link_icon,
						esc_url( wp_get_attachment_url( intval( $image_id ) ) )
					);
				}

				if ( 'on' === $enable_lightbox ) {
					$gallery_items .= sprintf(
						'<div data-mfp-src="%4$s" class="el_masonry_gallery_item %5$s">
							<div class="el_masonry_gallery_image_wrapper">%1$s %2$s</div>
							%3$s
						</div>',
						et_core_intentionally_unescaped( wp_get_attachment_image( intval( $image_id ), sanitize_text_field( $image_size ), false, $image_atts ), 'html' ),
						isset( $overlay_output ) ? $overlay_output : '',
						et_core_intentionally_unescaped( $title_and_caption, 'html' ),
						esc_url( wp_get_attachment_url( intval( $image_id ) ) ),
						esc_attr( $gallery_item_class )
					);
				} else if ( 'link' === $enable_lightbox ) {
					$link = get_post_meta( intval( $image_id ), 'dge_attachment_link', true );
					if ( '' !== $link ) {
						$image = sprintf(
							'<a href="%1$s"%2$s>%3$s</a>',
							esc_url( $link ),
							'on' === $link_target ? ' target="_blank"' : '',
							et_core_intentionally_unescaped( wp_get_attachment_image( intval( $image_id ), sanitize_text_field( $image_size ), false, $image_atts ), 'html' )
						);
					} else {
						$image = et_core_intentionally_unescaped( wp_get_attachment_image( intval( $image_id ), sanitize_text_field( $image_size ), false, $image_atts ), 'html' );
					}

					$gallery_items .= sprintf(
						'<div class="el_masonry_gallery_item %4$s">
							<div class="el_masonry_gallery_image_wrapper">%1$s %2$s</div>
							%3$s
						</div>',
						$image,
						isset( $overlay_output ) ? $overlay_output : '',
						et_core_intentionally_unescaped( $title_and_caption, 'html' ),
						esc_attr( $gallery_item_class )
					);
				} else {
					$gallery_items .= sprintf(
						'<div class="el_masonry_gallery_item %4$s">
							<div class="el_masonry_gallery_image_wrapper">%1$s %2$s</div>
							%3$s
						</div>',
						et_core_intentionally_unescaped( wp_get_attachment_image( intval( $image_id ), sanitize_text_field( $image_size ), false, $image_atts ), 'html' ),
						isset( $overlay_output ) ? $overlay_output : '',
						et_core_intentionally_unescaped( $title_and_caption, 'html' ),
						esc_attr( $gallery_item_class )
					);
				}
			}

			$data = array(
				'success' => true,
				'items'   => $gallery_items,
			);

			if ( 1 === $page ) {
				if ( '' !== $args['offset'] && ! empty( $args['offset'] ) ) {
					$data['total_pages'] = intval( ceil( ( $query->found_posts - $args['offset'] ) / $args['posts_per_page'] ) );
				} else {
					$data['total_pages'] = intval( ceil( $query->found_posts / $args['posts_per_page'] ) );
				}
			}
		} else {
			$data = array(
				'success' => false,
				'message' => esc_html__( 'No images found.', 'divi-gallery-extended' ),
			);
		}

		wp_send_json( $data );
	}

	public static function dge_get_taxonomies_options( $args = array(), $all = true, $key = 'term_id' ) {
		$defaults = array(
			'taxonomy'   => 'attachment-category',
			'hide_empty' => false,
		);

		$args = wp_parse_args( $args, $defaults );

		// Get the terms
		$terms = get_terms( $args );

		$options = array_combine(
			wp_list_pluck( $terms, $key ),
			wp_list_pluck( $terms, 'name' )
		);

		if ( $all === true ) {
			$options = array_replace( array( 'all' => esc_html__( 'All', 'divi-gallery-extended' ) ), $options );
		}

		return $options;
	}

}

new EL_DiviGalleryExtended;
