<?php
/**
 * Base class for vehicle-context dynamic tags.
 *
 * Subclasses fill the tag identity via three properties (`name`, `title`,
 * `category`) and implement `resolveValue()` to read from the specs row /
 * post meta / taxonomy. The template-builder preview-id resolution and
 * `Elementor\Tag::render()` plumbing live here once.
 *
 * Sites without Elementor PSR-4 autoload these files but bail before the
 * `extends \Elementor\Core\DynamicTags\Tag` declaration so the autoloader
 * doesn't fatal — same pattern the widget classes use.
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Elementor\DynamicTags;

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

use Elementor\Core\DynamicTags\Tag;
use ThemeREX\AutoDealer\PostTypes\VehiclePostType;
use function ThemeREX\AutoDealer\getVehicleSpecs;

abstract class AbstractVehicleTag extends Tag {

	protected string $tag_name     = '';
	protected string $tag_title    = '';
	protected string $tag_category = 'text';

	public function get_name(): string {
		return $this->tag_name;
	}

	public function get_title(): string {
		return $this->tag_title;
	}

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

	public function get_categories(): array {
		return array( $this->tag_category );
	}

	public function render(): void {
		echo wp_kses_post( $this->resolveValue( $this->resolveVehicleId() ) );
	}

	protected 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;
	}

	/**
	 * @param int $vehicleId Resolved vehicle post ID (may be 0).
	 */
	abstract protected function resolveValue( int $vehicleId ): string;

	/**
	 * Helper: read a specs-row column by key.
	 */
	protected function specs( int $vehicleId, string $key ): string {
		if ( $vehicleId <= 0 ) {
			return '';
		}
		$specs = getVehicleSpecs( $vehicleId );
		if ( ! is_array( $specs ) || ! isset( $specs[ $key ] ) ) {
			return '';
		}
		return (string) $specs[ $key ];
	}

	/**
	 * Helper: first taxonomy term name for a vehicle.
	 */
	protected function taxonomyName( int $vehicleId, string $taxonomy ): string {
		if ( $vehicleId <= 0 ) {
			return '';
		}
		$terms = wp_get_post_terms( $vehicleId, $taxonomy, array( 'fields' => 'names' ) );
		if ( is_wp_error( $terms ) || empty( $terms ) ) {
			return '';
		}
		return (string) $terms[0];
	}
}
