<?php
/**
 * Elementor Dynamic Tag — PowerSuite Custom Field.
 *
 * @package CustomFields
 */

namespace CustomFields;

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

class Elementor_CF_Field_Tag extends \Elementor\Core\DynamicTags\Tag {

	public function get_name(): string {
		return 'wpps-cf-field';
	}

	public function get_title(): string {
		return __( 'PowerSuite Custom Field', 'wp-powersuite' );
	}

	public function get_group(): array {
		return [ 'wp-powersuite-cf' ];
	}

	public function get_categories(): array {
		$categories = [
			\Elementor\Modules\DynamicTags\Module::TEXT_CATEGORY,
			\Elementor\Modules\DynamicTags\Module::URL_CATEGORY,
		];

		if ( defined( '\Elementor\Modules\DynamicTags\Module::POST_CONTENT_CATEGORY' ) ) {
			$categories[] = \Elementor\Modules\DynamicTags\Module::POST_CONTENT_CATEGORY;
		}

		return array_values( array_unique( $categories ) );
	}

	protected function register_controls(): void {
		$field_options = [ '' => __( '— Select —', 'wp-powersuite' ) ];

		foreach ( FieldOutput::integratableFields() as $field ) {
			$field_options[ $field['selection'] ] = $field['group_label'] . ' — ' . $field['field_label'];
		}

		if ( count( $field_options ) === 1 ) {
			$field_options = [ '' => __( '— No fields configured —', 'wp-powersuite' ) ];
		}

		$this->add_control(
			'cf_field',
			[
				'label'   => __( 'Custom Field', 'wp-powersuite' ),
				'type'    => \Elementor\Controls_Manager::SELECT,
				'options' => $field_options,
			]
		);

		$this->add_control(
			'cf_format',
			[
				'label'   => __( 'Output', 'wp-powersuite' ),
				'type'    => \Elementor\Controls_Manager::SELECT,
				'options' => [
					'display' => __( 'Display value', 'wp-powersuite' ),
					'raw'     => __( 'Raw stored value', 'wp-powersuite' ),
					'html'    => __( 'HTML', 'wp-powersuite' ),
					'url'     => __( 'URL', 'wp-powersuite' ),
					'text'    => __( 'Plain text', 'wp-powersuite' ),
				],
				'default' => 'display',
			]
		);
	}

	public function render(): void {
		$selection = $this->get_settings( 'cf_field' );
		if ( empty( $selection ) || ! is_string( $selection ) ) {
			return;
		}

		$parts = explode( ':', $selection, 2 );
		if ( count( $parts ) !== 2 ) {
			return;
		}

		$group_key  = sanitize_key( $parts[0] );
		$field_name = sanitize_key( $parts[1] );
		if ( $group_key === '' || $field_name === '' ) {
			return;
		}

		$post_id = get_the_ID();
		if ( ! $post_id ) {
			return;
		}

		echo FieldOutput::render(
			$group_key,
			$field_name,
			(int) $post_id,
			[
				'format' => sanitize_key( (string) $this->get_settings( 'cf_format' ) ),
			]
		);
	}
}
