<?php
/**
 * File Path: includes/metaboxes/class-mbs-metabox-media-uploader.php
 *
 * Media Uploader Metabox Helper
 *
 * Reusable media upload field with preview and wp.media integration.
 * Used by MBS_Metabox_Format_Repeater and other format metaboxes.
 *
 * @package MyBookShowroom
 */

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

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

	/**
	 * Render a media upload field with preview.
	 *
	 * @param string $name     Field name (e.g. 'mbs_default_cover_id')
	 * @param int    $value    Current attachment ID
	 * @param string $label    Field label
	 */
	public static function render( string $name, int $value = 0, string $label = 'Image' ): void {
		$img_url = $value ? wp_get_attachment_url( $value ) : '';
		?>
		<div class="mbs-media-uploader">
			<label for="<?php echo esc_attr( $name ); ?>"><?php echo esc_html( $label ); ?></label><br>

			<div class="mbs-media-preview">
				<?php if ( $img_url ) : ?>
					<img src="<?php echo esc_url( $img_url ); ?>" 
					     alt="Preview" 
					     class="mbs-media-preview-img">
				<?php endif; ?>
			</div>

			<input type="hidden" 
			       id="<?php echo esc_attr( $name ); ?>" 
			       name="<?php echo esc_attr( $name ); ?>" 
			       value="<?php echo esc_attr( $value ); ?>">

			<button type="button" 
			        class="button button-primary mbs-upload-button" 
			        data-field="<?php echo esc_attr( $name ); ?>">
				Select Image
			</button>

			<button type="button" 
			        class="button button-secondary mbs-remove-button" 
			        data-field="<?php echo esc_attr( $name ); ?>">
				Remove
			</button>
		</div>
		<?php
	}

	/**
	 * Enqueue wp.media and attach click handlers for all media uploader buttons.
	 * Called once from MBS_Settings or metabox loader.
	 */
	public static function enqueue_media(): void {
		wp_enqueue_media();
		wp_enqueue_script( 'mbs-media-uploader', MBS_ASSETS_URL . 'js/mbs-media-uploader.js', array( 'jquery' ), MBS_VERSION, true );
	}
}
