<?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();

	// Check premium access
	if ( isset( $tabs[ $active_tab ] ) && $tabs[ $active_tab ]['premium'] && ! Sifency_Addons_Theme_Builder_Master::sifency_addons_is_legal() ) {
		sifency_addons_render_premium_upsell( $tabs[ $active_tab ]['label'] );
		return;
	}

	// Base query
	$args = [
		'post_type'      => 'themebuilder',
		'posts_per_page' => -1,
	];

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

	// Filter by taxonomy if not "all" or "trash"
	if ( ! in_array( $active_tab, [ 'all', 'trash' ], true ) ) {
		$args['tax_query'] = [[
			'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><?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 );

						// URLs
						$edit_url     = admin_url( 'post.php?post=' . $sifency_addons_template_id . '&action=elementor' );
						$preview_url  = add_query_arg( [ '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 );

						// Human-readable post status
						$post_status = get_post_status( $sifency_addons_template_id );
                        $post_status_label = ucfirst( $post_status );

						?>
						<tr>
							<td>
								<strong class="table-list-item-title"><?php the_title(); ?></strong><br>
								<div class="d-flex">
									<?php if ( 'trash' !== $active_tab ) : ?>
										<a href="<?php echo esc_url( $edit_url ); ?>" target="_blank" class="sifency-edit-elementor-link">
											<?php esc_html_e( 'Edit with Elementor', 'sifency-addons' ); ?>
										</a> 
										<div class="sifency-separator">|</div>
										<a href="<?php echo esc_url( $preview_url ); ?>" target="_blank" class="sifency-preview-link">
											<?php esc_html_e( 'Preview', 'sifency-addons' ); ?>
										</a>
									<?php endif; ?>
								</div>
							</td>
							<td class="sifency-post-switch-status-col">
								<?php if ( 'trash' !== $active_tab ) : ?>
									<label class="sifency-switch">
										<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 
                                $note_text = esc_html__( 'This template is not published. It will not appear. Please edit with Elementor and publish it.', 'sifency-addons' );
                                $span_attributes = '';
                                if ( in_array( $post_status, ['draft', 'pending'], true ) ) {
                                    $span_attributes = ' data-tooltip="' . esc_attr( $note_text ) . '"';
                                }
                                echo '<span class="sifency-status-label"' . wp_kses_post ( $span_attributes ) . '>' . esc_html( $post_status_label ) . '</span>';
                                ?>
							</td>
							<td class="sifency-conditions-summary sifency-post-condition-col">
								<?php
								if ( ! empty( $conditions ) && is_array( $conditions ) ) {
									$include_count = count( $conditions['include'] ?? [] );
									$exclude_count = count( $conditions['exclude'] ?? [] );
									?>
									<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>

				<button class="sifency-floating-add-btn" 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
}