<?php
/**
 * Template part: dealer-card
 *
 * Dealer information sidebar card.
 *
 * @package ThemeREX\AutoDealer
 * @version 1.0.0
 *
 * @var int $dealer_id Dealer post ID (passed via extract).
 */

declare(strict_types=1);

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

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

if ( ! isset( $dealer_id ) || (int) $dealer_id < 1 ) {
	return;
}

$dealer_id   = (int) $dealer_id;
$dealer_name = get_the_title( $dealer_id );
$meta        = getDealerMeta( $dealer_id );

$phone    = $meta['phone'] ?? '';
$email    = $meta['email'] ?? '';
$whatsapp = $meta['whatsapp'] ?? '';
$address  = $meta['address'] ?? '';
$city     = $meta['city'] ?? '';
$state    = $meta['state'] ?? '';
$zip      = $meta['zip'] ?? '';
$country  = $meta['country'] ?? '';
$website  = $meta['website'] ?? '';
$logo_id  = (int) ( $meta['logo'] ?? 0 );

// Country joined into the address line so it shows in one piece.
$full_address_parts = array_filter( array( $address, $city, $state, $zip, $country ) );
$full_address       = implode( ', ', $full_address_parts );

// Hours and description — `getDealerMeta()` already resolves `hours` from
// the canonical `_trx_ad_working_hours` key (with legacy fallbacks).
$hours_raw   = (string) ( $meta['hours'] ?? '' );
$dealer_post = get_post( $dealer_id );
$description = $dealer_post ? trim( (string) $dealer_post->post_content ) : '';

// WhatsApp link: remove non-digits for wa.me.
$whatsapp_number = preg_replace( '/[^0-9]/', '', $whatsapp );

// Link through to the dealer's own page (demo-site finding D6) — except when
// the card is already rendering ON that page, where it would be circular.
// Surfaces opt out via the `trx-ad-dealer-card--no-dealer-link` modifier
// (same CSS-toggle mechanism as every other field).
$dealer_permalink = (string) get_permalink( $dealer_id );
$on_own_page      = is_singular( DealerPostType::POST_TYPE ) && get_queried_object_id() === $dealer_id;
$show_dealer_link = '' !== $dealer_permalink && ! $on_own_page;
?>

<aside class="trx-ad-dealer-card">
	<h2 class="trx-ad-dealer-card__heading"><?php esc_html_e( 'Dealer Information', 'trx-auto-dealer' ); ?></h2>

	<div class="trx-ad-dealer-card__header">
		<?php if ( $logo_id > 0 ) : ?>
			<div class="trx-ad-dealer-card__logo">
				<?php if ( $show_dealer_link ) : ?>
					<a class="trx-ad-dealer-card__logo-link" href="<?php echo esc_url( $dealer_permalink ); ?>" aria-hidden="true" tabindex="-1">
						<?php echo wp_get_attachment_image( $logo_id, 'thumbnail', false, array( 'class' => 'trx-ad-dealer-card__logo-img' ) ); ?>
					</a>
				<?php else : ?>
					<?php echo wp_get_attachment_image( $logo_id, 'thumbnail', false, array( 'class' => 'trx-ad-dealer-card__logo-img' ) ); ?>
				<?php endif; ?>
			</div>
		<?php endif; ?>
		<h3 class="trx-ad-dealer-card__name">
			<?php if ( $show_dealer_link ) : ?>
				<a class="trx-ad-dealer-card__name-link" href="<?php echo esc_url( $dealer_permalink ); ?>"><?php echo esc_html( $dealer_name ); ?></a>
			<?php else : ?>
				<?php echo esc_html( $dealer_name ); ?>
			<?php endif; ?>
		</h3>
	</div>

	<div class="trx-ad-dealer-card__details">

		<?php if ( '' !== $phone ) : ?>
			<div class="trx-ad-dealer-card__field trx-ad-dealer-card__field--phone">
				<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.5 19.5 0 01-6-6 19.79 19.79 0 01-3.07-8.67A2 2 0 014.11 2h3a2 2 0 012 1.72 12.84 12.84 0 00.7 2.81 2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7A2 2 0 0122 16.92z"/></svg>
				<a href="tel:<?php echo esc_attr( $phone ); ?>" class="trx-ad-dealer-card__link"><?php echo esc_html( $phone ); ?></a>
			</div>
		<?php endif; ?>

		<?php if ( '' !== $email ) : ?>
			<div class="trx-ad-dealer-card__field trx-ad-dealer-card__field--email">
				<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
				<a href="mailto:<?php echo esc_attr( $email ); ?>" class="trx-ad-dealer-card__link"><?php echo esc_html( $email ); ?></a>
			</div>
		<?php endif; ?>

		<?php if ( '' !== $full_address ) : ?>
			<div class="trx-ad-dealer-card__field trx-ad-dealer-card__field--address">
				<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0118 0z"/><circle cx="12" cy="10" r="3"/></svg>
				<span class="trx-ad-dealer-card__text"><?php echo esc_html( $full_address ); ?></span>
			</div>
		<?php endif; ?>

		<?php if ( '' !== $website ) : ?>
			<div class="trx-ad-dealer-card__field trx-ad-dealer-card__field--website">
				<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 014 10 15.3 15.3 0 01-4 10 15.3 15.3 0 01-4-10 15.3 15.3 0 014-10z"/></svg>
				<a href="<?php echo esc_url( $website ); ?>" class="trx-ad-dealer-card__link" target="_blank" rel="noopener noreferrer"><?php echo esc_html( wp_parse_url( $website, PHP_URL_HOST ) ?? $website ); ?></a>
			</div>
		<?php endif; ?>

		<?php if ( '' !== $hours_raw ) : ?>
			<?php
			// Split on newlines so each day gets its own clock icon row.
			$hours_lines = array_values( array_filter( array_map( 'trim', preg_split( "/\r\n|\r|\n/", $hours_raw ) ?: array( $hours_raw ) ), static fn( $l ) => '' !== $l ) );
			?>
			<?php foreach ( $hours_lines as $hours_line ) : ?>
				<div class="trx-ad-dealer-card__field trx-ad-dealer-card__field--hours">
					<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
					<span class="trx-ad-dealer-card__text"><?php echo esc_html( $hours_line ); ?></span>
				</div>
			<?php endforeach; ?>
		<?php endif; ?>

		<?php if ( '' !== $description ) : ?>
			<div class="trx-ad-dealer-card__field trx-ad-dealer-card__field--description">
				<div class="trx-ad-dealer-card__description"><?php echo wp_kses_post( wpautop( $description ) ); ?></div>
			</div>
		<?php endif; ?>

		<?php
		// Basic OpenStreetMap embed when coordinates are set. No JS, no API
		// key, no third-party loader. Pro replaces this with an interactive
		// Google Maps / Leaflet view (per ADR-11).
		$lat = (string) ( $meta['latitude'] ?? '' );
		$lng = (string) ( $meta['longitude'] ?? '' );
		if ( '' !== $lat && '' !== $lng && is_numeric( $lat ) && is_numeric( $lng ) ) :
			$lat_f = (float) $lat;
			$lng_f = (float) $lng;
			// 0.02° bbox ≈ a few city blocks — comfortable zoom for a
			// dealership pin without revealing the whole region.
			$bbox   = sprintf( '%f,%f,%f,%f', $lng_f - 0.02, $lat_f - 0.01, $lng_f + 0.02, $lat_f + 0.01 );
			$marker = sprintf( '%f,%f', $lat_f, $lng_f );
			$src    = sprintf(
				'https://www.openstreetmap.org/export/embed.html?bbox=%s&layer=mapnik&marker=%s',
				rawurlencode( $bbox ),
				rawurlencode( $marker )
			);
			$href   = sprintf( 'https://www.openstreetmap.org/?mlat=%f&mlon=%f#map=15/%f/%f', $lat_f, $lng_f, $lat_f, $lng_f );
			?>
			<div class="trx-ad-dealer-card__field trx-ad-dealer-card__field--map">
				<iframe
					class="trx-ad-dealer-card__map"
					src="<?php echo esc_url( $src ); ?>"
					title="<?php echo esc_attr( sprintf( /* translators: %s = dealer name */ __( 'Map showing %s', 'trx-auto-dealer' ), $dealer_name ) ); ?>"
					loading="lazy"
					referrerpolicy="no-referrer-when-downgrade">
				</iframe>
				<a class="trx-ad-dealer-card__map-link" href="<?php echo esc_url( $href ); ?>" target="_blank" rel="noopener noreferrer">
					<?php esc_html_e( 'View larger map', 'trx-auto-dealer' ); ?>
				</a>
			</div>
		<?php elseif ( '' !== $full_address ) : ?>
			<?php
			// No pinned/geocoded coordinates (e.g. the dealer only entered an
			// address and geocoding was offline or didn't resolve). Rather than
			// drop the map entirely — which read as a per-theme inconsistency in
			// UAT #11 — still offer a map affordance that searches the address on
			// OpenStreetMap. No JS, no API key.
			$search_href = 'https://www.openstreetmap.org/search?query=' . rawurlencode( $full_address );
			?>
			<div class="trx-ad-dealer-card__field trx-ad-dealer-card__field--map trx-ad-dealer-card__field--map-link-only">
				<a class="trx-ad-dealer-card__map-link" href="<?php echo esc_url( $search_href ); ?>" target="_blank" rel="noopener noreferrer">
					<?php esc_html_e( 'View on map', 'trx-auto-dealer' ); ?>
				</a>
			</div>
		<?php endif; ?>

	</div>

	<div class="trx-ad-dealer-card__actions">

		<?php if ( $show_dealer_link ) : ?>
			<a href="<?php echo esc_url( $dealer_permalink ); ?>" class="trx-ad-dealer-card__btn trx-ad-dealer-card__btn--page">
				<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>
				<?php esc_html_e( 'View Dealer Page', 'trx-auto-dealer' ); ?>
			</a>
		<?php endif; ?>

		<?php if ( '' !== $phone ) : ?>
			<a href="tel:<?php echo esc_attr( $phone ); ?>" class="trx-ad-dealer-card__btn trx-ad-dealer-card__btn--call">
				<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.5 19.5 0 01-6-6 19.79 19.79 0 01-3.07-8.67A2 2 0 014.11 2h3a2 2 0 012 1.72 12.84 12.84 0 00.7 2.81 2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7A2 2 0 0122 16.92z"/></svg>
				<?php esc_html_e( 'Call Now', 'trx-auto-dealer' ); ?>
			</a>
		<?php endif; ?>

		<?php if ( '' !== $whatsapp_number ) : ?>
			<a href="https://wa.me/<?php echo esc_attr( $whatsapp_number ); ?>" class="trx-ad-dealer-card__btn trx-ad-dealer-card__btn--whatsapp" target="_blank" rel="noopener noreferrer">
				<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347z"/><path d="M12 0C5.373 0 0 5.373 0 12c0 2.127.555 4.124 1.529 5.857L.06 23.524l5.826-1.529A11.94 11.94 0 0012 24c6.627 0 12-5.373 12-12S18.627 0 12 0zm0 21.818c-1.93 0-3.762-.523-5.362-1.51l-.384-.228-3.985 1.046 1.064-3.885-.25-.397A9.77 9.77 0 012.182 12c0-5.414 4.404-9.818 9.818-9.818S21.818 6.586 21.818 12 17.414 21.818 12 21.818z"/></svg>
				<?php esc_html_e( 'WhatsApp', 'trx-auto-dealer' ); ?>
			</a>
		<?php endif; ?>

		<?php if ( '' !== $email ) : ?>
			<a href="mailto:<?php echo esc_attr( $email ); ?>" class="trx-ad-dealer-card__btn trx-ad-dealer-card__btn--email">
				<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
				<?php esc_html_e( 'Email', 'trx-auto-dealer' ); ?>
			</a>
		<?php endif; ?>

	</div>
</aside>
