<?php
/**
 * Gallery dynamic tag — returns the vehicle's gallery as an array of
 * `{ id, url }` items, suitable for the Elementor Gallery / Image Gallery
 * controls. Implements `Data_Tag` (not `Tag`) because gallery controls expect
 * a structured value, not rendered HTML.
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Elementor\DynamicTags;

if ( ! class_exists( '\Elementor\Core\DynamicTags\Data_Tag' ) ) {
	return;
}

use Elementor\Core\DynamicTags\Data_Tag;
use Elementor\Modules\DynamicTags\Module;
use ThemeREX\AutoDealer\PostTypes\VehiclePostType;

class GalleryTag extends Data_Tag {

	public function get_name(): string {
		return 'trx-ad-gallery';
	}

	public function get_title(): string {
		return __( 'Vehicle Gallery', 'trx-auto-dealer' );
	}

	public function get_group(): string {
		return 'trx-auto-dealer';
	}

	public function get_categories(): array {
		return array( Module::GALLERY_CATEGORY );
	}

	public function get_value( array $options = array() ): array {
		$id = $this->resolveVehicleId();
		if ( $id <= 0 ) {
			return array();
		}

		$gallery_meta   = get_post_meta( $id, '_trx_ad_gallery', true );
		$attachment_ids = array();
		if ( is_string( $gallery_meta ) && '' !== $gallery_meta ) {
			$attachment_ids = array_filter( array_map( 'absint', explode( ',', $gallery_meta ) ) );
		} elseif ( is_array( $gallery_meta ) ) {
			$attachment_ids = array_filter( array_map( 'absint', $gallery_meta ) );
		}

		$out = array();
		foreach ( $attachment_ids as $aid ) {
			$url = wp_get_attachment_image_url( $aid, 'large' );
			if ( $url ) {
				$out[] = array(
					'id'  => $aid,
					'url' => $url,
				);
			}
		}
		return $out;
	}

	private function resolveVehicleId(): int {
		$id = (int) get_the_ID();
		if ( $id > 0 && VehiclePostType::POST_TYPE === get_post_type( $id ) ) {
			return $id;
		}

		if ( class_exists( '\Elementor\Plugin' ) ) {
			$current = \Elementor\Plugin::$instance->documents->get_current();
			if ( $current ) {
				$preview = (int) ( $current->get_settings( 'preview_id' ) ?? 0 );
				if ( $preview > 0 && VehiclePostType::POST_TYPE === get_post_type( $preview ) ) {
					return $preview;
				}
			}
		}

		return $id;
	}
}
