<?php
/**
 * CPT Builder - Taxonomy Post Types tab.
 *
 * @package CptBuilder
 *
 * @var array<string, mixed>  $definition
 * @var array<string, string> $post_types
 */

namespace CptBuilder;

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

$post_types   = isset( $post_types ) && is_array( $post_types ) ? $post_types : [];
$object_types = isset( $definition['object_types'] ) && is_array( $definition['object_types'] ) ? array_map( 'strval', $definition['object_types'] ) : [];

// Keep already-attached types listed even when they would be filtered out,
// so saving never silently drops an existing connection.
foreach ( $object_types as $attached ) {
	if ( $attached !== '' && ! isset( $post_types[ $attached ] ) ) {
		$post_types[ $attached ] = $attached;
	}
}
?>
<h2><?php esc_html_e( 'Attach to post types', 'wp-powersuite' ); ?></h2>
<p class="description"><?php esc_html_e( 'Choose which post types this taxonomy applies to. You can change this at any time.', 'wp-powersuite' ); ?></p>

<?php if ( $post_types === [] ) : ?>
	<p><?php esc_html_e( 'No post types are available yet.', 'wp-powersuite' ); ?></p>
<?php else : ?>
	<fieldset class="cptb-checkbox-grid">
		<?php foreach ( $post_types as $pt_key => $pt_label ) : ?>
			<label class="cptb-check">
				<input type="checkbox" name="object_types[]" value="<?php echo esc_attr( $pt_key ); ?>" <?php checked( in_array( $pt_key, $object_types, true ) ); ?>>
				<span><?php echo esc_html( $pt_label ); ?> <code><?php echo esc_html( $pt_key ); ?></code></span>
			</label>
		<?php endforeach; ?>
	</fieldset>
<?php endif; ?>
