<?php
/**
 * List of deployment items, ordered by their respective label.
 *
 * @package EaLab\WP_Deployer
 */

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

/**
 * Requires.
 */
require_once __DIR__ . '/deployment-item--form.php';
require_once __DIR__ . '/deployment-item--label-from-item.php';

use EaLab\WP_Deployer\vendor\Ealab\Deployer\Exception\WpDeployException;

/**
 * Displays the list of deployment items, ordered by their respective label.
 *
 * @param array<string,mixed> $deployment_items The deployment items.
 * @param array<string,mixed> $context The context of the form.
 *
 * @return string Markup.
 *
 * @throws WpDeployException Could not build deployment item list form.
 */
function deploy_sync_content__deployment_item_list__form( array $deployment_items, array $context ): string {
	// Sort the items by their UUID.
	// The items will be sorted again by their screen label,
	// but in case two items have the same screen label,
	// they will keep their order by UUID.
	ksort( $deployment_items );

	// Retrieve the label of each item.
	$dictionary = array();

	foreach ( $deployment_items as $deployment_item ) {
		$dictionary_item['item'] = $deployment_item;

		$dictionary_item['label'] = deploy_sync_content__deployment_item__label_from_item( $deployment_item, $context );

		$dictionary[] = $dictionary_item;
	}

	// Reorder by the label.
	uasort(
		$dictionary,
		function ( $a, $b ) {
			return ( $a['label'] ?? '' ) <=> ( $b['label'] ?? '' );
		}
	);

	$html = '';

	// Insert each deployment item form.
	foreach ( $dictionary as $dictionary_item ) {
		$context['label'] = $dictionary_item['label'];

		$html .= deploy_sync_content__deployment_item__form( $dictionary_item['item'], $context );
	}

	return $html;
}
