<?php
defined( 'ABSPATH' ) || exit;

function formulate_pricing_entries_page() {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'You do not have sufficient permissions.', 'formulate-pricing' ) );
	}

	// phpcs:disable WordPress.Security.NonceVerification.Recommended -- read-only GET filter params on admin display page
	$form_id  = isset( $_GET['form_id'] ) ? absint( wp_unslash( $_GET['form_id'] ) ) : 0;
	$search   = sanitize_text_field( isset( $_GET['s'] ) ? wp_unslash( $_GET['s'] ) : '' );
	$status   = sanitize_text_field( isset( $_GET['status'] ) ? wp_unslash( $_GET['status'] ) : '' );
	$allowed_statuses = array( '', 'unread', 'read', 'starred', 'trash' );
	if ( ! in_array( $status, $allowed_statuses, true ) ) {
		$status = '';
	}
	$paged    = max( 1, isset( $_GET['paged'] ) ? absint( wp_unslash( $_GET['paged'] ) ) : 1 );
	// phpcs:enable WordPress.Security.NonceVerification.Recommended
	$per_page = 25;

	// Fetch selected form info
	$current_form = $form_id ? Formulate_Pricing_Form::get( $form_id ) : null;

	// Get all forms for filter dropdown
	$all_forms = Formulate_Pricing_Form::get_all( array( 'per_page' => 100 ) );

	$query_args = array(
		'form_id'  => $form_id,
		'search'   => $search,
		'status'   => $status,
		'page'     => $paged,
		'per_page' => $per_page,
	);

	$entries = Formulate_Pricing_Entry::get_all( $query_args );
	$total   = Formulate_Pricing_Entry::count( $query_args );
	$pages   = (int) ceil( $total / $per_page );

	// Table columns: compact list — 2 labeled fields when a form is selected, else one summary.
	$list_columns   = $form_id ? Formulate_Pricing_Entry::get_list_columns( $form_id, 2 ) : array();
	$show_summary   = ! $form_id;
	$table_colspan  = 5 + ( $show_summary ? 1 : count( $list_columns ) );

	$export_nonce = wp_create_nonce( 'formulate_pricing_export_entries' );
	$export_url   = admin_url( 'admin-post.php?action=formulate_pricing_export_entries&form_id=' . $form_id . '&_wpnonce=' . $export_nonce );

	// Status counts
	$status_labels = array(
		''        => __( 'All', 'formulate-pricing' ),
		'unread'  => __( 'Unread', 'formulate-pricing' ),
		'read'    => __( 'Read', 'formulate-pricing' ),
		'starred' => __( 'Starred', 'formulate-pricing' ),
		'trash'   => __( 'Trash', 'formulate-pricing' ),
	);
	?>
	<div class="wrap bf-admin-wrap bf-entries-wrap">

		<!-- Page header -->
		<div class="bf-page-header">
			<div class="bf-page-header-left">
				<h1>
					<?php esc_html_e( 'Entries', 'formulate-pricing' ); ?>
					<?php if ( $current_form ) : ?>
						<span style="font-weight:400;color:#6b7280;font-size:18px"> / <?php echo esc_html( $current_form->title ); ?></span>
					<?php endif; ?>
				</h1>
				<p>
					<?php
					echo esc_html( sprintf(
						/* translators: %d: number of entries */
						_n( '%d entry', '%d entries', $total, 'formulate-pricing' ),
						$total
					) );
					?>
				</p>
			</div>
		<a href="<?php echo esc_url( $export_url ); ?>" class="bf-btn-secondary">
			<i class="hgi-stroke hgi-download-02"></i>
			<?php esc_html_e( 'Export CSV', 'formulate-pricing' ); ?>
		</a>
		</div>

		<!-- Filters bar -->
		<form method="get" action="<?php echo esc_url( admin_url( 'admin.php' ) ); ?>" id="bf-filters-form">
			<input type="hidden" name="page" value="formulate-pricing-entries">
			<input type="hidden" name="status" value="<?php echo esc_attr( $status ); ?>">

			<div class="bf-toolbar" style="margin-bottom:12px;">
				<!-- Form selector -->
				<select name="form_id" class="bf-filter-select" onchange="this.form.submit()">
					<option value="0"><?php esc_html_e( 'All Forms', 'formulate-pricing' ); ?></option>
					<?php foreach ( $all_forms as $f ) : ?>
					<option value="<?php echo esc_attr( $f->id ); ?>" <?php selected( $form_id, $f->id ); ?>>
						<?php echo esc_html( $f->title ); ?>
					</option>
					<?php endforeach; ?>
				</select>

				<!-- Search -->
			<div class="bf-search-field">
				<i class="hgi-stroke hgi-search-01"></i>
				<input type="search" name="s" value="<?php echo esc_attr( $search ); ?>" placeholder="<?php esc_attr_e( 'Search entries…', 'formulate-pricing' ); ?>">
				<button type="submit" aria-label="<?php esc_attr_e( 'Search', 'formulate-pricing' ); ?>">
					<i class="hgi-stroke hgi-arrow-right-01"></i>
				</button>
			</div>
			</div>

			<!-- Status tabs -->
			<div style="margin-bottom:12px;">
				<div class="bf-status-tabs">
					<?php foreach ( $status_labels as $st_val => $st_label ) :
						$cnt     = Formulate_Pricing_Entry::count( array( 'form_id' => $form_id, 'status' => $st_val, 'search' => $search ) );
						$tab_url = add_query_arg(
							array(
								'page'    => 'formulate-pricing-entries',
								'status'  => $st_val,
								'paged'   => 1,
								'form_id' => $form_id,
								's'       => $search,
							),
							admin_url( 'admin.php' )
						);
					?>
					<a href="<?php echo esc_url( $tab_url ); ?>"
					   class="bf-status-tab<?php echo esc_attr( $status === $st_val ? ' active' : '' ); ?>">
						<?php echo esc_html( $st_label ); ?>
						<span class="bf-status-count"><?php echo esc_html( $cnt ); ?></span>
					</a>
					<?php endforeach; ?>
				</div>
			</div>
		</form>

		<!-- Bulk action bar -->
		<div class="bf-bulk-bar">
			<select id="bf-bulk-action">
				<option value=""><?php esc_html_e( 'Bulk Actions', 'formulate-pricing' ); ?></option>
				<option value="read"><?php esc_html_e( 'Mark as Read', 'formulate-pricing' ); ?></option>
				<option value="unread"><?php esc_html_e( 'Mark as Unread', 'formulate-pricing' ); ?></option>
				<option value="starred"><?php esc_html_e( 'Mark as Starred', 'formulate-pricing' ); ?></option>
				<option value="trash"><?php esc_html_e( 'Move to Trash', 'formulate-pricing' ); ?></option>
				<option value="delete"><?php esc_html_e( 'Delete Permanently', 'formulate-pricing' ); ?></option>
			</select>
			<button id="bf-bulk-apply"><?php esc_html_e( 'Apply', 'formulate-pricing' ); ?></button>
			<span class="bf-bulk-msg"></span>
		</div>

		<!-- Entries table -->
		<div class="bf-card">
			<table class="bf-table">
				<thead>
					<tr>
						<th style="width:36px"><input type="checkbox" id="bf-check-all-entries"></th>
						<th style="width:32px"></th>
						<th><?php esc_html_e( 'Date', 'formulate-pricing' ); ?></th>
						<?php if ( $show_summary ) : ?>
						<th><?php esc_html_e( 'Form', 'formulate-pricing' ); ?></th>
						<th><?php esc_html_e( 'Summary', 'formulate-pricing' ); ?></th>
						<?php else : ?>
							<?php foreach ( $list_columns as $col ) : ?>
						<th><?php echo esc_html( $col['label'] ); ?></th>
							<?php endforeach; ?>
						<?php endif; ?>
						<th><?php esc_html_e( 'Payment', 'formulate-pricing' ); ?></th>
						<th><?php esc_html_e( 'Actions', 'formulate-pricing' ); ?></th>
					</tr>
				</thead>
				<tbody>
				<?php if ( empty( $entries ) ) : ?>
					<tr>
						<td colspan="<?php echo (int) $table_colspan; ?>">
							<div class="bf-empty-state">
						<div class="bf-empty-icon">
								<i class="hgi-stroke hgi-note-01" style="font-size:36px;color:#9ca3af"></i>
							</div>
								<h3><?php esc_html_e( 'No entries found', 'formulate-pricing' ); ?></h3>
								<p>
									<?php if ( $search || $status ) : ?>
										<?php esc_html_e( 'Try adjusting your filters or search term.', 'formulate-pricing' ); ?>
									<?php else : ?>
										<?php esc_html_e( 'Entries will appear here once someone submits your form.', 'formulate-pricing' ); ?>
									<?php endif; ?>
								</p>
							</div>
						</td>
					</tr>
				<?php else : ?>
					<?php foreach ( $entries as $entry ) :
						$entry_form_label = '';
						foreach ( $all_forms as $f ) {
							if ( (int) $f->id === (int) $entry->form_id ) {
								$entry_form_label = $f->title;
								break;
							}
						}
						$is_unread  = 'unread'  === $entry->status;
						$is_starred = 'starred' === $entry->status;
						$pay        = Formulate_Pricing_Entry::get_payment_status_display( $entry->payment_status ?? '' );
					?>
					<tr class="bf-entry-row<?php echo esc_attr( $is_unread ? ' bf-entry-unread' : '' ); ?>"
						data-entry-id="<?php echo esc_attr( $entry->id ); ?>">
						<td><input type="checkbox" class="bf-entry-check" value="<?php echo esc_attr( $entry->id ); ?>"></td>
						<td style="text-align:center">
							<?php if ( $is_starred ) : ?>
								<span class="bf-star-icon" title="<?php esc_attr_e( 'Starred', 'formulate-pricing' ); ?>">&#9733;</span>
							<?php elseif ( $is_unread ) : ?>
								<span class="bf-unread-dot" title="<?php esc_attr_e( 'Unread', 'formulate-pricing' ); ?>"></span>
							<?php endif; ?>
						</td>
						<td>
							<a href="#" class="bf-view-entry" data-entry-id="<?php echo esc_attr( $entry->id ); ?>"
							   style="color:#111827;text-decoration:none;font-size:13px;">
								<?php echo esc_html( date_i18n( 'M j, Y', strtotime( $entry->created_at ) ) ); ?>
							</a>
							<div style="font-size:11.5px;color:#9ca3af">
								<?php echo esc_html( date_i18n( get_option( 'time_format' ), strtotime( $entry->created_at ) ) ); ?>
							</div>
						</td>
						<?php if ( $show_summary ) : ?>
						<td style="font-size:12.5px;color:#6b7280"><?php echo esc_html( $entry_form_label ); ?></td>
						<td>
							<?php
							$summary = Formulate_Pricing_Entry::build_entry_summary( (int) $entry->form_id, $entry->entry_data, 2 );
							?>
							<span class="bf-entry-snippet" title="<?php echo esc_attr( $summary ); ?>">
								<?php echo esc_html( $summary ?: '—' ); ?>
							</span>
						</td>
						<?php else : ?>
							<?php foreach ( $list_columns as $col ) :
								$val = Formulate_Pricing_Entry::format_field_value( $entry->entry_data, $col['id'], $col['field'] );
							?>
						<td>
							<span class="bf-entry-snippet" title="<?php echo esc_attr( $val ); ?>">
								<?php echo esc_html( $val ?: '—' ); ?>
							</span>
						</td>
							<?php endforeach; ?>
						<?php endif; ?>
						<td>
							<?php if ( ! empty( $entry->payment_status ) ) : ?>
								<span class="bf-payment-badge" style="background:<?php echo esc_attr( $pay['color'] ); ?>20;color:<?php echo esc_attr( $pay['color'] ); ?>">
									<?php echo esc_html( $pay['label'] ); ?>
								</span>
								<?php
								if ( ! empty( $entry->wc_order_id ) && function_exists( 'wc_get_order' ) ) :
									$wc_order = wc_get_order( $entry->wc_order_id );
									if ( $wc_order ) :
								?>
									<div style="font-size:11px;margin-top:4px">
										<a href="<?php echo esc_url( $wc_order->get_edit_order_url() ); ?>" target="_blank" rel="noopener">
											<?php
											echo esc_html(
												sprintf(
													/* translators: %s: WooCommerce order number */
													__( 'Order #%s', 'formulate-pricing' ),
													$wc_order->get_order_number()
												)
											);
											?>
										</a>
									</div>
								<?php
									endif;
								endif;
								?>
							<?php else : ?>
								<span style="color:#9ca3af">—</span>
							<?php endif; ?>
						</td>
						<td>
							<div class="bf-row-acts">
								<a href="#" class="bf-btn-sm bf-view-entry" data-entry-id="<?php echo esc_attr( $entry->id ); ?>"><?php esc_html_e( 'View', 'formulate-pricing' ); ?></a>
								<a href="#" class="bf-btn-sm danger bf-delete-entry" data-entry-id="<?php echo esc_attr( $entry->id ); ?>"><?php esc_html_e( 'Delete', 'formulate-pricing' ); ?></a>
							</div>
						</td>
					</tr>
					<?php endforeach; ?>
				<?php endif; ?>
				</tbody>
			</table>

			<?php if ( $pages > 1 ) : ?>
			<div class="bf-pagination">
				<span>
					<?php
					echo esc_html( sprintf(
						/* translators: 1: current page, 2: total pages */
						__( 'Page %1$d of %2$d', 'formulate-pricing' ),
						$paged,
						$pages
					) );
					?>
				</span>
				<div>
					<?php
					$pagination_base = add_query_arg(
						array(
							'page'    => 'formulate-pricing-entries',
							'form_id' => $form_id,
							'status'  => $status,
							's'       => $search,
							'paged'   => '%#%',
						),
						admin_url( 'admin.php' )
					);
					echo wp_kses_post(
						paginate_links(
							array(
								'base'      => $pagination_base,
								'format'    => '',
								'total'     => $pages,
								'current'   => $paged,
								'prev_text' => '&#8592;',
								'next_text' => '&#8594;',
							)
						)
					);
					?>
				</div>
			</div>
			<?php endif; ?>
		</div>
	</div>

	<!-- Entry Detail Modal -->
	<div id="bf-entry-modal" class="bf-modal" style="display:none">
		<div class="bf-modal-backdrop"></div>
		<div class="bf-modal-box">
			<div class="bf-modal-header">
				<h2><?php esc_html_e( 'Entry Details', 'formulate-pricing' ); ?></h2>
				<button class="bf-modal-close-btn bf-modal-close" type="button">&times;</button>
			</div>
			<div class="bf-modal-body" id="bf-entry-modal-body">
			<div class="bf-loading">
				<i class="hgi-stroke hgi-loading-03" style="font-size:20px;color:#6366f1;animation:bf-spin .7s linear infinite"></i>
				<?php esc_html_e( 'Loading…', 'formulate-pricing' ); ?>
			</div>
			</div>
			<div class="bf-modal-footer">
				<button class="bf-btn-secondary bf-modal-close"><?php esc_html_e( 'Close', 'formulate-pricing' ); ?></button>
				<button class="bf-btn-sm danger bf-modal-delete-entry" data-entry-id="" style="padding:7px 14px;">
					<?php esc_html_e( 'Delete Entry', 'formulate-pricing' ); ?>
				</button>
			</div>
		</div>
	</div>

	<?php
}
