<?php
/**
 * Dynamic Tag: ACF Gallery Field
 *
 * @package captain-widgets-kit
 * @since   1.1.0
 */

use Elementor\Core\DynamicTags\Data_Tag;
use Elementor\Modules\DynamicTags\Module;
use Elementor\Controls_Manager;

if ( ! defined( 'ABSPATH' ) ) {
	exit; 
}

/**
 * Class Captwiki_Tag_ACF_Gallery
 * Returns an ACF gallery field as an Elementor gallery dynamic tag.
 */
class Captwiki_Tag_ACF_Gallery extends Data_Tag {
	/**
	 * Get tag name.
	 *
	 * @return string
	 */
	public function get_name(): string {
		return 'captwiki-tag-acf-gallery'; }
	/**
	 * Get tag title.
	 *
	 * @return string
	 */
	public function get_title(): string {
		return esc_html__( 'ACF Gallery Field', 'captain-widgets-kit' ); }
	/**
	 * Get tag group.
	 *
	 * @return array
	 */
	public function get_group(): array {
		return array( 'captwiki-acf' ); }
	/**
	 * Get tag categories.
	 *
	 * @return array
	 */
	public function get_categories(): array {
		return array( Module::GALLERY_CATEGORY ); }
	/**
	 * Check whether settings are required.
	 *
	 * @return bool
	 */
	public function is_settings_required(): bool {
		return true; }

	/**
	 * Register tag controls.
	 *
	 * @return void
	 */
	protected function register_controls(): void {
		$this->add_control(
			'captwiki_acf_field_key',
			array(
				'label'  => esc_html__( 'Key', 'captain-widgets-kit' ),
				'type'   => Controls_Manager::SELECT,
				'groups' => $this->captwiki_get_acf_gallery_groups(),
			)
		);
	}

	/**
	 * Build grouped ACF field options for gallery field type.
	 *
	 * @since  1.1.0
	 * @return array<int, array<string, mixed>>
	 */
	protected function captwiki_get_acf_gallery_groups(): array {
		if ( ! function_exists( 'acf_get_field_groups' ) ) {
			return array(); }
		$groups = array();
		foreach ( acf_get_field_groups() as $group ) {
			$fields = acf_get_fields( $group['key'] );
			if ( empty( $fields ) ) {
				continue; }
			$options = array();
			foreach ( $fields as $f ) {
				if ( 'gallery' === $f['type'] ) {
					$options[ $f['name'] ] = $f['label']; }
			}
			if ( $options ) {
				$groups[] = array(
					'label'   => $group['title'],
					'options' => $options,
				); }
		}
		return $groups;
	}

	/**
	 * Get tag value.
	 *
	 * @param array $options Function parameter.
	 * @return mixed
	 */
	public function get_value( array $options = array() ) {
		$key = $this->get_settings_for_display( 'captwiki_acf_field_key' );
		if ( empty( $key ) || ! function_exists( 'get_field' ) ) {
			return array(); }
		$value = ( is_tax() || is_category() || is_tag() )
			? get_field( $key, 'term_' . get_queried_object_id() )
			: get_field( $key, get_the_ID() );
		if ( empty( $value ) || ! is_array( $value ) ) {
			return array(); }
		$images = array();
		foreach ( $value as $image ) {
			if ( is_array( $image ) && ! empty( $image['ID'] ) ) {
				$images[] = array( 'id' => (int) $image['ID'] ); } elseif ( is_numeric( $image ) ) {
				$images[] = array( 'id' => (int) $image ); }
		}
		return $images;
	}
}
