<?php
/**
 * Gallery section — sortable thumbnail grid backed by attachment IDs.
 *
 * Extracted from VehicleDataMetaBox per QUALITY-IMPROVEMENT-PLAN.md §T2-2.
 *
 * @package ThemeREX\AutoDealer\Admin\MetaBoxes\Sections
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Admin\MetaBoxes\Sections;

defined( 'ABSPATH' ) || exit;

use ThemeREX\AutoDealer\Admin\MetaBoxes\AbstractVehicleDataSection;
use ThemeREX\AutoDealer\Admin\VehicleMediaMetaBox;

final class GallerySection extends AbstractVehicleDataSection {

	public function getKey(): string {
		return 'gallery';
	}

	public function render( \WP_Post $post ): void {
		$galleryIds = VehicleMediaMetaBox::getGalleryIds( $post->ID );
		?>
		<div class="trx-ad-gallery-toolbar">
			<button type="button" class="button button-primary" id="trx-ad-gallery-add">
				<span class="dashicons dashicons-plus-alt2" style="vertical-align:middle;margin-top:-2px;"></span>
				<?php esc_html_e( 'Add Images', 'trx-auto-dealer' ); ?>
			</button>
			<button type="button" class="button" id="trx-ad-gallery-clear" <?php echo empty( $galleryIds ) ? 'style="display:none;"' : ''; ?>>
				<?php esc_html_e( 'Remove All', 'trx-auto-dealer' ); ?>
			</button>
			<span class="trx-ad-gallery-hint">
				<?php esc_html_e( 'Drag to reorder. First image is the main photo.', 'trx-auto-dealer' ); ?>
			</span>
		</div>

		<div class="trx-ad-gallery-grid" id="trx-ad-gallery-grid">
			<?php foreach ( $galleryIds as $attachId ) : ?>
				<?php $thumb = wp_get_attachment_image_url( $attachId, 'thumbnail' ); ?>
				<?php
				if ( ! $thumb ) {
					continue; }
				?>
				<div class="trx-ad-gallery-item" data-id="<?php echo esc_attr( (string) $attachId ); ?>">
					<img src="<?php echo esc_url( $thumb ); ?>" alt="">
					<button type="button" class="trx-ad-gallery-remove" title="<?php esc_attr_e( 'Remove', 'trx-auto-dealer' ); ?>">
						<span class="dashicons dashicons-no-alt"></span>
					</button>
					<span class="trx-ad-gallery-badge"><?php esc_html_e( 'Main', 'trx-auto-dealer' ); ?></span>
				</div>
			<?php endforeach; ?>
		</div>

		<div class="trx-ad-gallery-empty" id="trx-ad-gallery-empty" <?php echo ! empty( $galleryIds ) ? 'style="display:none;"' : ''; ?>>
			<span class="dashicons dashicons-images-alt2"></span>
			<p><?php esc_html_e( 'No images yet. Click "Add Images" to upload or select from the media library.', 'trx-auto-dealer' ); ?></p>
		</div>

		<input type="hidden" name="trx_ad_gallery_ids" id="trx-ad-gallery-ids" value="<?php echo esc_attr( implode( ',', $galleryIds ) ); ?>">
		<?php
	}

	public function save( int $postId ): void {
		// Re-verify the meta-box nonce here as well as in the VehicleDataMetaBox
		// dispatcher -- defense in depth, and each save path is independently
		// auditable (wp.org 2026-07 review round 2).
		if (
			! isset( $_POST['_trx_ad_vehicle_data_nonce'] )
			|| ! wp_verify_nonce( sanitize_text_field( wp_unslash( (string) $_POST['_trx_ad_vehicle_data_nonce'] ) ), 'trx_ad_vehicle_data_save' )
		) {
			return;
		}

		$rawIds = isset( $_POST['trx_ad_gallery_ids'] )
			? sanitize_text_field( wp_unslash( (string) $_POST['trx_ad_gallery_ids'] ) )
			: '';

		if ( $rawIds !== '' ) {
			$ids = array_filter( array_map( 'absint', explode( ',', $rawIds ) ) );
			update_post_meta( $postId, VehicleMediaMetaBox::META_GALLERY, wp_json_encode( array_values( $ids ) ) );
		} else {
			delete_post_meta( $postId, VehicleMediaMetaBox::META_GALLERY );
		}
	}
}
