<?php
/**
 * Checkout Fields Tab Content for GGM Commerce Admin.
 *
 * @package GGM_Commerce
 */

defined( 'ABSPATH' ) || exit;

/**
 * Render the Checkout Fields settings tab.
 */
function ggm_commerce_render_checkout_fields_tab() {
	$checkout_fields = GGM_Commerce_Checkout_Fields::get_instance();
	$groups          = $checkout_fields->get_field_groups();
	$all_fields      = $checkout_fields->get_fields();
	$ungrouped       = $checkout_fields->get_ungrouped_fields();
	$positions       = $checkout_fields->get_positions();
	$field_types     = $checkout_fields->get_field_types();
	$nonce           = wp_create_nonce( 'ggm_commerce_admin' );

	// Detect context: standalone page or settings tab.
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$current_page = isset( $_GET['page'] ) ? sanitize_key( $_GET['page'] ) : '';
	$is_standalone = ( 'ggmc-checkout-fields' === $current_page );
	$base_url      = $is_standalone
		? admin_url( 'admin.php?page=ggmc-checkout-fields' )
		: admin_url( 'admin.php?page=ggmc-settings&tab=checkout-fields' );

	// Check if editing a specific field or group.
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$edit_field_id = isset( $_GET['edit_field'] ) ? intval( $_GET['edit_field'] ) : 0;
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$edit_group_id = isset( $_GET['edit_group'] ) ? intval( $_GET['edit_group'] ) : 0;
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$current_view = isset( $_GET['view'] ) ? sanitize_key( $_GET['view'] ) : 'fields';

	$editing_field = $edit_field_id ? $checkout_fields->get_field( $edit_field_id ) : null;
	$editing_group = $edit_group_id ? $checkout_fields->get_field_group( $edit_group_id ) : null;
	?>

	<div class="wrap ggmc-checkout-fields-admin">
		<p class="description"><?php esc_html_e( 'Add custom fields to your checkout form. Create fields individually or organize them into groups.', 'ggm-commerce' ); ?></p>

		<!-- Sub-tabs -->
		<nav class="nav-tab-wrapper" style="margin-bottom: 20px;">
			<a href="<?php echo esc_url( $base_url . '&view=fields' ); ?>"
			   class="nav-tab <?php echo 'groups' !== $current_view ? 'nav-tab-active' : ''; ?>">
				<?php esc_html_e( 'Fields', 'ggm-commerce' ); ?>
			</a>
			<a href="<?php echo esc_url( $base_url . '&view=groups' ); ?>"
			   class="nav-tab <?php echo 'groups' === $current_view ? 'nav-tab-active' : ''; ?>">
				<?php esc_html_e( 'Field Groups', 'ggm-commerce' ); ?>
			</a>
		</nav>

		<?php if ( 'groups' === $current_view ) : ?>
			<!-- GROUPS VIEW -->
			<?php if ( $editing_group || isset( $_GET['new_group'] ) ) : // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
				<!-- Group Edit/Create Form -->
				<div class="card" style="max-width: 700px;">
					<h3><?php echo $editing_group ? esc_html__( 'Edit Field Group', 'ggm-commerce' ) : esc_html__( 'Create Field Group', 'ggm-commerce' ); ?></h3>

					<form id="checkout-field-group-form">
						<input type="hidden" name="nonce" value="<?php echo esc_attr( $nonce ); ?>">
						<?php if ( $editing_group ) : ?>
							<input type="hidden" name="group_id" value="<?php echo esc_attr( $editing_group->id ); ?>">
						<?php endif; ?>

						<table class="form-table">
							<tr>
								<th><label for="group-name"><?php esc_html_e( 'Group Name', 'ggm-commerce' ); ?> <span class="required">*</span></label></th>
								<td><input type="text" id="group-name" name="name" value="<?php echo esc_attr( $editing_group->name ?? '' ); ?>" class="regular-text" required></td>
							</tr>
							<tr>
								<th><label for="group-description"><?php esc_html_e( 'Description', 'ggm-commerce' ); ?></label></th>
								<td><textarea id="group-description" name="description" rows="3" class="large-text"><?php echo esc_textarea( $editing_group->description ?? '' ); ?></textarea></td>
							</tr>
							<tr>
								<th><label for="group-position"><?php esc_html_e( 'Position', 'ggm-commerce' ); ?></label></th>
								<td>
									<select id="group-position" name="position">
										<?php foreach ( $positions as $pos_key => $pos_label ) : ?>
											<option value="<?php echo esc_attr( $pos_key ); ?>" <?php selected( $editing_group->position ?? 'after_billing', $pos_key ); ?>><?php echo esc_html( $pos_label ); ?></option>
										<?php endforeach; ?>
									</select>
									<p class="description"><?php esc_html_e( 'Where this group of fields appears in the checkout form.', 'ggm-commerce' ); ?></p>
								</td>
							</tr>
						</table>

						<p>
							<button type="submit" class="button button-primary" id="save-group-btn">
								<?php echo $editing_group ? esc_html__( 'Update Group', 'ggm-commerce' ) : esc_html__( 'Create Group', 'ggm-commerce' ); ?>
							</button>
							<a href="<?php echo esc_url( $base_url . '&view=groups' ); ?>" class="button"><?php esc_html_e( 'Cancel', 'ggm-commerce' ); ?></a>
						</p>
					</form>

					<?php if ( $editing_group ) : ?>
						<!-- Group Fields -->
						<hr>
						<h4><?php esc_html_e( 'Fields in this Group', 'ggm-commerce' ); ?></h4>
						<?php
						$group_fields = $checkout_fields->get_group_fields( $editing_group->id );
						if ( ! empty( $group_fields ) ) :
							?>
							<table class="wp-list-table widefat fixed striped">
								<thead>
									<tr>
										<th><?php esc_html_e( 'Name', 'ggm-commerce' ); ?></th>
										<th><?php esc_html_e( 'Type', 'ggm-commerce' ); ?></th>
										<th><?php esc_html_e( 'Required', 'ggm-commerce' ); ?></th>
										<th><?php esc_html_e( 'Actions', 'ggm-commerce' ); ?></th>
									</tr>
								</thead>
								<tbody>
									<?php foreach ( $group_fields as $gf ) : ?>
										<tr>
											<td><?php echo esc_html( $gf->name ); ?></td>
											<td><?php echo esc_html( $field_types[ $gf->field_type ] ?? $gf->field_type ); ?></td>
											<td><?php echo $gf->required ? '<span class="dashicons dashicons-yes" style="color: #46b450;"></span>' : '<span class="dashicons dashicons-minus" style="color: #999;"></span>'; ?></td>
											<td>
												<button type="button" class="button button-small remove-from-group-btn" data-group-id="<?php echo esc_attr( $editing_group->id ); ?>" data-field-id="<?php echo esc_attr( $gf->id ); ?>">
													<?php esc_html_e( 'Remove', 'ggm-commerce' ); ?>
												</button>
											</td>
										</tr>
									<?php endforeach; ?>
								</tbody>
							</table>
						<?php else : ?>
							<p class="description"><?php esc_html_e( 'No fields in this group yet. Add fields from the Fields tab.', 'ggm-commerce' ); ?></p>
						<?php endif; ?>

						<!-- Add field to group -->
						<?php if ( ! empty( $ungrouped ) ) : ?>
							<div style="margin-top: 10px;">
								<select id="add-field-to-group-select">
									<option value=""><?php esc_html_e( '-- Select a field to add --', 'ggm-commerce' ); ?></option>
									<?php foreach ( $ungrouped as $uf ) : ?>
										<option value="<?php echo esc_attr( $uf->id ); ?>"><?php echo esc_html( $uf->name ); ?></option>
									<?php endforeach; ?>
								</select>
								<button type="button" class="button add-field-to-group-btn" data-group-id="<?php echo esc_attr( $editing_group->id ); ?>"><?php esc_html_e( 'Add to Group', 'ggm-commerce' ); ?></button>
							</div>
						<?php endif; ?>
					<?php endif; ?>
				</div>

			<?php else : ?>
				<!-- Groups List -->
				<div class="card">
					<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
						<h3 style="margin: 0;"><?php esc_html_e( 'Field Groups', 'ggm-commerce' ); ?></h3>
						<a href="<?php echo esc_url( $base_url . '&view=groups&new_group=1' ); ?>" class="button button-primary">
							<?php esc_html_e( 'Add New Group', 'ggm-commerce' ); ?>
						</a>
					</div>

					<?php if ( ! empty( $groups ) ) : ?>
						<table class="wp-list-table widefat fixed striped">
							<thead>
								<tr>
									<th><?php esc_html_e( 'Name', 'ggm-commerce' ); ?></th>
									<th><?php esc_html_e( 'Position', 'ggm-commerce' ); ?></th>
									<th><?php esc_html_e( 'Fields', 'ggm-commerce' ); ?></th>
									<th><?php esc_html_e( 'Status', 'ggm-commerce' ); ?></th>
									<th><?php esc_html_e( 'Actions', 'ggm-commerce' ); ?></th>
								</tr>
							</thead>
							<tbody>
								<?php foreach ( $groups as $group ) : ?>
									<?php $group_field_count = count( $checkout_fields->get_group_fields( $group->id ) ); ?>
									<tr>
										<td>
											<strong><?php echo esc_html( $group->name ); ?></strong>
											<?php if ( $group->description ) : ?>
												<br><span class="description"><?php echo esc_html( $group->description ); ?></span>
											<?php endif; ?>
										</td>
										<td><?php echo esc_html( $positions[ $group->position ] ?? $group->position ); ?></td>
										<td><?php echo esc_html( $group_field_count ); ?></td>
										<td>
											<span class="ggmc-status-badge ggmc-status-<?php echo esc_attr( $group->status ); ?>">
												<?php echo esc_html( ucfirst( $group->status ) ); ?>
											</span>
										</td>
										<td>
											<a href="<?php echo esc_url( $base_url . '&view=groups&edit_group=' . $group->id ); ?>" class="button button-small"><?php esc_html_e( 'Edit', 'ggm-commerce' ); ?></a>
											<button type="button" class="button button-small button-link-delete delete-group-btn" data-group-id="<?php echo esc_attr( $group->id ); ?>" data-group-name="<?php echo esc_attr( $group->name ); ?>">
												<?php esc_html_e( 'Delete', 'ggm-commerce' ); ?>
											</button>
										</td>
									</tr>
								<?php endforeach; ?>
							</tbody>
						</table>
					<?php else : ?>
						<p class="description"><?php esc_html_e( 'No field groups created yet. Groups let you organize related fields together under a heading.', 'ggm-commerce' ); ?></p>
					<?php endif; ?>
				</div>
			<?php endif; ?>

		<?php else : ?>
			<!-- FIELDS VIEW -->
			<?php if ( $editing_field || isset( $_GET['new_field'] ) ) : // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
				<!-- Field Edit/Create Form -->
				<div class="card" style="max-width: 700px;">
					<h3><?php echo $editing_field ? esc_html__( 'Edit Checkout Field', 'ggm-commerce' ) : esc_html__( 'Create Checkout Field', 'ggm-commerce' ); ?></h3>

					<form id="checkout-field-form">
						<input type="hidden" name="nonce" value="<?php echo esc_attr( $nonce ); ?>">
						<?php if ( $editing_field ) : ?>
							<input type="hidden" name="field_id" value="<?php echo esc_attr( $editing_field->id ); ?>">
						<?php endif; ?>

						<table class="form-table">
							<tr>
								<th><label for="field-name"><?php esc_html_e( 'Admin Name', 'ggm-commerce' ); ?> <span class="required">*</span></label></th>
								<td>
									<input type="text" id="field-name" name="name" value="<?php echo esc_attr( $editing_field->name ?? '' ); ?>" class="regular-text" required>
									<p class="description"><?php esc_html_e( 'Internal name for admin reference.', 'ggm-commerce' ); ?></p>
								</td>
							</tr>
							<tr>
								<th><label for="field-label"><?php esc_html_e( 'Customer Label', 'ggm-commerce' ); ?></label></th>
								<td>
									<input type="text" id="field-label" name="label" value="<?php echo esc_attr( $editing_field->label ?? '' ); ?>" class="regular-text">
									<p class="description"><?php esc_html_e( 'Label shown to customers on checkout. Defaults to Admin Name if left empty.', 'ggm-commerce' ); ?></p>
								</td>
							</tr>
							<tr>
								<th><label for="field-type"><?php esc_html_e( 'Field Type', 'ggm-commerce' ); ?></label></th>
								<td>
									<select id="field-type" name="field_type">
										<?php foreach ( $field_types as $type_key => $type_label ) : ?>
											<option value="<?php echo esc_attr( $type_key ); ?>" <?php selected( $editing_field->field_type ?? 'text', $type_key ); ?>><?php echo esc_html( $type_label ); ?></option>
										<?php endforeach; ?>
									</select>
								</td>
							</tr>
							<tr class="field-options-row" style="<?php echo in_array( ( $editing_field->field_type ?? 'text' ), array( 'select', 'radio', 'checkbox' ), true ) ? '' : 'display:none;'; ?>">
								<th><label for="field-options"><?php esc_html_e( 'Options', 'ggm-commerce' ); ?></label></th>
								<td>
									<?php
									$options_text = '';
									if ( ! empty( $editing_field->options ) ) {
										$decoded = json_decode( $editing_field->options, true );
										if ( is_array( $decoded ) ) {
											$options_text = implode( "\n", $decoded );
										}
									}
									?>
									<textarea id="field-options" name="options" rows="4" class="large-text"><?php echo esc_textarea( $options_text ); ?></textarea>
									<p class="description"><?php esc_html_e( 'One option per line.', 'ggm-commerce' ); ?></p>
								</td>
							</tr>
							<tr>
								<th><label for="field-placeholder"><?php esc_html_e( 'Placeholder', 'ggm-commerce' ); ?></label></th>
								<td><input type="text" id="field-placeholder" name="placeholder" value="<?php echo esc_attr( $editing_field->placeholder ?? '' ); ?>" class="regular-text"></td>
							</tr>
							<tr>
								<th><label for="field-help-text"><?php esc_html_e( 'Help Text', 'ggm-commerce' ); ?></label></th>
								<td>
									<textarea id="field-help-text" name="help_text" rows="2" class="large-text"><?php echo esc_textarea( $editing_field->help_text ?? '' ); ?></textarea>
									<p class="description"><?php esc_html_e( 'Displayed below the field to guide the customer.', 'ggm-commerce' ); ?></p>
								</td>
							</tr>
							<tr>
								<th><label for="field-default"><?php esc_html_e( 'Default Value', 'ggm-commerce' ); ?></label></th>
								<td><input type="text" id="field-default" name="default_value" value="<?php echo esc_attr( $editing_field->default_value ?? '' ); ?>" class="regular-text"></td>
							</tr>
							<tr>
								<th><label for="field-position"><?php esc_html_e( 'Position', 'ggm-commerce' ); ?></label></th>
								<td>
									<select id="field-position" name="position">
										<?php foreach ( $positions as $pos_key => $pos_label ) : ?>
											<option value="<?php echo esc_attr( $pos_key ); ?>" <?php selected( $editing_field->position ?? 'after_billing', $pos_key ); ?>><?php echo esc_html( $pos_label ); ?></option>
										<?php endforeach; ?>
									</select>
									<p class="description"><?php esc_html_e( 'Where this field appears in checkout. Ignored if field is in a group (inherits group position).', 'ggm-commerce' ); ?></p>
								</td>
							</tr>
							<tr>
								<th><label for="field-width"><?php esc_html_e( 'Width', 'ggm-commerce' ); ?></label></th>
								<td>
									<select id="field-width" name="width">
										<option value="full" <?php selected( $editing_field->width ?? 'full', 'full' ); ?>><?php esc_html_e( 'Full Width', 'ggm-commerce' ); ?></option>
										<option value="half" <?php selected( $editing_field->width ?? 'full', 'half' ); ?>><?php esc_html_e( 'Half Width', 'ggm-commerce' ); ?></option>
									</select>
								</td>
							</tr>
							<tr>
								<th><label for="field-validation"><?php esc_html_e( 'Validation', 'ggm-commerce' ); ?></label></th>
								<td>
									<select id="field-validation" name="validation">
										<option value="" <?php selected( $editing_field->validation ?? '', '' ); ?>><?php esc_html_e( 'None', 'ggm-commerce' ); ?></option>
										<option value="email" <?php selected( $editing_field->validation ?? '', 'email' ); ?>><?php esc_html_e( 'Email', 'ggm-commerce' ); ?></option>
										<option value="url" <?php selected( $editing_field->validation ?? '', 'url' ); ?>><?php esc_html_e( 'URL', 'ggm-commerce' ); ?></option>
										<option value="number" <?php selected( $editing_field->validation ?? '', 'number' ); ?>><?php esc_html_e( 'Number', 'ggm-commerce' ); ?></option>
										<option value="phone" <?php selected( $editing_field->validation ?? '', 'phone' ); ?>><?php esc_html_e( 'Phone', 'ggm-commerce' ); ?></option>
									</select>
								</td>
							</tr>
							<tr>
								<th><?php esc_html_e( 'Options', 'ggm-commerce' ); ?></th>
								<td>
									<label>
										<input type="checkbox" name="required" value="1" <?php checked( $editing_field->required ?? 0, 1 ); ?>>
										<?php esc_html_e( 'Required', 'ggm-commerce' ); ?>
									</label>
									<br>
									<label>
										<input type="checkbox" name="admin_editable" value="1" <?php checked( $editing_field->admin_editable ?? 0, 1 ); ?>>
										<?php esc_html_e( 'Admin can edit on order', 'ggm-commerce' ); ?>
									</label>
									<br>
									<label>
										<input type="checkbox" name="show_in_email" value="1" <?php checked( $editing_field->show_in_email ?? 1, 1 ); ?>>
										<?php esc_html_e( 'Show in order emails', 'ggm-commerce' ); ?>
									</label>
								</td>
							</tr>
						</table>

						<p>
							<button type="submit" class="button button-primary" id="save-field-btn">
								<?php echo $editing_field ? esc_html__( 'Update Field', 'ggm-commerce' ) : esc_html__( 'Create Field', 'ggm-commerce' ); ?>
							</button>
							<a href="<?php echo esc_url( $base_url . '&view=fields' ); ?>" class="button"><?php esc_html_e( 'Cancel', 'ggm-commerce' ); ?></a>
						</p>
					</form>
				</div>

			<?php else : ?>
				<!-- Fields List -->
				<div class="card">
					<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
						<h3 style="margin: 0;"><?php esc_html_e( 'Checkout Fields', 'ggm-commerce' ); ?></h3>
						<a href="<?php echo esc_url( $base_url . '&view=fields&new_field=1' ); ?>" class="button button-primary">
							<?php esc_html_e( 'Add New Field', 'ggm-commerce' ); ?>
						</a>
					</div>

					<?php if ( ! empty( $all_fields ) ) : ?>
						<table class="wp-list-table widefat fixed striped">
							<thead>
								<tr>
									<th><?php esc_html_e( 'Name', 'ggm-commerce' ); ?></th>
									<th><?php esc_html_e( 'Label', 'ggm-commerce' ); ?></th>
									<th><?php esc_html_e( 'Type', 'ggm-commerce' ); ?></th>
									<th><?php esc_html_e( 'Position', 'ggm-commerce' ); ?></th>
									<th><?php esc_html_e( 'Required', 'ggm-commerce' ); ?></th>
									<th><?php esc_html_e( 'Group', 'ggm-commerce' ); ?></th>
									<th><?php esc_html_e( 'Status', 'ggm-commerce' ); ?></th>
									<th><?php esc_html_e( 'Actions', 'ggm-commerce' ); ?></th>
								</tr>
							</thead>
							<tbody>
								<?php
								// Build group membership map.
								$field_group_map = array();
								foreach ( $groups as $g ) {
									$gf = $checkout_fields->get_group_fields( $g->id );
									foreach ( $gf as $f ) {
										$field_group_map[ $f->id ] = $g;
									}
								}

								foreach ( $all_fields as $field ) :
									$in_group = isset( $field_group_map[ $field->id ] ) ? $field_group_map[ $field->id ] : null;
									?>
									<tr>
										<td><strong><?php echo esc_html( $field->name ); ?></strong></td>
										<td><?php echo esc_html( $field->label ); ?></td>
										<td><?php echo esc_html( $field_types[ $field->field_type ] ?? $field->field_type ); ?></td>
										<td>
											<?php
											if ( $in_group ) {
												echo esc_html( $positions[ $in_group->position ] ?? $in_group->position );
												echo ' <small>(' . esc_html__( 'via group', 'ggm-commerce' ) . ')</small>';
											} else {
												echo esc_html( $positions[ $field->position ] ?? $field->position );
											}
											?>
										</td>
										<td><?php echo $field->required ? '<span class="dashicons dashicons-yes" style="color: #46b450;"></span>' : '<span class="dashicons dashicons-minus" style="color: #999;"></span>'; ?></td>
										<td><?php echo $in_group ? esc_html( $in_group->name ) : '<span class="description">' . esc_html__( 'Ungrouped', 'ggm-commerce' ) . '</span>'; ?></td>
										<td>
											<span class="ggmc-status-badge ggmc-status-<?php echo esc_attr( $field->status ); ?>">
												<?php echo esc_html( ucfirst( $field->status ) ); ?>
											</span>
										</td>
										<td>
											<a href="<?php echo esc_url( $base_url . '&view=fields&edit_field=' . $field->id ); ?>" class="button button-small"><?php esc_html_e( 'Edit', 'ggm-commerce' ); ?></a>
											<button type="button" class="button button-small button-link-delete delete-field-btn" data-field-id="<?php echo esc_attr( $field->id ); ?>" data-field-name="<?php echo esc_attr( $field->name ); ?>">
												<?php esc_html_e( 'Delete', 'ggm-commerce' ); ?>
											</button>
										</td>
									</tr>
								<?php endforeach; ?>
							</tbody>
						</table>
					<?php else : ?>
						<p class="description"><?php esc_html_e( 'No checkout fields created yet. Click "Add New Field" to create your first custom checkout field.', 'ggm-commerce' ); ?></p>
					<?php endif; ?>
				</div>
			<?php endif; ?>
		<?php endif; ?>
	</div>

	<script type="text/javascript">
	jQuery(document).ready(function($) {
		var ajaxUrl = '<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>';
		var nonce = '<?php echo esc_js( $nonce ); ?>';
		var isEditing = <?php echo $editing_field ? 'true' : 'false'; ?>;
		var isEditingGroup = <?php echo $editing_group ? 'true' : 'false'; ?>;

		// Toggle options field visibility based on field type.
		$('#field-type').on('change', function() {
			var type = $(this).val();
			if (['select', 'radio', 'checkbox'].indexOf(type) !== -1) {
				$('.field-options-row').show();
			} else {
				$('.field-options-row').hide();
			}
		});

		// Field form submit.
		$('#checkout-field-form').on('submit', function(e) {
			e.preventDefault();
			var formData = $(this).serializeArray();
			var data = { action: isEditing ? 'ggmc_update_checkout_field' : 'ggmc_create_checkout_field', nonce: nonce };

			formData.forEach(function(item) {
				data[item.name] = item.value;
			});

			// Handle unchecked checkboxes.
			if (!data.required) data.required = '0';
			if (!data.admin_editable) data.admin_editable = '0';
			if (!data.show_in_email) data.show_in_email = '0';

			$('#save-field-btn').prop('disabled', true).text('Saving...');

			$.post(ajaxUrl, data, function(response) {
				if (response.success) {
					window.location.href = '<?php echo esc_url( $base_url . '&view=fields' ); ?>';
				} else {
					alert(response.data.message || 'Error saving field.');
					$('#save-field-btn').prop('disabled', false).text(isEditing ? 'Update Field' : 'Create Field');
				}
			}).fail(function() {
				alert('Request failed.');
				$('#save-field-btn').prop('disabled', false).text(isEditing ? 'Update Field' : 'Create Field');
			});
		});

		// Group form submit.
		$('#checkout-field-group-form').on('submit', function(e) {
			e.preventDefault();
			var formData = $(this).serializeArray();
			var data = { action: isEditingGroup ? 'ggmc_update_checkout_field_group' : 'ggmc_create_checkout_field_group', nonce: nonce };

			formData.forEach(function(item) {
				data[item.name] = item.value;
			});

			$('#save-group-btn').prop('disabled', true).text('Saving...');

			$.post(ajaxUrl, data, function(response) {
				if (response.success) {
					window.location.href = '<?php echo esc_url( $base_url . '&view=groups' ); ?>';
				} else {
					alert(response.data.message || 'Error saving group.');
					$('#save-group-btn').prop('disabled', false).text(isEditingGroup ? 'Update Group' : 'Create Group');
				}
			}).fail(function() {
				alert('Request failed.');
				$('#save-group-btn').prop('disabled', false).text(isEditingGroup ? 'Update Group' : 'Create Group');
			});
		});

		// Delete field.
		$('.delete-field-btn').on('click', function() {
			var fieldId = $(this).data('field-id');
			var fieldName = $(this).data('field-name');
			if (!confirm('Delete field "' + fieldName + '"? Order values for this field will be preserved.')) return;

			$.post(ajaxUrl, {
				action: 'ggmc_delete_checkout_field',
				nonce: nonce,
				field_id: fieldId
			}, function(response) {
				if (response.success) {
					location.reload();
				} else {
					alert(response.data.message || 'Error deleting field.');
				}
			});
		});

		// Delete group.
		$('.delete-group-btn').on('click', function() {
			var groupId = $(this).data('group-id');
			var groupName = $(this).data('group-name');
			if (!confirm('Delete group "' + groupName + '"? Fields in this group will become ungrouped.')) return;

			$.post(ajaxUrl, {
				action: 'ggmc_delete_checkout_field_group',
				nonce: nonce,
				group_id: groupId
			}, function(response) {
				if (response.success) {
					location.reload();
				} else {
					alert(response.data.message || 'Error deleting group.');
				}
			});
		});

		// Add field to group.
		$('.add-field-to-group-btn').on('click', function() {
			var groupId = $(this).data('group-id');
			var fieldId = $('#add-field-to-group-select').val();
			if (!fieldId) return;

			$.post(ajaxUrl, {
				action: 'ggmc_add_field_to_group',
				nonce: nonce,
				group_id: groupId,
				field_id: fieldId
			}, function(response) {
				if (response.success) {
					location.reload();
				} else {
					alert(response.data.message || 'Error adding field to group.');
				}
			});
		});

		// Remove field from group.
		$('.remove-from-group-btn').on('click', function() {
			var groupId = $(this).data('group-id');
			var fieldId = $(this).data('field-id');

			$.post(ajaxUrl, {
				action: 'ggmc_remove_field_from_group',
				nonce: nonce,
				group_id: groupId,
				field_id: fieldId
			}, function(response) {
				if (response.success) {
					location.reload();
				} else {
					alert(response.data.message || 'Error removing field from group.');
				}
			});
		});
	});
	</script>

	<style>
	.ggmc-checkout-fields-admin .card { padding: 15px 20px; max-width: 100%; }
	.ggmc-checkout-fields-admin .form-table th { width: 160px; padding: 15px 10px 15px 0; }
	.ggmc-checkout-fields-admin .required { color: #dc3545; }
	.ggmc-status-badge { display: inline-block; padding: 2px 8px; border-radius: 3px; font-size: 12px; }
	.ggmc-status-active { background: #d4edda; color: #155724; }
	.ggmc-status-inactive { background: #f8d7da; color: #721c24; }
	</style>
	<?php
}
