<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

$profile_id       = gigneo_active_profile_id();
$profile_type     = gigneo_profile_type( $profile_id );
$platform_type    = gigneo_platform_type();
$freelancer_label = gigneo_freelancer_plural();
$employer_label   = gigneo_employer_plural();
$profile_access   = gigneo_employer_profile_access();

// Define Tabs based on role and platform type
$saved_tabs       = array();
$default_tab      = 'freelancer' === $profile_type ? 'jobs' : 'freelancers';
$service_platform = in_array( $platform_type, array( 'services', 'both' ), true );
$jobs_platform    = in_array( $platform_type, array( 'jobs', 'both' ), true );

if ( 'freelancer' === $profile_type ) {
	if ( 'public' === $profile_access ) {
		$saved_tabs[ strtolower( $employer_label ) ] = array(
			'label'     => $employer_label,
			// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
			'meta_key'  => '_gigneo_pm_saved_employer',
			'card_path' => 'dashboard/saved/parts/employer',
			'type'      => 'employer',
		);

		$default_tab = strtolower( $employer_label );
	}
	if ( $jobs_platform ) {
			$saved_tabs['jobs'] = array(
				'label'     => esc_html__( 'Jobs', 'gigneo' ),
				// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
				'meta_key'  => '_gigneo_pm_saved_job',
				'card_path' => 'dashboard/saved/parts/job',
				'type'      => 'job',
			);
	}
} else {
	$saved_tabs[ strtolower( $freelancer_label ) ] = array(
		'label'     => $freelancer_label,
		// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
		'meta_key'  => '_gigneo_pm_saved_freelancer',
		'card_path' => 'dashboard/saved/parts/freelancer',
		'type'      => 'freelancer',
	);

	$default_tab = strtolower( $freelancer_label );
	if ( $service_platform ) {
		$saved_tabs['services'] = array(
			'label'     => esc_html__( 'Services', 'gigneo' ),
			// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
			'meta_key'  => '_gigneo_pm_saved_service',
			'card_path' => 'dashboard/saved/parts/service',
			'type'      => 'service',
		);
	}
}

// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only parameters no nonce required.
$active_tab   = ! empty( $_GET['tab'] ) ? sanitize_text_field( wp_unslash( $_GET['tab'] ) ) : $default_tab;
$search_val   = ! empty( $_GET['search'] ) ? sanitize_text_field( wp_unslash( $_GET['search'] ) ) : '';
$current_page = ! empty( $_GET['step'] ) ? intval( $_GET['step'] ) : 1;
// phpcs:enable WordPress.Security.NonceVerification.Recommended -- Read-only parameters no nonce required.

// Fetch Counts and identify active tab data
$current_saved_ids = array();
$current_tab_info  = array();

foreach ( $saved_tabs as $saved_key => $saved_tab ) {
	$saved_ids = array_filter( (array) gigneo_post_meta( $profile_id, $saved_tab['meta_key'] ) );
	$valid_ids = array_filter(
		$saved_ids,
		function ( $id ) {
			return ! empty( $id ) && in_array( get_post_status( $id ), array( 'publish', 'active' ), true );
		}
	);

	$saved_tabs[ $saved_key ]['count'] = count( $valid_ids );
	if ( $active_tab === $saved_key ) {
		$current_saved_ids = $valid_ids;
		$current_tab_info  = $saved_tab;
	}
}
// Fallback to 'items' if tab is invalid
if ( empty( $current_tab_info ) ) {
	$active_tab        = 'items';
	$current_tab_info  = $saved_tabs['items'] ?? array();
	$saved_ids         = (array) gigneo_post_meta( $profile_id, $current_tab_info['meta_key'] ) ?? array();
	$current_saved_ids = array_filter( $saved_ids, 'get_post_status' );
}

$saved_type    = $current_tab_info['type'] ?? 'item';
$show_per_page = apply_filters( 'gigneo_saved_per_page', 9 );
$saved_query   = null;
$display_count = 0;
if ( ! empty( $current_saved_ids ) ) {
	$args = array(
		'post_type'      => 'gigneo_' . $saved_type,
		'post_status'    => array( 'publish', 'active' ),
		'post__in'       => $current_saved_ids,
		'posts_per_page' => $show_per_page,
		'paged'          => $current_page,
	);

	if ( ! empty( $search_val ) ) {
		$args['s'] = $search_val;
	}

	$saved_query   = new WP_Query( $args );
	$display_count = $saved_query->found_posts ?? 0;
}

$dashboard_url = gigneo_dashboard_url( 'saved', 'list' );
?>

<div class="gn-dashboard-section gn-saved-listing-wrapper gn-service-listing-wrapper">
	<div class="gn-head">
		<div class="gn-listing-actions-wrapper">
			<?php if ( count( $saved_tabs ) > 1 ) { ?>
			<ul id="gn-saved-filters" class="gn-filters">
				<?php
				foreach ( $saved_tabs as $saved_key => $saved_tab ) {
					$saved_tab_url = add_query_arg(
						array(
							'tab'  => $saved_key,
							'step' => 1,
						),
						$dashboard_url
					);
					$is_active     = ( $active_tab === $saved_key );
					$count         = intval( $saved_tab['count'] );
					?>
					<li class="gn-filter <?php echo $is_active ? 'gn-active' : ''; ?>">
						<a href="<?php echo esc_url( $saved_tab_url ); ?>" class="gn-title">
							<?php echo esc_html( $saved_tab['label'] ); ?>
							<?php if ( $count > 0 ) { ?>
							<span class="gn-count"><?php echo esc_html( $count ); ?></span>
							<?php } ?>
						</a>
					</li>
				<?php } ?>
			</ul>
			<?php } else { ?>
				<h3 class="gn-title"><?php echo esc_html( $current_tab_info['label'] ); ?></h3>
			<?php } ?>
			<div class="gn-actions">
				<div class="gn-search-wrapper">
					<form class="gn-search" method="get" action="">
						<input type="hidden" name="source" value="saved">
						<input type="hidden" name="ref" value="list">
						<input type="hidden" name="tab" value="<?php echo esc_attr( $active_tab ); ?>">
						<label for="gn-saved-search-input">
							<input id="gn-saved-search-input" type="search" name="search" class="gn-search-input" value="<?php echo esc_attr( $search_val ); ?>" placeholder="<?php echo esc_attr__( 'Search...', 'gigneo' ); ?>" />
						</label>
						<button type="submit" class="gn-search-icon">
							<i class="hi hi-magnifying-glass" aria-hidden="true"></i>
						</button>
					</form>
				</div>
			</div>
		</div>
	</div>
	<?php if ( $display_count ) { ?>
	<div class="gn-body">
			<div class="gn-archive-wrapper">
				<div class="gn-archive-content">
					<div class="gn-archive-main gn-<?php echo esc_attr( $saved_type ); ?>-archive-main gn-saved-grid">
						<?php
						if ( ! empty( $saved_query ) && $saved_query->have_posts() ) {
							while ( $saved_query->have_posts() ) {
								$saved_query->the_post();
								$args = array(
									'p_id'         => $saved_query->post->ID,
									'profile_id'   => $profile_id,
									'profile_type' => $profile_type,
									'saved_items'  => $current_saved_ids,

								);
								gigneo_load_template(
									$current_tab_info['card_path'],
									false,
									$args
								);
							}
							wp_reset_postdata();
						}
						?>
					</div>
					<?php
					if ( ! empty( $saved_query ) ) {
						gigneo_pagination( $saved_query, $current_page, 'gn-saved-pagination' );
					}
					?>
				</div>
			</div>
	</div>
			<?php
	} else {
		gigneo_not_found(
			'saved_list',
			array(
				'title'       => esc_html__( 'No saved items found', 'gigneo' ),
				'description' => esc_html__( 'Try saving a profile, service or job to this list.', 'gigneo' ),
			)
		);
	}
	?>
</div>

