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

use Elementor\Core\DynamicTags\Tag;
use Elementor\Modules\DynamicTags\Module;
use Elementor\Controls_Manager;
if ( ! defined( 'ABSPATH' ) ) {
	exit; }
/**
 * Class Captwiki_Tag_ACF_URL
 * Outputs an ACF URL field as an Elementor URL dynamic tag.
 */
class Captwiki_Tag_ACF_URL extends Tag {
	/**
	 * Get tag name.
	 *
	 * @return string
	 */
	public function get_name(): string {
		return 'captwiki-tag-acf-url'; }
	/**
	 * Get tag title.
	 *
	 * @return string
	 */
	public function get_title(): string {
		return esc_html__( 'ACF URL 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::URL_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_url_groups(),
			)
		);
	}

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

	/**
	 * Render tag output.
	 *
	 * @return void
	 */
	public function render(): void {
		$field_name = $this->get_settings( 'captwiki_acf_field_key' );
		if ( empty( $field_name ) || ! function_exists( 'get_field' ) ) {
			return; }
		$url = ( is_tax() || is_category() || is_tag() )
			? get_field( $field_name, get_queried_object() )
			: get_field( $field_name, get_the_ID() );
		if ( ! empty( $url ) ) {
			echo esc_url( $url ); }
	}
}
