<?php
/**
 * Elementor Dynamic Tag - PowerSuite Option
 *
 * Outputs a value from an Options Page Builder field.
 *
 * @package OptionsPageBuilder
 * @since 1.0.0
 */

namespace OptionsPageBuilder;

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

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

	public function get_name(): string {
		return 'wpps-opb-option';
	}

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

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

	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 ( $this->getPages() as $p ) {
			if ( ! is_array( $p ) || empty( $p['slug'] ) || empty( $p['fields'] ) || ! is_array( $p['fields'] ) ) {
				continue;
			}

			$slug       = sanitize_key( $p['slug'] );
			$page_label = $p['page_title'] ?? $p['menu_title'] ?? $slug;

			foreach ( $p['fields'] as $field ) {
				if ( ! is_array( $field ) || in_array( $field['type'] ?? '', [ 'group', 'message' ], true ) ) {
					continue;
				}

				$field_id = $field['field_id'] ?? $field['id'] ?? '';
				if ( $field_id === '' ) {
					continue;
				}

				$field_label = $field['label'] ?? ucfirst( str_replace( '_', ' ', $field_id ) );
				$key         = $slug . ':' . sanitize_key( $field_id );
				$field_options[ $key ] = $page_label . ' — ' . $field_label;
			}
		}

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

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

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

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

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

		if ( ! wpps_opb_page_exists( $page_slug ) ) {
			return;
		}

		echo wpps_opb_render_field_output( $page_slug, $field_id );
	}

	private function getPages(): array {
		$p = get_option( 'wp_powersuite_opb_pages', [] );
		return is_array( $p ) ? $p : [];
	}
}
