<?php
/**
 * Builds the `FAQPage` schema piece from per-vehicle FAQ entries.
 *
 * Reads from the `_trx_ad_faq` post meta (array of `{question, answer}`).
 * Empty meta → returns `[]` (no piece). Sites can use any field-builder
 * UI (ACF, Meta Box, plain admin field) — we just consume the array.
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Integrations\Schema;

class FaqSchema {

	/**
	 * @return array<string, mixed>
	 */
	public function buildPiece( int $postId ): array {
		if ( $postId <= 0 ) {
			return array();
		}

		$raw = get_post_meta( $postId, '_trx_ad_faq', true );

		// Accept either an already-decoded array or a JSON string.
		if ( is_string( $raw ) && '' !== $raw ) {
			$decoded = json_decode( $raw, true );
			$raw     = is_array( $decoded ) ? $decoded : array();
		}
		if ( ! is_array( $raw ) ) {
			$raw = array();
		}

		$entries = array();
		foreach ( $raw as $row ) {
			if ( ! is_array( $row ) ) {
				continue;
			}
			$q = trim( (string) ( $row['question'] ?? $row['q'] ?? '' ) );
			$a = trim( (string) ( $row['answer'] ?? $row['a'] ?? '' ) );
			if ( '' === $q || '' === $a ) {
				continue;
			}
			$entries[] = array(
				'@type'          => 'Question',
				'name'           => $q,
				'acceptedAnswer' => array(
					'@type' => 'Answer',
					'text'  => $a,
				),
			);
		}

		if ( empty( $entries ) ) {
			return array();
		}

		$permalink = (string) get_permalink( $postId );
		$piece     = array(
			'@type'      => 'FAQPage',
			'@id'        => $permalink . '#faq',
			'mainEntity' => $entries,
		);

		/**
		 * Filter the FAQPage piece.
		 *
		 * @param array $piece
		 * @param int   $postId
		 * @param array $entries
		 */
		return (array) apply_filters( 'trx_ad_schema_faq_piece', $piece, $postId, $entries );
	}
}
