<?php
/**
 * Accordion content for schema of advanced settings.
 *
 * @package EaLab\WP_Deployer
 * @deprecated Old form.
 */

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

use EaLab\WP_Deployer\vendor\Dakwamine\Component\ComponentBasedObject;
use EaLab\WP_Deployer\vendor\Ealab\Deployer\Tracking\TrackerConfig\AutomaticTrackerConfigProvider;
use EaLab\WP_Deployer\vendor\Ealab\Deployer\Tracking\TrackerConfig\TrackerConfigProviderManager;
use EaLab\WP_Deployer\vendor\Ealab\Deployer\Tracking\TrackingManager;
use EaLab\WP_Deployer\vendor\Ealab\Deployer\Utility\Database;

require_once DEPLOY_SYNC_CONTENT__PLUGIN_DIR . '/admin/partials/component/advanced-settings/item-value-handler-subforms.php';

/**
 * Accordion content for schema of advanced settings.
 *
 * @param array|null $context The context to build this component.
 */
function deploy_sync_content__advanced_settings_accordion_content( ?array $context = null ): void {
	$value_handlers = deploy_sync_content__get_item_value_handlers();

	// Dev note: this will duplicate the templates the more accordions are included.
	// But it's fine.
	deploy_sync_content__item_value_handler_subforms_write_templates();

	$auto_tracker_config_provider = ComponentBasedObject::getRootComponentByClassName( AutomaticTrackerConfigProvider::class, true );

	$trackers_auto_defs = $context['trackers_auto_defs'] ?? $auto_tracker_config_provider->collect();

	$tracking_manager = ComponentBasedObject::getRootComponentByClassName( TrackingManager::class, true );

	$tracker_config_provider_manager = deploy_sync_content__get_root_cbo( TrackerConfigProviderManager::class );

	$active_tracker_definitions = $tracker_config_provider_manager->getActiveConfig();

	$wp_prefix = Database::getDatabasePrefix();

	$all_tables = Database::getTableNames(
		array(
			'without_dsc_tables' => true,
			'without_prefix'     => true,
		)
	);

	if ( isset( $context['tables'] ) ) {
		$tables = &$context['tables'];
	} else {
		$tables = array();
	}

	if ( isset( $context['schema_index'] ) ) {
		$schema_index = &$context['schema_index'];
	} else {
		$schema_index = 0;
	}

	if ( isset( $context['collapse_id'] ) ) {
		$collapse_id = &$context['collapse_id'];
	} else {
		$collapse_id = uniqid();
	}

	if ( isset( $context['accordion_title'] ) ) {
		$accordion_title = &$context['accordion_title'];
	} else {
		$accordion_title = __( 'Click to show', 'deploy-sync-content' );
	}

	?>
	<div class="accordionSmall accordion-item">
		<h2 class="accordion-header">
			<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse"
				data-bs-target="#collapse<?php echo esc_attr( $collapse_id ); ?>" aria-expanded="false"
				aria-controls="collapse<?php echo esc_attr( $collapse_id ); ?>">
				<?php echo wp_kses_post( $accordion_title ); ?>
			</button>
		</h2>
		<div id="collapse<?php echo esc_attr( $collapse_id ); ?>" class="accordion-collapse collapse"
			data-bs-parent="#accordionAdvancedSettings">
			<div class="accordion-body">
				<?php
				foreach ( $tables as $tb ) :
					++$schema_index;
					$tracker_id            = Database::removePrefix( $tb, $wp_prefix );
					$tracker_item          = $tracking_manager->getItemTrackerByTrackerId( $tracker_id );
					$auto_local_id_tracker = $trackers_auto_defs[ $tracker_id ]['local_id_field']['name'] ?? '';
					?>
					<div class="row mb-2 wrapper-checkbox-table">
						<div class="col-12">
							<input id="deploy_sync_content__setting_table_plugin_<?php echo esc_attr( $tb ); ?>"
								name="deploy_sync_content__settings_schemas[<?php echo esc_attr( $schema_index ); ?>]"
								class="table-plugin"
								type="checkbox"
								value="<?php echo esc_attr( $tb ); ?>"
								<?php
								if ( ! empty( $active_tracker_definitions ) && array_key_exists( $tracker_id, $active_tracker_definitions ) && ! empty( $active_tracker_definitions[ $tracker_id ] ) ) {
									echo 'checked="checked"';
								}
								?>
							/>
							<span class="deploy-sync-content--settings-schema-table"
								data-table="<?php echo esc_attr( $tb ); ?>"
								id="deploy_sync_content__settings_tb_<?php echo esc_attr( $tb ); ?>">
								<?php echo esc_html( $tb ); ?>
							</span>
						</div>
					</div>

					<div class="wrapper-options-table" data-table="<?php echo esc_attr( $tb ); ?>">
						<div class="row pt-3">
							<div class="col-2">
								<input id="deploy_sync_content__setting_track_<?php echo esc_attr( $tb ); ?>"
									class="class-deploy-sync-content-setting-track"
									name="deploy_sync_content__settings_state_<?php echo esc_attr( $tb ); ?>"
									type="radio"
									value="track"
									<?php
									if ( false === ( $active_tracker_definitions[ $tracker_id ]['excluded'] ?? false )
										|| ! array_key_exists( 'excluded', $active_tracker_definitions[ $tracker_id ] ) ) {
										// This is the default value.
										echo 'checked="checked"';
									}
									?>
								/>
								<?php echo esc_html__( 'Track', 'deploy-sync-content' ); ?>
							</div>
							<div class="col-2">
								<input id="deploy_sync_content__setting_follow_<?php echo esc_attr( $tb ); ?>"
									class="class-deploy-sync-content-setting-follow"
									name="deploy_sync_content__settings_state_<?php echo esc_attr( $tb ); ?>"
									type="radio"
									value="follow"
									<?php
									if ( true === ( $active_tracker_definitions[ $tracker_id ]['excluded'] ?? false ) ) {
										echo 'checked="checked"';
									}
									?>
								/>
								<?php echo esc_html__( 'Follow', 'deploy-sync-content' ); ?>
							</div>
							<div class="col-2">
								<a href="javascript:;" class="tooltip-icon" data-bs-placement="top"
									data-bs-custom-class="custom-tooltip" data-bs-toggle="tooltip"
									data-bs-title="Track: with data  Follow: without data"><i
										class="bi bi-question-circle-fill"></i></a>
							</div>
						</div>

						<div class="form-group row mt-3">
							<label for="inputLabel"
								class="col-sm-3 col-form-label"><?php echo esc_html__( 'Label', 'deploy-sync-content' ); ?></label>
							<div class="col-sm-9">
								<input type="text"
									value="<?php echo esc_attr( array_key_exists( 'tracker_label', $active_tracker_definitions[ $tracker_id ] ?? array() ) ? $active_tracker_definitions[ $tracker_id ]['tracker_label'] : '' ); ?>"
									class="form-control deploy-sync-content--settings-label"
									name="deploy_sync_content__settings_label_<?php echo esc_attr( $tb ); ?>"
									data-table="<?php echo esc_attr( $tb ); ?>"
									id="deploy_sync_content__settings_label_<?php echo esc_attr( $tb ); ?>"
									placeholder="<?php echo esc_attr__( 'Type to customize the label…', 'deploy-sync-content' ); ?>">
							</div>
						</div>

						<?php $cols_table = Database::getAllColumnNames( $tb ); ?>

						<div class="form-group row mt-3">
							<div class="col-sm-3 col-form-label">
								<label for="inputLabel"
									class=""><?php echo esc_html__( 'Local ID', 'deploy-sync-content' ); ?></label>
								<a
									href="javascript:;"
									class="tooltip-icon"
									data-bs-placement="top"
									data-bs-custom-class="custom-tooltip"
									data-bs-toggle="tooltip"
									data-bs-title="<?php echo esc_attr__( 'This is usually the autoincremented column of this table. If no autoincremented column is available, you may need to select one or more suitable columns that uniquely identifies the rows in this table.', 'deploy-sync-content' ); ?>">
									<i class="bi bi-question-circle-fill"></i>
								</a>
							</div>
							<div class="col-sm-9">
								<select class="form-select multiselect-deploy-sync-content"
									id="localid-<?php echo esc_attr( $tb ); ?>"
									name="localid-<?php echo esc_attr( $tb ); ?>"
									data-placeholder="<?php echo esc_attr__( 'Select one or more local IDs…', 'deploy-sync-content' ); ?>"
									multiple>
									<?php
									$selected_local_id_fields = $active_tracker_definitions[ $tracker_id ]['local_id_field']['name'] ?? '[]';

									$decoded_local_id_fields = json_decode( $selected_local_id_fields );

									$selected_local_id_fields = ( ! json_last_error() && is_array( $decoded_local_id_fields ) )
										// This is a composite local ID, or an unset value of an unconfigured tracker.
										? $decoded_local_id_fields
										// This is a single local ID.
										: array( $selected_local_id_fields );

									foreach ( $cols_table as $col ) :
										?>
										<option
											<?php echo esc_attr( in_array( $col, $selected_local_id_fields, true ) ? 'selected' : '' ); ?>>
											<?php echo esc_html( $col ); ?>
										</option>
									<?php endforeach; ?>
								</select>
							</div>
						</div>

						<fieldset>
							<legend><?php echo esc_html__( 'Field Schema', 'deploy-sync-content' ); ?>&nbsp;&nbsp;<a
									href="javascript:;"
									class="tooltip-icon"
									data-bs-placement="top"
									data-bs-custom-class="custom-tooltip"
									data-bs-toggle="tooltip"
									data-bs-title="Select fields for mapping"><i
										class="bi bi-question-circle-fill"></i></a></legend>

							<?php foreach ( $cols_table as $col ) : ?>

								<div
									class="form-group row mt-3 col-table-<?php echo esc_attr( $tb ); ?>"
									data-col="<?php echo esc_attr( $col ); ?>">
									<label for="selectCol<?php echo esc_attr( $col ); ?>"
										class="col-sm-4 col-form-label"><?php echo esc_html( $col ); ?></label>
									<div class="col-sm-4">
										<select
											name="deploy_sync_content__settings_fieldtable_ivh[<?php echo esc_attr( $tb ); ?>][<?php echo esc_attr( $col ); ?>][value_handler]"
											data-localid="<?php echo esc_attr( ( null !== $tracker_item ) ? $tracker_item->getLocalIdFieldName() : $auto_local_id_tracker ); ?>"
											data-table="<?php echo esc_attr( $tb ); ?>"
											data-fieldName="<?php echo esc_attr( $col ); ?>"
											id="deploy_sync_content__settings_fieldtable_<?php echo esc_attr( $tb ); ?>_<?php echo esc_attr( $col ); ?>"
											class="form-select select-mapping"
											aria-label="selectCol<?php echo esc_attr( $col ); ?>">

											<option value="none">Not set</option>

											<?php foreach ( $value_handlers as $value_handler_id => $value_handler_label ) { ?>
												<?php
												if ( 'reference' === $value_handler_id ) {
													// Reference item value handlers are handled later.
													continue;
												}

												if ( 'scalar' === $value_handler_id ) {
													// Scalar is the default value handler, when no value is set.
													// So it's better to have the "Not set" option match with it.
													continue;
												}
												?>
												<option
													value="<?php echo esc_attr( $value_handler_id ); ?>"
													<?php echo esc_attr( ( $active_tracker_definitions[ $tracker_id ]['field_definitions_overrides'][ $col ]['value_handler'] ?? null ) === $value_handler_id ? 'selected' : '' ); ?>
												>
													<?php echo esc_html( $value_handler_label ); ?>
												</option>
											<?php } ?>

											<?php
											// Build the reference item value handler options.
											foreach ( $all_tables as $db_table ) :
												if ( ! empty( $active_tracker_definitions[ $tracker_id ]['field_definitions_overrides'][ $col ] ?? array() )
													&& array_key_exists( 'value_handler', $active_tracker_definitions[ $tracker_id ]['field_definitions_overrides'][ $col ] ) ) {
													?>
													<option
														value="reference:<?php echo esc_attr( $db_table ); ?>"
														<?php echo esc_attr( ( 'reference:' . $db_table ) === $active_tracker_definitions[ $tracker_id ]['field_definitions_overrides'][ $col ]['value_handler'] ? 'selected' : '' ); ?>>
														Ref: <?php echo esc_html( $wp_prefix . $db_table ); ?>
													</option>
												<?php } else { ?>
													<option value="reference:<?php echo esc_attr( $db_table ); ?>">
														Ref: <?php echo esc_html( $wp_prefix . $db_table ); ?>
													</option>
													<?php
												}
											endforeach;
											?>
										</select>
									</div>
									<div class="col-sm-4 is-dependency">
										<input
											data-primarytrackerid="<?php echo esc_attr( ! empty( $active_tracker_definitions[ $tracker_id ]['subordination'] ) ? $active_tracker_definitions[ $tracker_id ]['subordination']['primary_tracker_id'] : '' ); ?>"
											data-primaryitemidfield="<?php echo esc_attr( ! empty( $active_tracker_definitions[ $tracker_id ]['subordination'] ) ? $active_tracker_definitions[ $tracker_id ]['subordination']['primary_item_id_field'] : '' ); ?>"
											name="deploy_sync_content__settings_fieldtable_dependency_<?php echo esc_attr( $tb ); ?>"
											type="checkbox" value=""
											<?php
											echo esc_attr(
												! empty( $active_tracker_definitions[ $tracker_id ]['subordination']['primary_item_id_field'] )
												&& ( $active_tracker_definitions[ $tracker_id ]['subordination']['primary_item_id_field'] === $col ) ? 'checked' : ''
											);
											?>
										>
										<?php echo esc_html__( 'Dependency', 'deploy-sync-content' ); ?>
									</div>
									<div class="row">
										<div class="col-sm-4"></div>
										<div class="ivh-subform col">
											<?php
											$current_item_value_handler = $active_tracker_definitions[ $tracker_id ]['field_definitions_overrides'][ $col ]['value_handler'] ?? '';

											$maybe_subform_function = 'deploy_sync_content__item_value_handler_subform__' . $current_item_value_handler;

											function_exists( $maybe_subform_function ) && $maybe_subform_function(
												array(
													'for_table'               => $tb,
													'for_field'               => $col,
													'item_value_handler_item' => $active_tracker_definitions[ $tracker_id ]['field_definitions_overrides'][ $col ],
												)
											);
											?>
										</div>
									</div>
								</div>

							<?php endforeach; ?>

						</fieldset>
					</div>
				<?php endforeach; ?>
			</div>
		</div>
	</div>
	<?php
}
