<?php

use Elementor\Icons_Manager;
use Gigneo\Modules;

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

$settings = $this->get_settings_for_display();

$include_by = (array) ( $settings['include_by'] ?? array() );
$exclude_by = (array) ( $settings['exclude_by'] ?? array() );

$query_args = array(
	'post_type'      => 'gigneo_employer',
	'post_status'    => 'publish',
	'posts_per_page' => absint( $settings['posts_per_page'] ?? 9 ),
	'no_found_rows'  => true,
);

$post_not_in = array();
$meta_query  = array( 'relation' => 'AND' );
$tax_query   = array();

// Visibility.
$profile_conditions = gigneo_option( '_gigneo_ts_employer_visibility_conditions' );
$profile_conditions = ! empty( $profile_conditions ) && is_array( $profile_conditions ) ? $profile_conditions : array();

if ( in_array( 'profile_image', $profile_conditions, true ) ) {
	$meta_query[] = array(
		'key'     => '_thumbnail_id',
		'compare' => 'EXISTS',
	);
}

if ( in_array( 'email_verified', $profile_conditions, true ) && in_array( 'email_verification', gigneo_active_modules(), true ) ) {
	$verified_authors         = array_map( 'absint', gigneo_email_verified_users( 'employer' ) );
	$query_args['author__in'] = ! empty( $verified_authors ) ? $verified_authors : array();
}

$meta_term_keys = array(
	'gigneo_facet' => 'carbon_fields:_gigneo_pm_categories',
	'gigneo_skill' => 'carbon_fields:_gigneo_pm_skills',
);

$add_term_filters = static function ( $term_keys, $exclude = false ) use ( &$meta_query, &$tax_query, $meta_term_keys ) {
	foreach ( (array) $term_keys as $term_key ) {
		if ( ! is_string( $term_key ) || ! str_contains( $term_key, ':' ) ) {
			continue;
		}

		list($term_taxonomy, $filter_term_id) = explode( ':', $term_key, 2 );
		$filter_term_id                       = absint( $filter_term_id );
		$filter_term                          = get_term( $filter_term_id, $term_taxonomy );

		if ( ! $filter_term || is_wp_error( $filter_term ) ) {
			continue;
		}

		if ( isset( $meta_term_keys[ $term_taxonomy ] ) ) {
			$meta_query[] = array(
				'key'     => $meta_term_keys[ $term_taxonomy ],
				'value'   => '"' . $filter_term->slug . '"',
				'compare' => $exclude ? 'NOT LIKE' : 'LIKE',
			);
		} elseif ( in_array( $term_taxonomy, array( 'gigneo_language', 'gigneo_license' ), true ) ) {
			$term_query = array(
				'taxonomy' => $term_taxonomy,
				'field'    => 'term_id',
				'terms'    => array( $filter_term_id ),
			);

			if ( $exclude ) {
				$term_query['operator'] = 'NOT IN';
			}

			$tax_query[] = $term_query;
		}
	}
};

if ( in_array( 'term', $include_by, true ) && ! empty( $settings['include_term_ids'] ) ) {
	$add_term_filters( $settings['include_term_ids'] );
}

if ( in_array( 'term', $exclude_by, true ) && ! empty( $settings['exclude_term_ids'] ) ) {
	$add_term_filters( $settings['exclude_term_ids'], true );
}

if ( count( $tax_query ) > 0 ) {
	$tax_query['relation'] = 'AND';
	// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
	$query_args['tax_query'] = $tax_query;
}

if ( count( $meta_query ) > 1 ) {
	// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
	$query_args['meta_query'] = $meta_query;
}

// Include authors.
if ( in_array( 'author', $include_by, true ) && ! empty( $settings['include_authors'] ) ) {
	$include_authors = array_map( 'absint', (array) $settings['include_authors'] );

	if ( ! empty( $include_authors ) ) {
		$query_args['author__in'] = ! empty( $query_args['author__in'] )
			? array_values( array_intersect( $query_args['author__in'], $include_authors ) )
			: $include_authors;

		if ( empty( $query_args['author__in'] ) ) {
			$query_args['author__in'] = array( 0 );
		}
	}
}

// Include employers.
if ( in_array( 'employer', $include_by, true ) && ! empty( $settings['include_employers'] ) ) {
	$query_args['post__in'] = array_map( 'absint', (array) $settings['include_employers'] );
}

// Exclude authors.
if ( in_array( 'author', $exclude_by, true ) && ! empty( $settings['exclude_authors'] ) ) {
	$query_args['author__not_in'] = array_map( 'absint', (array) $settings['exclude_authors'] );
}

// Exclude employers.
if ( in_array( 'employer', $exclude_by, true ) && ! empty( $settings['exclude_employers'] ) ) {
	$post_not_in = array_map( 'absint', (array) $settings['exclude_employers'] );
}

// WP_Query ignores post__not_in when post__in is set, so apply excludes here.
if ( ! empty( $post_not_in ) ) {
	if ( ! empty( $query_args['post__in'] ) ) {
		$query_args['post__in'] = array_values( array_diff( $query_args['post__in'], $post_not_in ) );

		if ( empty( $query_args['post__in'] ) ) {
			$query_args['post__in'] = array( 0 );
		}
	} else {
		// phpcs:ignore WordPressVIPMinimum.Performance.WPQueryParams.PostNotIn_post__not_in -- Exclude user-selected employers from Elementor widget query.
		$query_args['post__not_in'] = $post_not_in;
	}
}

// Order.
$sort_by    = $settings['orderby'] ?? 'date';
$sort_order = $settings['order'] ?? 'DESC';

switch ( $sort_by ) {
	case 'title':
	case 'menu_order':
		$query_args['orderby'] = $sort_by;
		$query_args['order']   = $sort_order;
		break;
	case 'rand':
		$query_args['orderby'] = 'rand';
		break;
	case 'recommended':
		// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
		$query_args['meta_key'] = '_gigneo_pm_orders_completed';
		$query_args['orderby']  = 'meta_value_num';
		$query_args['order']    = $sort_order;
		break;
	case 'top_rated':
		// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
		$query_args['meta_key'] = '_gigneo_pm_average_rating';
		$query_args['orderby']  = 'meta_value_num';
		$query_args['order']    = $sort_order;
		break;
	default:
		$query_args['orderby'] = 'date';
		$query_args['order']   = $sort_order;
		break;
}

$query_args = apply_filters( 'gigneo_elementor_employer_carousel_query_args', $query_args, $settings, $this );

$employer_query     = new WP_Query( $query_args );
$active_profile_id  = gigneo_active_profile_id();
$country_state_list = gigneo_countries_with_states( 'active' );
$saved_items        = gigneo_post_meta( $active_profile_id, '_gigneo_pm_saved_employer' );
$saved_items        = ! empty( $saved_items ) && is_array( $saved_items ) ? array_map( 'absint', $saved_items ) : array();
?>
<div class="gn-employers-carousel-main-wrapper">
	<div class="gn-ele-employer-carousel swiper gn-swiper-body">
		<div class="swiper-wrapper">
			<?php if ( $employer_query->have_posts() ) : ?>
				<?php
				while ( $employer_query->have_posts() ) :
					$employer_query->the_post();

					$employer_id    = get_the_ID();
					$name           = gigneo_profile_name( $employer_id );
					$profile_url    = get_permalink( $employer_id );
					$cover_image_id = gigneo_post_meta( $employer_id, '_gigneo_pm_cover_image' );
					$tagline        = gigneo_post_meta( $employer_id, '_gigneo_pm_tagline' );
					$city_slug      = gigneo_post_meta( $employer_id, '_gigneo_pm_city' );
					$country_state  = gigneo_post_meta( $employer_id, '_gigneo_pm_country_state' );
					$average_rating = gigneo_profile_rating( $employer_id, 'average' );
					$rating_count   = gigneo_profile_rating( $employer_id );
					$total_spent    = gigneo_profile_stat( 'total_spending', $employer_id );
					$success_rate   = gigneo_profile_stat( 'success_rate', $employer_id );
					$total_orders   = gigneo_profile_stat( 'total_orders_count', $employer_id );
					$is_saved       = in_array( $employer_id, $saved_items, true );
					$total_spent    = $total_spent['lifetime'] ?? 0;
					$success_rate   = $success_rate['lifetime'] ?? 0;
					$total_orders   = $total_orders['lifetime'] ?? 0;
					$city_term      = ! empty( $city_slug ) ? get_term_by( 'slug', $city_slug, 'gigneo_city' ) : false;
					$city_name      = $city_term && ! is_wp_error( $city_term ) ? $city_term->name : '';

					$location_label = implode(
						', ',
						array_filter(
							array(
								$city_name,
								$country_state_list[ $country_state ] ?? '',
							)
						)
					);
					?>
					<div class="swiper-slide gn-employer-card-item">
						<div class="gn-employer-card gn-employer-card-layout-1"
							data-item-id="<?php echo esc_attr( $employer_id ); ?>">
							<div class="gn-head">
								<div class="gn-cover-wrapper">
									<figure class="gn-cover">
										<?php gigneo_attachment_image_src( $cover_image_id, 'large', 'cover' ); ?>
									</figure>
									<?php if ( 'yes' === $settings['show_save_button'] ) { ?>
										<button
											class="gn-save-btn gn-btn gn-<?php echo esc_attr( $is_saved ? 'saved' : 'unsaved' ); ?>"
											data-gn-id="<?php echo esc_attr( $employer_id ); ?>" data-gn-type="employer"
											aria-label="<?php esc_attr_e( 'Save', 'gigneo' ); ?>">
											<?php gigneo_saved_icon( true ); ?>
										</button>
									<?php } ?>
								</div>
							</div>
							<div class="gn-body">
								<figure
									class="gn-avatar gn-<?php echo esc_attr( gigneo_online_status( $employer_id ) ? 'online' : 'offline' ); ?>">
									<img src="<?php echo esc_url( gigneo_profile_avatar_url( $employer_id, 'employer' ) ); ?>"
										alt="<?php echo esc_attr( $name ); ?>">
								</figure>
								<div class="gn-info-wrapper">
									<div class="gn-name-wrapper">
										<a href="<?php echo esc_url( $profile_url ); ?>" class="gn-name">
											<?php echo esc_html( $name ); ?>
										</a>
										<?php gigneo_verification_badge( $employer_id, true ); ?>
										<?php if ( 'yes' === $settings['show_rating'] && $average_rating > 0 ) : ?>
											<span class="gn-rating">
												<i class="hi hi-star-alt" aria-hidden="true"></i>
												<?php echo esc_html( number_format( $average_rating, 1 ) ); ?>
												<span class="gn-count">
													(<?php echo esc_html( $rating_count ); ?>)
												</span>
											</span>
										<?php endif; ?>
									</div>
									<?php if ( 'yes' === $settings['show_location'] && ! empty( $location_label ) ) : ?>
										<p class="gn-location">
											<i class="hi hi-map-pin" aria-hidden="true"></i>
											<?php echo esc_html( $location_label ); ?>
										</p>
									<?php endif; ?>
									<?php if ( 'yes' === $settings['show_tagline'] && ! empty( $tagline ) ) : ?>
										<p class="gn-description gn-two-line-ellipsis">
											<?php echo esc_html( $tagline ); ?>
										</p>
									<?php endif; ?>
								</div>
								<?php if ( 'yes' === $settings['show_stats'] ) { ?>
									<div class="gn-stats-wrapper">
										<div class="gn-stat">
											<span class="gn-value">
												<?php echo esc_html( $total_orders ); ?>
											</span>
											<span class="gn-label">
												<?php esc_html_e( 'Orders', 'gigneo' ); ?>
											</span>
										</div>
										<div class="gn-stat">
											<span class="gn-value">
												<?php echo esc_html( gigneo_price_format( $total_spent, true ) ); ?>
											</span>
											<span class="gn-label">
												<?php esc_html_e( 'Spent', 'gigneo' ); ?>
											</span>
										</div>
										<div class="gn-stat">
											<span class="gn-value">
												<?php echo esc_html( $success_rate ); ?>%
											</span>
											<span class="gn-label">
												<?php esc_html_e( 'Success rate', 'gigneo' ); ?>
											</span>
										</div>
									</div>
								<?php } ?>
							</div>
							<?php if ( 'yes' === $settings['show_view_profile'] ) { ?>
								<div class="gn-footer">
									<div class="gn-actions">
										<a href="<?php echo esc_url( $profile_url ); ?>"
											class="gn-view-profile gn-btn gn-btn-outline-grey gn-btn-md">
											<?php esc_html_e( 'View profile', 'gigneo' ); ?>
											<i class="hi hi-arrow-up-right" aria-hidden="true"></i>
										</a>
									</div>
								</div>
							<?php } ?>
						</div>
					</div>
				<?php endwhile; ?>
				<?php wp_reset_postdata(); ?>
			<?php endif; ?>
		</div>
	</div>
	<div class="gn-swiper-arrows">
		<?php
		if ( 'yes' === ( $settings['arrows'] ?? '' ) ) {
			?>
			<button type="button" class="gn-swiper-arrow gn-swiper-arrow-prev">
				<?php Icons_Manager::render_icon( $settings['arrow_prev'], array( 'aria-hidden' => 'true' ) ); ?>
			</button>
			<button type="button" class="gn-swiper-arrow gn-swiper-arrow-next">
				<?php Icons_Manager::render_icon( $settings['arrow_next'], array( 'aria-hidden' => 'true' ) ); ?>
			</button>
			<?php
		}
		if ( 'yes' === ( $settings['bullets'] ?? '' ) ) {
			?>
			<div class="gn-swiper-bullets"></div>
			<?php
		}
		?>
	</div>
</div>