<?php
/**
 * Customize the dealer admin list table.
 *
 * Adds a logo thumbnail column and a location summary so the list view
 * is scannable instead of being just title + author + date.
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Admin;

defined( 'ABSPATH' ) || exit;
use ThemeREX\AutoDealer\PostTypes\DealerPostType;

class DealerListTable {

	public function register(): void {
		$post_type = DealerPostType::POST_TYPE;
		add_filter( "manage_{$post_type}_posts_columns", array( $this, 'addColumns' ) );
		add_action( "manage_{$post_type}_posts_custom_column", array( $this, 'renderColumn' ), 10, 2 );
	}

	/**
	 * @param array<string,string> $columns
	 * @return array<string,string>
	 */
	public function addColumns( array $columns ): array {
		$new = array();
		foreach ( $columns as $key => $label ) {
			if ( 'cb' === $key ) {
				$new[ $key ]               = $label;
				$new['trx_ad_dealer_logo'] = '';
				continue;
			}
			$new[ $key ] = $label;
			if ( 'title' === $key ) {
				$new['trx_ad_dealer_location'] = __( 'Location', 'trx-auto-dealer' );
				$new['trx_ad_dealer_phone']    = __( 'Phone', 'trx-auto-dealer' );
			}
		}
		return $new;
	}

	public function renderColumn( string $column, int $post_id ): void {
		switch ( $column ) {
			case 'trx_ad_dealer_logo':
				$this->renderLogo( $post_id );
				break;
			case 'trx_ad_dealer_location':
				$this->renderLocation( $post_id );
				break;
			case 'trx_ad_dealer_phone':
				$phone = (string) get_post_meta( $post_id, '_trx_ad_phone', true );
				echo '' !== $phone ? esc_html( $phone ) : '<span class="trx-ad-muted">—</span>';
				break;
		}
	}

	private function renderLogo( int $post_id ): void {
		$thumb_id = (int) get_post_thumbnail_id( $post_id );
		if ( $thumb_id > 0 ) {
			$src = wp_get_attachment_image_url( $thumb_id, array( 60, 60 ) );
			if ( is_string( $src ) && '' !== $src ) {
				printf(
					'<a href="%1$s" class="trx-ad-thumb"><img src="%2$s" alt="" loading="lazy" width="60" height="60"></a>',
					esc_url( get_edit_post_link( $post_id ) ?? '' ),
					esc_url( $src )
				);
				return;
			}
		}
		echo '<span class="trx-ad-thumb trx-ad-thumb--empty" aria-hidden="true"></span>';
	}

	private function renderLocation( int $post_id ): void {
		$city    = (string) get_post_meta( $post_id, '_trx_ad_city', true );
		$state   = (string) get_post_meta( $post_id, '_trx_ad_state', true );
		$country = (string) get_post_meta( $post_id, '_trx_ad_country', true );

		$parts = array_filter(
			array( $city, $state, $country ),
			static fn( string $v ): bool => '' !== $v
		);

		if ( empty( $parts ) ) {
			echo '<span class="trx-ad-muted">—</span>';
			return;
		}

		echo esc_html( implode( ', ', $parts ) );
	}
}
