<?php
/*
Plugin Name: Divi Dynamic Gallery
Plugin URI:  https://diviplugins.com/downloads/divi-dynamic-gallery/
Description: Displays a masonry gallery from images selected within the module or from images defined in a custom field.
Version:     1.1
Author:      DiviPlugins
Author URI:  https://diviplugins.com
License:     GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: dpddg-dp-divi-dynamic-gallery
Domain Path: /languages

DP Divi Dynamic Gallery is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
any later version.

DP Divi Dynamic Gallery is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with DP Divi Masonry Gallery. If not, see https://www.gnu.org/licenses/gpl-2.0.html.
*/
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

define( 'DPDDG_VERSION', '1.1' );
define( 'DPDDG_URL', plugin_dir_url( __FILE__ ) );
define( 'DPDDG_DIR', plugin_dir_path( __FILE__ ) );
define( 'DPDDG_STORE_URL', 'https://diviplugins.com/' );
define( 'DPDDG_ITEM_NAME', 'Divi Dynamic Gallery' );
define( 'DPDDG_ITEM_ID', '141447' );

if ( ! function_exists( 'dpddg_initialize_extension' ) ) {
	/**
	 * Creates the extension's main class instance.
	 *
	 * @since 1.0.0
	 */
	function dpddg_initialize_extension() {
		require_once plugin_dir_path( __FILE__ ) . 'includes/DpDiviDynamicGallery.php';
	}

	add_action( 'divi_extensions_init', 'dpddg_initialize_extension' );
}

if ( ! function_exists( 'dpddg_register_scripts_and_styles' ) ) {
	/**
	 * Register/enqueue scripts and styles
	 */
	function dpddg_register_scripts_and_styles() {
		if ( defined( 'ET_BUILDER_URI' ) ) {
			wp_register_script( 'magnific-popup', ET_BUILDER_URI . '/feature/dynamic-assets/assets/js/magnific-popup.js', array( 'jquery' ), ET_CORE_VERSION, true );
		}
	}

	add_action( 'wp_enqueue_scripts', 'dpddg_register_scripts_and_styles', 20 );
}

if ( ! function_exists( 'dpddg_get_images_data' ) ) {
	/**
	 * @param $props
	 *
	 * @return array
	 */
	function dpddg_get_images_data( $props ) {
		$images_data = array(
			'filters' => array(),
			'images'  => array()
		);
		$gallery_ids = array();
		if ( ( 'on' === $props['conditional_tags']['is_singular'] || 'true' === $props['conditional_tags']['is_singular'] ) && 'on' === $props['dynamic_content'] ) {
			if ( $props['dynamic_content_src'] === 'cf' && ! empty( $props['dynamic_content_field'] ) ) {
				if ( is_plugin_active( 'types/wpcf.php' ) ) {
					$toolset_repeating_image = get_post_meta( $props['the_ID'], 'wpcf-' . $props['dynamic_content_field'] );
					if ( ! empty( $toolset_repeating_image ) ) {
						foreach ( $toolset_repeating_image as $image_url ) {
							$gallery_ids[] = et_get_attachment_id_by_url( $image_url );
						}
					}
				}
				if ( empty( $gallery_ids ) ) {
					if ( class_exists( 'ACF' ) ) {
						$field_object = get_field_object( $props['dynamic_content_field'], $props['the_ID'] );
						if ( isset( $field_object['type'] ) && $field_object['type'] === 'photo_gallery' ) {
							if ( is_array( $field_object['value'] ) ) {
								foreach ( $field_object['value'] as $value ) {
									$gallery_ids[] = $value['id'];
								}
							} else {
								$gallery_ids = explode( ',', $field_object['value'] );
							}
						} else {
							$gallery_ids = get_field( $props['dynamic_content_field'], $props['the_ID'], false );
						}
					} else {
						$field_value = get_post_meta( $props['the_ID'], $props['dynamic_content_field'], true );
						if ( is_array( $field_value ) ) {
							$gallery_ids = $field_value;
						} else {
							if ( substr_count( $field_value, ',' ) ) {
								$gallery_ids = explode( ',', $field_value );
							} else {
								$gallery_ids = get_post_meta( $props['the_ID'], $props['dynamic_content_field'] );
							}
						}
					}
				}
			}
			if ( $props['dynamic_content_src'] === 'woo' && function_exists( 'wc_get_product' ) && get_post_type( $props['the_ID'] ) === 'product' ) {
				$product = wc_get_product( $props['the_ID'] );
				if ( $product ) {
					$gallery_ids = $product->get_gallery_image_ids();
				}
			}
		} else if ( isset( $props['gallery_ids'] ) ) {
			$gallery_ids = explode( ',', $props['gallery_ids'] );
		}
		if ( is_array( $gallery_ids ) && ! empty( $gallery_ids ) ) {
			$query_args            = array(
				'post_status'    => 'any',
				'posts_per_page' => - 1,
				'post_type'      => 'attachment',
				'post__in'       => apply_filters( 'dpddg_custom_images_ids', $gallery_ids, $props ),
				'order'          => $props['order'],
				'orderby'        => $props['orderby'],
				'post_mime_type' => 'image',
			);
			$query                 = new WP_Query( apply_filters( 'dpddg_query_args', $query_args, $props ) );
			$overlay_data          = explode( '|', $props['overlay_data'] );
			$lightbox_data         = explode( '|', $props['lightbox_data'] );
			$already_added_filters = array();
			if ( $query->have_posts() ) {
				while ( $query->have_posts() ) {
					$query->the_post();
					$image_data             = array();
					$image_id               = get_the_ID();
					$image_data['id']       = $image_id;
					$image_data['image']    = wp_get_attachment_image( $image_id, $props['image_size'], 'false', array( 'class' => 'dp-ddg-image' ) );
					$image_data['metadata'] = wp_get_attachment_metadata( $image_id );
					$image_data['url']      = wp_get_attachment_url( $image_id );
					$image_data['ratio']    = 0;
					if ( isset( $image_data['metadata'] ) ) {
						$image_size = isset( $image_data['metadata']['sizes'][ $props['image_size'] ] ) ? $image_data['metadata']['sizes'][ $props['image_size'] ] : false;
						if ( $image_size ) {
							$image_data['ratio'] = ( $image_size['height'] / $image_size['width'] ) * 100;
						} else {
							if ( intval( $image_data['metadata']['width'] ) ) {
								$image_data['ratio'] = ( $image_data['metadata']['height'] / $image_data['metadata']['width'] ) * 100;
							}
						}
					}
					if ( 'on' === $props['show_title'] || 'on' === $props['show_caption'] || 'on' === $props['show_description'] || 'on' === $props['show_overlay'] ) {
						if ( 'on' === $props['show_title'] || 'on' === $overlay_data[0] || 'on' === $lightbox_data[0] ) {
							$image_data['title'] = get_the_title( $image_id );
						}
						if ( 'on' === $props['show_caption'] || 'on' === $overlay_data[1] || 'on' === $lightbox_data[1] ) {
							$image_data['caption'] = wp_get_attachment_caption( $image_id );
						}
						if ( 'on' === $props['show_description'] || 'on' === $overlay_data[2] || 'on' === $lightbox_data[2] ) {
							$image_data['description'] = get_the_content( null, false, $image_id );
						}
					}
					if ( 'on' === $props['show_filters'] && ! empty( $props['filters_taxonomy'] ) ) {
						$image_data['terms'] = dpddg_extract_posts_terms( $image_id, $props );
						if ( is_array( $image_data['terms'] ) ) {
							foreach ( $image_data['terms'] as $term ) {
								if ( ! in_array( $term['term_id'], $already_added_filters ) ) {
									$images_data['filters'][] = $term;
									$already_added_filters[]  = $term['term_id'];
								}
							}
						}
					}
					$images_data['images'][] = $image_data;
				}
				if ( ! empty( $images_data['filters'] ) ) {
					if ( isset( $props['filter_order_by'] ) && $props['filter_order_by'] !== 'none' ) {
						$ordered_terms         = [];
						$filter_terms_args     = [
							'taxonomy'   => $props['filters_taxonomy'],
							'hide_empty' => 0,
							'order'      => $props['filter_order'],
							'orderby'    => $props['filter_order_by'],
							'include'    => isset( $props['filter_order_custom'] ) && $props['filter_order_by'] === 'include' ? $props['filter_order_custom'] : []
						];
						$filter_terms_in_order = get_terms( $filter_terms_args );
						if ( ! is_wp_error( $filter_terms_in_order ) ) {
							foreach ( $filter_terms_in_order as $term ) {
								foreach ( $images_data['filters'] as $filter ) {
									if ( $filter['term_id'] === $term->term_id ) {
										$ordered_terms[] = $filter;
										break;
									}
								}
							}
						}
						if ( ! empty( $ordered_terms ) ) {
							$images_data['filters'] = $ordered_terms;
						}
					} else {
						if ( isset( $props['filter_order'] ) && $props['filter_order'] === 'DESC' ) {
							$images_data['filters'] = array_reverse( $images_data['filters'] );
						}
					}
				}
			} else {
				$images_data['no_results'] = $props['no_results'];
			}
			wp_reset_postdata();
		} else {
			$images_data['no_results'] = $props['no_results'];
		}

		return $images_data;
	}
}

if ( ! function_exists( 'dpddg_get_images_data_ajax' ) ) {
	/**
	 *
	 */
	function dpddg_get_images_data_ajax() {
		check_ajax_referer( 'dpddg_get_images_data_action', 'nonce_images_data' );
		$post     = $_POST;
		$response = array();
		if ( isset( $post['props'] ) ) {
			$props                     = $post['props'];
			$props['the_ID']           = $post['postId'];
			$props['conditional_tags'] = $post['conditionalTags'];
			$response                  = dpddg_get_images_data( $props );
		} else {
			$response['error'] = __( 'Missing module data.', 'dpddg-dp-divi-dynamic-gallery' );
		}
		wp_send_json( $response );
	}

	add_action( 'wp_ajax_dpddg_get_images_data_action', 'dpddg_get_images_data_ajax' );
}

if ( ! function_exists( 'dpddg_get_media_taxonomies_ajax' ) ) {
	/**
	 *
	 */
	function dpddg_get_media_taxonomies_ajax() {
		check_ajax_referer( 'dpddg_get_media_taxonomies_action', 'nonce_taxonomies' );
		$media_taxonomies = get_object_taxonomies( 'attachment', 'objects' );
		$options          = array();
		if ( is_array( $media_taxonomies ) && ! empty( $media_taxonomies ) ) {
			$options[] = array(
				'value' => 'no_tax_selected',
				'label' => __( 'Select Taxonomy', 'dpddg-dp-divi-dynamic-gallery' )
			);
			foreach ( $media_taxonomies as $taxonomy ) {
				$options[] = array(
					'value' => $taxonomy->name,
					'label' => $taxonomy->label
				);
			}
		} else {
			$options[] = array(
				'value' => 'no_tax',
				'label' => __( 'No taxonomies found for media', 'dpddg-dp-divi-dynamic-gallery' )
			);
		}
		wp_send_json( $options );
	}

	add_action( 'wp_ajax_dpddg_get_media_taxonomies_action', 'dpddg_get_media_taxonomies_ajax' );
}

if ( ! function_exists( 'dpddg_extract_posts_terms' ) ) {
	/**
	 *
	 */
	function dpddg_extract_posts_terms( $attachment_id, $props ) {
		$all_terms = array();
		if ( taxonomy_exists( $props['filters_taxonomy'] ) ) {
			$terms = wp_get_post_terms( $attachment_id, $props['filters_taxonomy'] );
			if ( is_array( $terms ) && ! empty( $terms ) ) {
				foreach ( $terms as $term ) {
					$term_data   = array(
						'term_id' => $term->term_id,
						'name'    => $term->name,
						'slug'    => $term->slug,
						'parent'  => $term->parent,
						'link'    => get_term_link( $term->term_id ),
					);
					$all_terms[] = $term_data;
				}
			}
		}

		return $all_terms;
	}
}

if ( ! function_exists( 'dpddg_admin_scripts_and_styles' ) ) {
	/**
	 * Register/enqueue admin scripts and styles
	 */
	function dpddg_admin_scripts_and_styles() {
		wp_enqueue_style( 'dpddg_admin_styles', DPDDG_URL . 'admin/dp-ddg-admin.min.css', array(), DPDDG_VERSION, 'all' );
	}

	add_action( 'admin_enqueue_scripts', 'dpddg_admin_scripts_and_styles' );
}

if ( ! function_exists( 'dpddg_get_thumbnail_sizes_options' ) ) {
	/**
	 *
	 */
	function dpddg_get_thumbnail_sizes_options() {
		global $_wp_additional_image_sizes;
		$images_sizes = array(
			array( 'value' => 'full', 'label' => 'Original Size' ),
			array(
				'value' => 'thumbnail',
				'label' => 'Thumbnail - (' . get_option( "thumbnail_size_w" ) . 'x' . get_option( "thumbnail_size_w" ) . ')'
			),
			array(
				'value' => 'medium',
				'label' => 'Medium - (' . get_option( "medium_size_w" ) . 'x' . get_option( "medium_size_w" ) . ')'
			),
			array(
				'value' => 'medium_large',
				'label' => 'Medium Large - (' . get_option( "medium_large_size_w" ) . 'x' . get_option( "medium_large_size_w" ) . ')'
			),
			array(
				'value' => 'large',
				'label' => 'Large - (' . get_option( "large_size_w" ) . 'x' . get_option( "large_size_w" ) . ')'
			)
		);
		foreach ( $_wp_additional_image_sizes as $size_key => $size ) {
			$images_sizes[] = array(
				'value' => $size_key,
				'label' => trim( ucwords( str_replace( array(
						'et-pb-',
						'--',
						'-',
						'_'
					), ' ', $size_key ) ) ) . ' - (' . $size['width'] . 'x' . $size['height'] . ')'
			);
		}

		return $images_sizes;
	}
}

if ( ! function_exists( 'dpddg_ajax_get_thumbnail_sizes_options' ) ) {
	function dpddg_ajax_get_thumbnail_sizes_options() {
		wp_send_json( dpddg_get_thumbnail_sizes_options() );
	}

	add_action( 'wp_ajax_get_thumbnail_sizes_options', 'dpddg_ajax_get_thumbnail_sizes_options' );
}

if ( ! function_exists( 'dpddg_admin_page_updater_license' ) ) {

	function dpddg_admin_page_updater_license() {
		require_once DPDDG_DIR . 'edd/class-dp-page.php';
		require_once DPDDG_DIR . 'edd/class-dp-ddg-updater.php';
		require_once DPDDG_DIR . 'edd/class-dp-ddg-license.php';
		$dp_page = new DiviPlugins_Menu_Page();
		add_action( 'admin_menu', array( $dp_page, 'add_dp_page' ) );
		$license = new Dp_Ddg_License();
		add_action( 'init', array( $license, 'init_plugin_updater' ), 0 );
		add_action( 'diviplugins_page_add_license', array( $license, 'license_html' ) );
		add_action( 'admin_init', array( $license, 'register_license_option' ) );
		add_action( 'admin_init', array( $license, 'activate_license' ) );
		add_action( 'admin_init', array( $license, 'deactivate_license' ) );
		add_action( 'admin_notices', array( $license, 'notice_license_activation_result' ) );
		if ( get_option( 'dpddg_license_status' ) !== 'valid' ) {
			add_action( 'admin_notices', array( $license, 'notice_activation_license_require' ) );
		}
	}

	dpddg_admin_page_updater_license();

}

if ( ! function_exists( 'dpddg_add_plugin_row_meta' ) ) {

	function dpddg_add_plugin_row_meta( $links, $file ) {
		if ( plugin_basename( 'dp-divi-dynamic-gallery/dp-divi-dynamic-gallery.php' ) === $file ) {
			$links['license'] = sprintf( '<a href="%s"> %s </a>', admin_url( 'plugins.php?page=dp_divi_plugins_menu' ), __( 'License', 'dpddg-dp-divi-dynamic-gallery' ) );
			$links['support'] = sprintf( '<a href="%s" target="_blank"> %s </a>', 'https://diviplugins.com/documentation/divi-dynamic-gallery/', __( 'Get support', 'dpddg-dp-divi-dynamic-gallery' ) );
		}

		return $links;
	}

	add_filter( 'plugin_row_meta', 'dpddg_add_plugin_row_meta', 10, 2 );
}