<?php
/**
 * Button to access the merge page of a deployment item.
 *
 * @package EaLab\WP_Deployer
 */

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

/**
 * Button to access the merge page of a deployment item.
 *
 * @param array $context The build context.
 *
 * @return string Markup.
 */
function deploy_sync_content__deployment_item__merge_button( array $context ): string {
	$button_label = $context['button_label'] ?? __( 'Resolve', 'deploy-sync-content' );

	$primary_item_full_uuid = $context['primary_item_full_uuid'] ?? null;
	$all_item_full_uuids    = $context['all_item_full_uuids'] ?? array();

	if ( empty( $primary_item_full_uuid ) ) {
		// Cannot merge a non-existent item.
		return '';
	}

	$uuids_imploded = implode( ',', $all_item_full_uuids );

	$link_args = array(
		'deployment_bundle' => $context['bundle_id'] ?? 'unknown_bundle',
		'form_context'      => $context['form_context'] ?? 'unknown_context',
		'tab'               => 'merge',
		'uuid'              => rawurlencode( $uuids_imploded ),
	);

	$link_to_merge = add_query_arg( $link_args, admin_url( DEPLOY_SYNC_CONTENT__BASIC_URI ) );

	if ( strlen( $link_to_merge ) > 4000 ) {
		// Too many items for the URL.
		// Rebuild the URL, but only include the main item.
		// As an enhancement to this system, we could open a merge session
		// upon the click on the button; a merge session would be created
		// in the database with all the item UUIDs that needs to be merged,
		// and the merge page would get a session ID that will tell it to
		// load the session, not the UUIDs from the URL.
		$link_args['uuid'] = $primary_item_full_uuid;

		// Rebuild the URL.
		$link_to_merge = add_query_arg( $link_args, admin_url( DEPLOY_SYNC_CONTENT__BASIC_URI ) );
	}

	return '<a href="' . esc_attr( $link_to_merge ) . '" class="btn btn-primary">' . esc_html( $button_label ) . '</a>';
}
