<?php
/**
 * File Path: includes/helpers/class-mbs-link-icon-helper.php
 *
 * Buy Link Icon Helper
 *
 * Centralises retailer/platform icon resolution, label lookup, and site icon
 * URL resolution. Used by buy link render classes and admin metaboxes.
 *
 * @package MyBookShowroom
 * @since   1.5.0
 */

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

class MBS_Link_Icon_Helper { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- mbs_/MBS_ prefix is correct; scanner not configured with plugin prefix

	/**
	 * Resolve the icon image URL for a known retailer/platform key.
	 * Prefers SVG over PNG if the SVG file exists on disk.
	 *
	 * @param  string $key           sanitize_key()-processed retailer key.
	 * @param  string $retailers_url Base URL for the retailers folder (with trailing slash).
	 * @return string  Full URL to the icon file, or empty string if key/URL is empty.
	 * @since  1.5.0
	 */
	public static function resolve_icon_src( string $key, string $retailers_url ): string {
		if ( ! $key || ! $retailers_url ) {
			return '';
		}
		// BUG-ICON fix: verify the file exists before constructing a URL.
		// Previously the SVG check fell back to a PNG URL without confirming the PNG
		// exists, producing a 404 href for unknown/custom retailer keys.
		$svg_path = MBS_ASSETS_DIR . 'images/retailers/' . $key . '.svg';
		if ( file_exists( $svg_path ) ) {
			return trailingslashit( $retailers_url ) . $key . '.svg';
		}
		$png_path = MBS_ASSETS_DIR . 'images/retailers/' . $key . '.png';
		if ( file_exists( $png_path ) ) {
			return trailingslashit( $retailers_url ) . $key . '.png';
		}
		return ''; // No icon asset exists for this key — caller shows placeholder.
	}

	/**
	 * Return the human-readable display label for a retailer/platform key.
	 *
	 * Used for rendering placeholders, button text, and frontend display.
	 * Returns ucfirst( str_replace( '-', ' ', $key ) ) for unknown non-empty keys.
	 * Returns 'Buy Now' for an empty key.
	 *
	 * @param  string $key  sanitize_key()-processed retailer key.
	 * @return string  Display label.
	 * @since  1.5.0
	 */
	public static function get_label( string $key ): string {
		$labels = self::label_map();
		return $labels[ $key ] ?? ( $key ? ucfirst( str_replace( '-', ' ', $key ) ) : 'Buy Now' );
	}

	/**
	 * Return the canonical label for storing in the database.
	 *
	 * Returns '' for unknown keys, preserving the existing ?: fallback-to-raw_label
	 * contract in the save path. This protects custom labels on retailer keys
	 * not in the map.
	 *
	 * @param  string $key  sanitize_key()-processed retailer key.
	 * @return string  Canonical label, or empty string if key is unknown.
	 * @since  1.5.0
	 */
	public static function get_canonical_label( string $key ): string {
		$labels = self::label_map();
		return $labels[ $key ] ?? '';
	}

	/**
	 * Resolve the site icon URL with a two-step fallback.
	 *
	 * Step 1: get_site_icon_url( $size ).
	 * Step 2: wp_get_attachment_url() on the raw attachment when the sized
	 *         thumbnail has not been generated by WordPress.
	 *
	 * @param  int $size  Thumbnail size in pixels (default 32).
	 * @return string  Site icon URL, or empty string if no site icon is set.
	 * @since  1.5.0
	 */
	public static function get_site_icon_url( int $size = 32 ): string {
		$icon_id = (int) get_option( 'site_icon' );
		if ( ! $icon_id ) {
			return '';
		}
		$url = \get_site_icon_url( $size );
		if ( ! $url ) {
			$url = wp_get_attachment_url( $icon_id ) ?: '';
		}
		return $url;
	}

	/**
	 * Shared 21-entry label map used by get_label() and get_canonical_label().
	 *
	 * @return array<string,string>
	 * @since  1.5.0
	 */
	private static function label_map(): array {
		return array(
			'amazon'       => 'Amazon',
			'apple'        => 'Apple Books',
			'audible'      => 'Audible',
			'bam'          => 'Books-A-Million',
			'bn'           => 'Barnes & Noble',
			'bookshop'     => 'Bookshop.org',
			'google'       => 'Google Play',
			'kobo'         => 'Kobo',
			'powells'      => "Powell's",
			'waterstones'  => 'Waterstones',
			'gumroad'      => 'Gumroad',
			'bookfunnel'   => 'BookFunnel',
			'shopify-buy'  => 'Shopify',
			'signed-copy'  => 'Signed Copy',
			'library'      => 'Library',
			'bookbub'      => 'BookBub',
			'goodreads'    => 'Goodreads',
			'storygraph'   => 'StoryGraph',
			'scribd'       => 'Scribd',
			'librarything' => 'LibraryThing',
			'reedsy'       => 'Reedsy',
		);
	}
}
