<?php
/**
 * Builds the `AutoDealer` (LocalBusiness subtype) schema piece.
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Integrations\Schema;

use ThemeREX\AutoDealer\PostTypes\DealerPostType;
use function ThemeREX\AutoDealer\getDealerMeta;

class AutoDealerSchema {

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

		$meta      = getDealerMeta( $dealerId );
		$permalink = (string) get_permalink( $dealerId );

		$piece = array(
			'@type' => 'AutoDealer',
			'@id'   => $permalink . '#organization',
			'name'  => (string) get_the_title( $dealerId ),
			'url'   => $permalink,
		);

		$logo_id = (int) ( $meta['logo'] ?? 0 );
		if ( $logo_id > 0 ) {
			$logo_url = wp_get_attachment_image_url( $logo_id, 'full' );
			if ( $logo_url ) {
				$piece['logo']  = $logo_url;
				$piece['image'] = $logo_url;
			}
		}

		// Description — dealer post content (stripped of HTML).
		$content = get_post_field( 'post_content', $dealerId );
		if ( is_string( $content ) && '' !== $content ) {
			$piece['description'] = trim( wp_strip_all_tags( $content ) );
		}

		// Contact channels.
		if ( ! empty( $meta['phone'] ) ) {
			$piece['telephone'] = (string) $meta['phone'];
		}
		if ( ! empty( $meta['email'] ) ) {
			$piece['email'] = (string) $meta['email'];
		}

		// Postal address — required by Google for LocalBusiness rich results.
		$address_node = array_filter(
			array(
				'@type'           => 'PostalAddress',
				'streetAddress'   => $meta['address'] ?? '',
				'addressLocality' => $meta['city'] ?? '',
				'addressRegion'   => $meta['state'] ?? '',
				'postalCode'      => $meta['zip'] ?? '',
				'addressCountry'  => $meta['country'] ?? '',
			)
		);
		if ( count( $address_node ) > 1 ) {
			$piece['address'] = $address_node;
		}

		// Geo coordinates.
		if ( ! empty( $meta['latitude'] ) && ! empty( $meta['longitude'] )
			&& is_numeric( $meta['latitude'] ) && is_numeric( $meta['longitude'] ) ) {
			$piece['geo'] = array(
				'@type'     => 'GeoCoordinates',
				'latitude'  => (float) $meta['latitude'],
				'longitude' => (float) $meta['longitude'],
			);
		}

		// Hours — keep raw lines as openingHours strings (admin enters
		// "Mo-Fr 09:00-18:00" style values per line).
		if ( ! empty( $meta['hours'] ) ) {
			$lines = array_values( array_filter( array_map( 'trim', preg_split( "/\r\n|\r|\n/", (string) $meta['hours'] ) ?: array() ) ) );
			if ( ! empty( $lines ) ) {
				$piece['openingHours'] = $lines;
			}
		}

		// Sub-organisation web channels.
		$same_as = array();
		if ( ! empty( $meta['website'] ) ) {
			$same_as[] = (string) $meta['website'];
		}
		if ( ! empty( $same_as ) ) {
			$piece['sameAs'] = $same_as;
		}

		/**
		 * Filter the AutoDealer JSON-LD piece.
		 *
		 * @param array $piece
		 * @param int   $dealerId
		 * @param array $meta
		 */
		return (array) apply_filters( 'trx_ad_schema_autodealer_piece', $piece, $dealerId, $meta );
	}
}
