<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Renders the content for a specific tab (the table of templates).
 */
function sifency_addons_render_tab_content( string $active_tab ): void {
	$tabs = sifency_addons_themebuilder_get_tabs();

	if ( isset( $tabs[ $active_tab ] ) && $tabs[ $active_tab ]['sync_state'] && ! Sifency_Addons_Theme_Builder_Master::sync_environment_state() ) {
		sifency_addons_render_sync_state_upsell( $tabs[ $active_tab ]['label'] );
		return;
	}

	$args = array(
		'post_type'      => 'themebuilder',
		'posts_per_page' => -1,
	);

	if ( 'trash' === $active_tab ) {
		$args['post_status'] = array( 'trash' );
	} else {
		$args['post_status'] = array( 'publish', 'draft', 'pending' );
	}

	if ( ! in_array( $active_tab, array( 'all', 'trash' ), true ) ) {
		$args['tax_query'] = array(
			array(
				'taxonomy' => 'sifency_builder_type',
				'field'    => 'slug',
				'terms'    => $active_tab,
			),
		);
	}

	$templates_query = new WP_Query( $args );
	?>
	<div class="sifency-templates-list-container">

		<table class="wp-list-table widefat fixed striped sifency-templates-table">
			<thead>
				<tr>
					<th class="sifency-post-title-col"><?php esc_html_e( 'Title', 'sifency-addons' ); ?></th>
					<th class="sifency-post-switch-status-col"><?php esc_html_e( 'Status', 'sifency-addons' ); ?></th>
					<th class="sifency-post-publish-status-col"><?php esc_html_e( 'Status', 'sifency-addons' ); ?></th>
					<th class="sifency-post-condition-col"><?php esc_html_e( 'Conditions', 'sifency-addons' ); ?></th>
					<th class="sifency-post-action-col"><?php esc_html_e( 'Actions', 'sifency-addons' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<?php if ( $templates_query->have_posts() ) : ?>
					<?php
					while ( $templates_query->have_posts() ) :
						$templates_query->the_post();
						$sifency_addons_template_id = get_the_ID();
						$is_active                  = get_post_meta( $sifency_addons_template_id, '_sifency_builder_active', true );
						$conditions                 = get_post_meta( $sifency_addons_template_id, '_themebuilder_conditions', true );
						$tooltip                    = 'Active or Deactive';
						$edit_url                   = admin_url( 'post.php?post=' . $sifency_addons_template_id . '&action=elementor' );
						$preview_url                = add_query_arg( array( 'preview' => 'true' ), get_permalink( $sifency_addons_template_id ) );
						$restore_url                = wp_nonce_url( admin_url( 'post.php?action=untrash&post=' . $sifency_addons_template_id ), 'untrash-post_' . $sifency_addons_template_id );
						$delete_perm                = wp_nonce_url( admin_url( 'post.php?action=delete&post=' . $sifency_addons_template_id ), 'delete-post_' . $sifency_addons_template_id );

						$dup_nonce      = wp_create_nonce( 'sifency_duplicate_post_' . $sifency_addons_template_id );
						$duplicate_link = admin_url( 'admin.php?action=sifency_duplicate_post&post=' . $sifency_addons_template_id . '&sifency_duplicate_nonce=' . $dup_nonce );
						?>
						<tr class="sifency-post-lists-wrap" data-template-id="<?php echo esc_attr( $sifency_addons_template_id ); ?>">
							<td  class="sifency-post-title-col">
								<?php
								sifency_addons_render_template_inline_edit(
									$sifency_addons_template_id,
									array( 'editable' => ( 'trash' !== $active_tab ) )
								);
								?>
								<div class="d-flex">
									<?php if ( 'trash' !== $active_tab ) : ?>
										<a href="<?php echo esc_url( $edit_url ); ?>" target="_blank" class="sifency-edit-elementor-link sifency-admin-btn text-underline-animation">
											<span><?php esc_html_e( 'Edit with Elementor', 'sifency-addons' ); ?></span>
										</a> 
										<div class="sifency-separator">|</div>
										<a href="<?php echo esc_url( $preview_url ); ?>" target="_blank" class="sifency-preview-link text-underline-animation">
											<span><?php esc_html_e( 'Preview', 'sifency-addons' ); ?></span>
										</a>
										<div class="sifency-separator">|</div>
										<a href="<?php echo esc_url( $duplicate_link ); ?>" class="sifency-admin-btn text-underline-animation"><span>Duplicate</span></a>
										<?php
										$post_id    = get_the_ID();
										$exporter   = new \Sifency\Admin\Elementor_Native_Exporter();
										$export_url = $exporter->get_export_url( $post_id );

										if ( $export_url ) :
											?>
											<div class="sifency-separator">|</div>

											<a href="<?php echo esc_url( $export_url ); ?>"
											class="sifency-admin-btn sifency-export-link text-underline-animation">
												<span><?php esc_html_e( 'Export JSON', 'sifency-addons' ); ?></span>
											</a>
										<?php endif; ?>

									<?php endif; ?>
								</div>
							</td>
							<td class="sifency-post-switch-status-col">
								<?php if ( 'trash' !== $active_tab ) : ?>
									<label class="sifency-switch" data-tooltip="<?php echo esc_attr( $tooltip ); ?>">
										<input type="checkbox" class="sifency-status-toggle"
											data-template-id="<?php echo esc_attr( $sifency_addons_template_id ); ?>"
											<?php checked( $is_active, '1' ); ?>>
										<span class="slider round"></span>
									</label>
									<span class="status-label">
										<?php echo $is_active ? esc_html__( 'Active', 'sifency-addons' ) : esc_html__( 'Inactive', 'sifency-addons' ); ?>
									</span>
								<?php else : ?>
									<span class="status-label">
										<?php esc_html_e( 'Trashed', 'sifency-addons' ); ?>
									</span>
								<?php endif; ?>
							</td>
							<td class="sifency-post-publish-status-col">
								<?php sifency_addons_render_template_status_badge( $sifency_addons_template_id ); ?>
							</td>
							<td class="sifency-conditions-summary sifency-post-condition-col">
								<?php
								if ( ! empty( $conditions ) && is_array( $conditions ) ) {
									$include_count = count( $conditions['include'] ?? array() );
									$exclude_count = count( $conditions['exclude'] ?? array() );
									?>
									<div class="sifency-condition-badges">
										<span class="sifency-badge include">
											<span class="dashicons dashicons-yes-alt"></span>
											<?php echo esc_html__( 'Include:', 'sifency-addons' ) . ' ' . absint( $include_count ); ?>
										</span>
										<span class="sifency-badge exclude">
											<span class="dashicons dashicons-no-alt"></span>
											<?php echo esc_html__( 'Exclude:', 'sifency-addons' ) . ' ' . absint( $exclude_count ); ?>
										</span>
									</div>
									<?php
								} else {
									?>
									<span class="sifency-notset"><?php esc_html_e( 'Not Set', 'sifency-addons' ); ?></span>
									<?php
								}
								?>
							</td>


							<td class="sifency-post-action-col">
								<?php if ( 'trash' !== $active_tab ) : ?>
									<div class="sifency-action-buttons">
										<button class="sifency-btn sifency-edit-conditions-btn edit"
												data-template-id="<?php echo esc_attr( $sifency_addons_template_id ); ?>">
											<span class="dashicons dashicons-edit"></span>
											<?php esc_html_e( 'Edit Conditions', 'sifency-addons' ); ?>
										</button>

										<a href="<?php echo esc_url( get_delete_post_link( $sifency_addons_template_id ) ); ?>"
										class="sifency-btn delete">
											<span class="dashicons dashicons-trash"></span>
											<?php esc_html_e( 'Delete', 'sifency-addons' ); ?>
										</a>
									</div>
								<?php else : ?>
									<div class="sifency-action-buttons">
										<a href="<?php echo esc_url( $restore_url ); ?>" class="sifency-btn restore sifency-admin-btn">
											<span class="dashicons dashicons-undo"></span>
											<?php esc_html_e( 'Restore', 'sifency-addons' ); ?>
										</a>

										<a href="<?php echo esc_url( $delete_perm ); ?>" class="sifency-btn delete-perm sifency-admin-btn">
											<span class="dashicons dashicons-no"></span>
											<?php esc_html_e( 'Delete Permanently', 'sifency-addons' ); ?>
										</a>
									</div>
								<?php endif; ?>
							</td>

						</tr>
						<?php
					endwhile;
					wp_reset_postdata();
					?>
				<?php else : ?>
					<tr><td colspan="5"><?php esc_html_e( 'No templates found.', 'sifency-addons' ); ?></td></tr>
				<?php endif; ?>
			</tbody>
		</table>

		<?php if ( 'trash' !== $active_tab ) : ?>
			<div class="sifency-templates-header">
				<button class="page-title-action" id="sifency-open-new-template-modal">
					<?php
					if ( 'all' !== $active_tab && isset( $tabs[ $active_tab ] ) ) {
						printf(
							/* translators: %s: Add new template type label */
							esc_html__( 'Add New %s', 'sifency-addons' ),
							esc_html( $tabs[ $active_tab ]['label'] )
						);
					} else {
						esc_html_e( 'Add New Template', 'sifency-addons' );
					}
					?>
				</button>

				<div class="sifency-template-notice fade-in" id="sifency-template-notice">
						<button type="button" class="sifency-notice-close">&times;</button>

						<div class="sifency-notice-icon">⚡</div>

						<div class="sifency-notice-content">
							<h4>Template Builder Priority</h4>

							<p>
								The <strong>Template Builder</strong> works independently from other layout settings.
								If a template is active here, it will automatically override:
							</p>

							<ul>
								<li>Theme Options Layout</li>
								<li>Metabox Template Settings</li>
								<li>Default Theme Layouts</li>
							</ul>

							<p class="sifency-notice-tip">
								💡 Tip: Disable the template here if you want to use the default theme layouts again.
							</p>
						</div>
				</div>

				<button class="sifency-floating-add-btn page-title-action sifency-floating-add-btn sifency-open-new-section-modal" id="sifency-open-new-template-modal">
					<span class="sifency-add-label">
						<?php
						if ( 'all' !== $active_tab && isset( $tabs[ $active_tab ] ) ) {
							printf(
								/* translators: %s: Add new template type label */
								esc_html__( 'Add New %s', 'sifency-addons' ),
								esc_html( $tabs[ $active_tab ]['label'] )
							);
						} else {
							esc_html_e( 'Add New Template', 'sifency-addons' );
						}
						?>
					</span>
					<span class="sifency-add-icon">+</span>
				</button>
			</div>
		<?php endif; ?>
	</div>
	<?php
}
