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

class Sifency_CPT_Items {
	private function render_sidebar( $post_type ) {
		$post_type_obj  = get_post_type_object( $post_type );
		$count_posts    = wp_count_posts( $post_type );
		$current_status = isset( $_GET['post_status'] ) ? $_GET['post_status'] : 'all';
		$current_cat    = isset( $_GET['term'] ) ? $_GET['term'] : '';

		$taxonomies = get_object_taxonomies( $post_type, 'objects' );
		$main_tax   = null;
		if ( ! empty( $taxonomies ) ) {
			foreach ( $taxonomies as $tax ) {
				if ( $tax->public ) {
					$main_tax = $tax;
					break; }
			}
		}
		?>
		<aside class="sifency-cpt-sidebar">
			<div class="sifency-brand">
				<div class="sifency-logo-icon"><span class="dashicons dashicons-admin-post"></span></div>
				<span><?php echo esc_html( $post_type_obj->labels->name ); ?></span>
			</div>
			<nav class="sifency-nav">
				<div class="sifency-nav-cpt">
				<div class="nav-section-title">Status</div>
				<div class="sifency-nav-items">
				<a href="<?php echo esc_url( admin_url( 'edit.php?post_type=' . $post_type ) ); ?>" class="sifency-admin-btn nav-item <?php echo $current_status === 'all' && $current_cat === '' ? 'active' : ''; ?>">
					<span class="dashicons dashicons-menu"></span> All Posts <span class="count"><?php echo esc_html( number_format_i18n( $count_posts->publish + $count_posts->draft ) ); ?></span>
				</a>
				
				<a href="<?php echo esc_url( admin_url( 'edit.php?post_type=' . $post_type . '&post_status=publish' ) ); ?>" class="sifency-admin-btn nav-item <?php echo $current_status === 'publish' ? 'active' : ''; ?>">
					<span class="dashicons dashicons-yes-alt"></span> Published <span class="count"><?php echo esc_html( number_format_i18n( $count_posts->publish ) ); ?></span>
				</a>
				
				<a href="<?php echo esc_url( admin_url( 'edit.php?post_type=' . $post_type . '&post_status=draft' ) ); ?>" class="sifency-admin-btn nav-item <?php echo $current_status === 'draft' ? 'active' : ''; ?>">
					<span class="dashicons dashicons-edit"></span> Drafts <span class="count"><?php echo esc_html( number_format_i18n( $count_posts->draft ) ); ?></span>
				</a>
				
				<a href="<?php echo esc_url( admin_url( 'edit.php?post_type=' . $post_type . '&post_status=trash' ) ); ?>" class="sifency-admin-btn nav-item <?php echo $current_status === 'trash' ? 'active' : ''; ?>">
					<span class="dashicons dashicons-trash"></span> Trash <span class="count"><?php echo esc_html( number_format_i18n( $count_posts->trash ) ); ?></span>
				</a>
				</div>
				</div>
				<div class="category-container">
				<?php
				if ( $main_tax ) :
					$terms = get_terms(
						array(
							'taxonomy'   => $main_tax->name,
							'hide_empty' => true,
						)
					);
					if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) :
						?>
						<div class="nav-section-title"><?php echo esc_html( $main_tax->labels->name ); ?></div>
						<div class="nav-scroll-area">
						<?php
						foreach ( $terms as $term ) :
							$link      = admin_url( 'edit.php?post_type=' . $post_type . '&' . $main_tax->name . '=' . $term->slug );
							$is_active = ( isset( $_GET[ $main_tax->name ] ) && $_GET[ $main_tax->name ] === $term->slug );
							?>
							<a href="<?php echo esc_url( $link ); ?>" class="sifency-admin-btn nav-item <?php echo $is_active ? 'active' : ''; ?>">
								<span class="dashicons dashicons-category"></span> <?php echo esc_html( $term->name ); ?>
							   
								<span class="count"><?php echo esc_html( number_format_i18n( $term->count ) ); ?></span>
							</a>
						<?php endforeach; ?>
						</div>
						
						<a href="<?php echo esc_url( admin_url( 'edit-tags.php?taxonomy=' . $main_tax->name . '&post_type=' . $post_type ) ); ?>" class="nav-item-manage sifency-admin-btn text_underline_animation">
							<span>Manage Categories</span> &rarr;
						</a>
					<?php endif; ?>
				<?php endif; ?>
				</div>
			</nav>
			<div class="sidebar-footer">
				<a href="<?php echo esc_url( add_query_arg( 'view', 'classic' ) ); ?>" class="classic-link sifency-admin-btn text_underline_animation">
					<span class="dashicons dashicons-undo"></span> <span>Switch to Classic View</span>
				</a>
			</div>
		</aside>
		<?php
	}

	public function render_post_list_interface() {
		global $wp_query;
		$screen        = get_current_screen();
		$post_type_obj = get_post_type_object( $screen->post_type );
		$search_query  = isset( $_GET['s'] ) ? sanitize_text_field( $_GET['s'] ) : '';

		if ( function_exists( 'sifency_addons_admin_render_layout' ) ) {
			sifency_addons_admin_render_layout( '', function () { } );
		}
		?>
		<div class="sifency-app-wrapper">
			<?php $this->render_sidebar( $screen->post_type ); ?>
			<main class="sifency-main">
				<header class="sifency-topbar">
					<div class="topbar-left">
						<h2><?php echo esc_html( $post_type_obj->labels->name ); ?></h2>
					</div>
					<div class="topbar-right">
						<form method="get" class="sifency-search sifency-admin-btn">
							<input type="hidden" name="post_type" value="<?php echo esc_attr( $screen->post_type ); ?>">
							<span class="dashicons dashicons-search sifency-admin-btn"></span>
						   
							<input type="search" name="s" value="<?php echo esc_attr( $search_query ); ?>" placeholder="Search..." class="sifency-admin-btn">
						</form>
						
						<a href="<?php echo esc_url( admin_url( 'post-new.php?post_type=' . $screen->post_type ) ); ?>" class="sifency-btn-primary sifency-admin-btn save-meta">
							<span class="dashicons dashicons-plus"></span> Add New
						</a>
					</div>
				</header>

				<div class="sifency-content-area">
					<?php if ( have_posts() ) : ?>
						<div class="sifency-grid">
							<?php
							while ( have_posts() ) :
								the_post();
								$id             = get_the_ID();
								$status         = get_post_status();
								$edit_link      = get_edit_post_link();
								$elementor_link = admin_url( 'post.php?post=' . $id . '&action=elementor' );
								$dup_nonce      = wp_create_nonce( 'sifency_duplicate_post_' . $id );
								$duplicate_link = admin_url( 'admin.php?action=sifency_duplicate_post&post=' . $id . '&sifency_duplicate_nonce=' . $dup_nonce );
								$view_link      = ( 'publish' === $status ) ? get_permalink( $id ) : get_preview_post_link( $id );

								$thumb_id  = get_post_thumbnail_id( $id );
								$thumb_url = wp_get_attachment_image_url( $thumb_id, 'thumbnail' );
								$has_thumb = ! empty( $thumb_url );

								$post_type    = get_post_type();
								$main_tax_obj = null;
								$taxonomies   = get_object_taxonomies( $post_type, 'objects' );
								if ( $taxonomies ) {
									foreach ( $taxonomies as $tax ) {
										if ( $tax->public && $tax->hierarchical ) {
											$main_tax_obj = $tax;
											break;
										}
									}
								}
								?>
								
								<div class="sifency-card-for-cpt" id="post-card-<?php echo esc_attr( $id ); ?>">
									<div class="card-status status-<?php echo esc_attr( $status ); ?>"></div>
									<div class="card-body">
										<div class="cpt-card-header">
											<h3 class="card-title">
												<?php
												sifency_addons_render_template_inline_edit(
													$id,
													array(
														'editable'       => ( 'trash' !== $status ),
														'variant'        => 'cpt-card',
														'title_fallback' => '(No Title)',
													)
												);
												?>
											</h3>
											<?php if ( $status !== 'trash' ) : ?>
												
												<div class="sifency-thumb-wrapper" data-id="<?php echo esc_attr( $id ); ?>" title="Click to set Featured Image">
													<img src="<?php echo $has_thumb ? esc_url( $thumb_url ) : ''; ?>" 
														class="sifency-thumb-img <?php echo $has_thumb ? '' : 'hidden'; ?>">
													<div class="sifency-thumb-placeholder <?php echo $has_thumb ? 'hidden' : ''; ?>">
														<span class="dashicons dashicons-camera"></span>
													</div>
													<div class="sifency-thumb-spinner dashicons dashicons-update"></div>
												</div>
											<?php endif; ?>
										</div>
										<div class="card-meta">
											<div>
												<span title="Published Date" style="display:block; margin-bottom:5px;">
													<span class="dashicons dashicons-calendar-alt"></span> 
													<?php echo get_the_date( 'M j, Y' ); ?>
												</span>
												<div class="sifency-cat-wrapper">
													<span class="dashicons dashicons-category"></span>
													<?php
													if ( $main_tax_obj ) :
														$all_terms        = get_terms(
															array(
																'taxonomy'   => $main_tax_obj->name,
																'hide_empty' => false,
															)
														);
														$current_term_ids = wp_get_post_terms( $id, $main_tax_obj->name, array( 'fields' => 'ids' ) );
														?>
														<select class="sifency-select2-update" 
																data-post-id="<?php echo esc_attr( $id ); ?>" 
																data-tax="<?php echo esc_attr( $main_tax_obj->name ); ?>" 
																multiple="multiple">
															<?php
															foreach ( $all_terms as $term ) :
																$selected = in_array( $term->term_id, $current_term_ids ) ? 'selected' : '';
																?>
																<option value="<?php echo esc_attr( $term->term_id ); ?>" <?php echo esc_attr( $selected ); ?>>
																	<?php echo esc_html( $term->name ); ?>
																</option>
															<?php endforeach; ?>
														</select>
													<?php else : ?>
														<span style="opacity:0.6;">No Taxonomy</span>
													<?php endif; ?>
												</div>
											</div>
											
											<span class="status-badge badge-<?php echo esc_attr( $status ); ?>"><?php echo esc_html( ucfirst( $status ) ); ?></span>
										</div>
										<div class="sifency-download-post-date">
										<?php
										$post_id    = get_the_ID();
										$exporter   = new \Sifency\Admin\Elementor_Native_Exporter();
										$export_url = $exporter->get_export_url( $post_id );

										if ( $export_url ) :
											?>
											<a href="<?php echo esc_url( $export_url ); ?>"
											class="sifency-admin-btn sifency-export-link text-underline-animation status-badge">
												<span><?php esc_html_e( 'Export JSON', 'sifency-addons' ); ?></span>
											</a>
										<?php endif; ?>
										</div>
									</div>
									<div class="card-actions">
										<?php if ( 'trash' !== $status ) : ?>
											<div class="sifency-group-links">
												<a href="<?php echo esc_url( $elementor_link ); ?>" class="sifency-btn-xs btn-elementor sifency-admin-btn text_underline_animation" target="_blank"><span class="dashicons dashicons-art"></span> <span>Elementor</span></a>
												
												<a href="<?php echo esc_url( $edit_link ); ?>" class="sifency-btn-xs btn-classic sifency-admin-btn text_underline_animation" target="_blank"><span class="dashicons dashicons-edit"></span> <span>Classic</span></a>
												
												<button type="button" class="sifency-btn-xs btn-meta sifency-admin-btn text_underline_animation sifency-meta-trigger" data-id="<?php echo esc_attr( $id ); ?>">
													<span class="dashicons dashicons-forms"></span><span>Meta</span>
												</button>
											</div>
											<div class="sifency-cpt-icons">
												<a href="<?php echo esc_url( $view_link ); ?>" target="_blank" class="sifency-icon-btn sifency-admin-btn" title="Preview / View">
													<span class="dashicons dashicons-visibility"></span>
												</a>
												<a href="<?php echo esc_url( $duplicate_link ); ?>" class="sifency-icon-btn sifency-admin-btn" title="Duplicate"><span class="dashicons dashicons-admin-page"></span></a>
												<a href="<?php echo get_delete_post_link(); ?>" class="sifency-icon-btn delete-link sifency-admin-btn" onclick="return confirm('Trash this item?')" title="Move to Trash"><span class="dashicons dashicons-trash"></span></a>
											</div>
										<?php else : ?>
											<?php $restore_url = wp_nonce_url( admin_url( 'post.php?action=untrash&post=' . $id ), 'untrash-post_' . $id ); ?>
											<a href="<?php echo esc_url( $restore_url ); ?>" class="sifency-btn-xs btn-classic sifency-admin-btn"><span class="dashicons dashicons-undo"></span> Restore</a>
											<a href="<?php echo get_delete_post_link( $id, '', true ); ?>" class="sifency-icon-btn delete-link sifency-admin-btn" onclick="return confirm('Delete permanently?')" title="Delete Permanently"><span class="dashicons dashicons-trash"></span></a>
										<?php endif; ?>
									</div>
								</div>
							<?php endwhile; ?>
						</div>
						<?php if ( $wp_query->max_num_pages > 1 ) : ?>
							<div class="sifency-pagination">
								
								<?php
								echo wp_kses_post(
									paginate_links(
										array(
											'base'      => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
											'format'    => '?paged=%#%',
											'current'   => max( 1, get_query_var( 'paged' ) ),
											'total'     => $wp_query->max_num_pages,
											'prev_text' => '&larr;',
											'next_text' => '&rarr;',
										)
									)
								);
								?>
							</div>
						<?php endif; ?>
					<?php else : ?>
						<div class="sifency-empty-state"><span class="dashicons dashicons-filter"></span><h3>No items found</h3></div>
					<?php endif; ?>
				</div>
				
				<a href="<?php echo esc_url( admin_url( 'post-new.php?post_type=' . $screen->post_type ) ); ?>" class="sifency-btn-primary sifency-admin-btn sifency-floating-add-btn">
					<span class="sifency-add-label"> Add new</span>
					<span class="sifency-add-icon"><span class="dashicons dashicons-plus"></span> </span>
				</a>
			</main>
		</div>
		<?php
	}
}