<?php
/**
 * Item tracker form for export and import.
 *
 * @package EaLab\WP_Deployer
 */

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

/**
 * Requires.
 */
require_once __DIR__ . '/../utility/component-based-object.php';
require_once __DIR__ . '/deployment-item--label-from-item.php';
require_once __DIR__ . '/deployment-item-list--form.php';
require_once __DIR__ . '/required-plugins.php';

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

/**
 * Tracker list form.
 *
 * @param array<string,array> $deployment_items The deployment items, keyed by their full UUID.
 * @param array               $context The context. It contains the following keys:
 *   - form_context (string): 'export' or 'import'.
 *   - bundle_id (string): When form_context is 'import', this contains the subdirectory name
 *     of the bundle containing the given deployment items.
 *
 * @throws WpDeployException If the tracker ID is unset.
 */
function deploy_sync_content__item_tracker__form( array $deployment_items = array(), array $context = array() ): string {
	if ( empty( $deployment_items ) ) {
		return '';
	}

	if ( ! in_array( $context['form_context'] ?? null, array( 'export', 'import' ), true ) ) {
		// Context is unset or invalid.
		throw new WpDeployException( 'Could not build item tracker form: the context is unset or invalid.' );
	}

	$tracker_id = reset( $deployment_items )['tracker'] ?? '';

	if ( empty( $tracker_id ) ) {
		// Tracker ID is unset. This should never happen.
		throw new WpDeployException( 'Tracker ID is unset.' );
	}

	// Check if this item tracker is subordinated to another one.
	$tracking_manager = deploy_sync_content__get_root_cbo( TrackingManager::class );

	try {
		if ( $tracking_manager->isItemTrackerSubordinatedTo( $tracker_id ) ) {
			// This item tracker is subordinated to another one.
			// Do not display it. Its items will be displayed in the form of the other item tracker.
			return '';
		}
	} catch ( WpDeployException $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
		// This could mean that the tracker is not yet initialized,
		// and may be initialized by a plugin to install.
		// In this case, we will show the items of this tracker
		// so that the user can select them.
		// TODO: in this case we may display a message to the user
		// to inform him about the plugins to install for the following deployment items.
	}

	// TODO: Récupérer le screen label traduit du tracker depuis la config.
	$item_tracker_title = esc_html( $tracker_id );

	$select_all_label = esc_html__( 'Select All', 'deploy-sync-content' );

	// The counting is limited to item tracker forms, and counts also the items of subordinated item trackers.
	$context['prechecked_items_count'] = $context['prechecked_items_count'] ?? new Deploy_Sync_Content__State( 0 );
	$context['disabled_items_count']   = $context['disabled_items_count'] ?? new Deploy_Sync_Content__State( 0 );
	$context['all_items_count']        = $context['all_items_count'] ?? new Deploy_Sync_Content__State( 0 );

	$deploy_sync_content__deployment_item_list__form = deploy_sync_content__deployment_item_list__form( $deployment_items, $context );

	$is_reviewing       = ( 'export' === $context['form_context'] ) && in_array( 'review', $context['form_context_tags'] ?? array(), true );
	$all_items_checked  = $context['prechecked_items_count']->value === $context['all_items_count']->value;
	$all_items_disabled = $all_items_checked && $is_reviewing;
	$select_all_attrs   = ( $all_items_checked ? ' checked' : '' ) . ( $all_items_disabled ? ' disabled' : '' );

	return '
<fieldset>
    <legend>' . $item_tracker_title . '</legend>
    <div class="row select-all-row">
        <div class="col-auto"><input name="selectAll-' . $tracker_id . '" type="checkbox" value="selectAll-' . $tracker_id . '" class="select-all-checkbox"' . $select_all_attrs . '>' . $select_all_label . '</div>
    </div>
    <div class="list-trackers list-trackers-' . $tracker_id . '">
        ' . $deploy_sync_content__deployment_item_list__form . '
    </div>
</fieldset>
';
}
