<?php
/**
 * Builds the `Offer` schema piece for a vehicle (price, availability,
 * priceValidUntil, seller).
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Integrations\Schema;

use ThemeREX\AutoDealer\PostTypes\VehiclePostType;
use function ThemeREX\AutoDealer\getSettings;
use function ThemeREX\AutoDealer\getVehicleSpecs;

class OfferSchema {

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

		$specs = getVehicleSpecs( $postId );
		if ( ! is_array( $specs ) ) {
			$specs = array();
		}

		// "Price on request" listings: omit the offer entirely (search
		// engines reject Offer with no price). Rich-result-eligible
		// listings need a numeric price.
		if ( ! empty( $specs['price_on_request'] ) ) {
			return array();
		}

		$price = isset( $specs['price'] ) && is_numeric( $specs['price'] ) ? (float) $specs['price'] : null;
		$sale  = isset( $specs['sale_price'] ) && is_numeric( $specs['sale_price'] ) ? (float) $specs['sale_price'] : null;
		$final = ( $sale && $sale > 0 ) ? $sale : $price;

		if ( null === $final || $final <= 0 ) {
			return array();
		}

		$permalink = (string) get_permalink( $postId );
		$currency  = strtoupper( (string) getSettings( 'currency_code', 'USD' ) );

		$piece = array(
			'@type'         => 'Offer',
			'@id'           => $permalink . '#offer',
			'url'           => $permalink,
			'price'         => number_format( $final, 2, '.', '' ),
			'priceCurrency' => $currency,
			'itemOffered'   => array( '@id' => $permalink . '#car' ),
		);

		// Availability mapped from status field.
		$status                = (string) ( $specs['status'] ?? 'available' );
		$availability_map      = array(
			'available'   => 'https://schema.org/InStock',
			'reserved'    => 'https://schema.org/InStock',
			'sold'        => 'https://schema.org/OutOfStock',
			'coming_soon' => 'https://schema.org/PreOrder',
		);
		$piece['availability'] = $availability_map[ $status ] ?? 'https://schema.org/InStock';

		// Sale-from-original price hint.
		if ( $sale && $price && $sale > 0 && $sale < $price ) {
			$piece['priceSpecification'] = array(
				'@type'         => 'UnitPriceSpecification',
				'price'         => number_format( $sale, 2, '.', '' ),
				'priceCurrency' => $currency,
				'priceType'     => 'https://schema.org/SalePrice',
			);
		}

		// Seller — link to the dealer's AutoDealer node when available.
		$dealer_id = (int) ( $specs['dealer_id'] ?? 0 );
		if ( $dealer_id <= 0 ) {
			$dealer_id = (int) get_post_meta( $postId, '_trx_ad_dealer_id', true );
		}
		if ( $dealer_id > 0 && 'trx_ad_dealer' === get_post_type( $dealer_id ) ) {
			$piece['seller'] = array( '@id' => get_permalink( $dealer_id ) . '#organization' );
		}

		/**
		 * Filter the Offer JSON-LD piece.
		 *
		 * @param array $piece
		 * @param int   $postId
		 * @param array $specs
		 */
		return (array) apply_filters( 'trx_ad_schema_offer_piece', $piece, $postId, $specs );
	}
}
