<?php

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_job',
	'post_status'    => 'publish',
	'posts_per_page' => absint( $settings['posts_per_page'] ?? 9 ),
	'no_found_rows'  => true,
);

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

$add_term_filters = static function ( $term_keys, $exclude = false ) use ( &$tax_query ) {
	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 ) || ! in_array( $term_taxonomy, array( 'gigneo_facet', 'gigneo_skill' ), true ) ) {
			continue;
		}

		$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 ) > 1 ) {
	// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
	$query_args['tax_query'] = $tax_query;
}

// Include authors.
if ( in_array( 'author', $include_by, true ) && ! empty( $settings['include_authors'] ) ) {
	$include_authors = $this->resolve_query_author_ids( $settings['include_authors'] );

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

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

// Exclude authors.
if ( in_array( 'author', $exclude_by, true ) && ! empty( $settings['exclude_authors'] ) ) {
	$exclude_authors = $this->resolve_query_author_ids( $settings['exclude_authors'] );

	if ( ! empty( $exclude_authors ) ) {
		$query_args['author__not_in'] = $exclude_authors;
	}
}

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

// 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 jobs 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 'budget':
		// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
		$query_args['meta_key'] = '_gigneo_pm_price';
		$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_job_grid_query_args', $query_args, $settings, $this );

$job_query          = new WP_Query( $query_args );
$active_profile_id  = gigneo_active_profile_id();
$saved_items        = gigneo_post_meta( $active_profile_id, '_gigneo_pm_saved_job' );
$saved_items        = ! empty( $saved_items ) && is_array( $saved_items ) ? array_map( 'absint', $saved_items ) : array();
$country_state_list = gigneo_countries_with_states( 'active' );
$enable_filters     = $settings['enable_filters'] ?? 'no';
$filter_all_text    = ucfirst( mb_strtolower( $settings['filter_all_text'] ?? esc_html__( 'All', 'gigneo' ) ) );
$category_filters   = array();

if ( 'yes' === $enable_filters && ! empty( $job_query->posts ) ) {
	foreach ( $job_query->posts as $post_obj ) {
		$gn_terms = get_the_terms( $post_obj->ID, 'gigneo_facet' );

		if ( $gn_terms && ! is_wp_error( $gn_terms ) ) {
			foreach ( $gn_terms as $gn_term ) {
				if ( 0 !== (int) $gn_term->parent ) {
					continue;
				}

				$category_filters[ $gn_term->slug ] = ucfirst( mb_strtolower( $gn_term->name ) );
			}
		}
	}
}
?>
<div class="gn-jobs-grid-main-wrapper">
	<?php if ( 'yes' === $enable_filters && ! empty( $category_filters ) ) { ?>
		<div class="gn-grid-filters gn-jobs-grid-filters">
			<ul class="gn-jobs-grid-filter-list">
				<li class="gn-jobs-grid-filter-item active"
					data-filter="*"><?php echo esc_html( $filter_all_text ); ?></li>
				<?php foreach ( $category_filters as $f_slug => $f_name ) { ?>
					<li class="gn-jobs-grid-filter-item"
						data-filter=".cat-<?php echo esc_attr( $f_slug ); ?>"><?php echo esc_html( $f_name ); ?></li>
				<?php } ?>
			</ul>
		</div>
	<?php } ?>
	<div class="gn-ele-job-grid-wrapper">
		<?php
		if ( $job_query->have_posts() ) {
			while ( $job_query->have_posts() ) {
				$job_query->the_post();
				$job_id = get_the_ID();

				$job_title     = get_the_title( $job_id );
				$author_id     = get_post_field( 'post_author', $job_id );
				$price         = gigneo_post_meta( $job_id, '_gigneo_pm_price' );
				$description   = gigneo_post_meta( $job_id, '_gigneo_pm_description' );
				$duration      = gigneo_post_meta( $job_id, '_gigneo_pm_duration' );
				$duration_type = gigneo_post_meta( $job_id, '_gigneo_pm_duration_type' );
				$work_mode     = gigneo_post_meta( $job_id, '_gigneo_pm_type' );
				$is_featured   = gigneo_post_meta( $job_id, '_gigneo_pm_featured' );

				$profile_id     = gigneo_profile_id( $author_id, 'employer' );
				$avatar_id      = get_post_thumbnail_id( $profile_id ) ?? 0;
				$online_status  = gigneo_online_status( $profile_id );
				$average_rating = gigneo_profile_rating( $profile_id, 'average' );
				$reviews        = gigneo_profile_rating( $profile_id );

				// Location
				$country_state_raw = gigneo_post_meta( $job_id, '_gigneo_pm_country_state' );
				$city              = gigneo_post_meta( $job_id, '_gigneo_pm_city' );
				$country_label     = ! empty( $country_state_list[ $country_state_raw ] ) ? $country_state_list[ $country_state_raw ] : '';
				$city_term         = ! empty( $city ) ? get_term_by( 'slug', $city, 'gigneo_city' ) : false;
				$location_label    = implode( ', ', array_filter( array( $city_term->name ?? '', $country_label ?? '' ) ) );

				$gn_terms       = get_the_terms( $job_id, 'gigneo_facet' );
				$cat_class_list = array();

				if ( $gn_terms && ! is_wp_error( $gn_terms ) ) {
					foreach ( $gn_terms as $gn_term ) {
						$cat_class_list[] = 'cat-' . $gn_term->slug;
					}
				}
				$cat_class_str = ! empty( $cat_class_list ) ? ' ' . implode( ' ', $cat_class_list ) : '';

				// Save state
				$active_class = ( ! empty( $saved_items ) && in_array( $job_id, $saved_items, true ) ) ? 'gn-saved' : '';
				?>
				<div class="gn-job-card-item <?php echo esc_attr( $cat_class_str ); ?>">
					<div class="gn-job-card gn-job-card-layout-1" data-item-id="<?php echo intval( $job_id ); ?>">
					<div class="gn-head">
                        <div class="gn-heading-wrapper">
								<h2 class="gn-title">
									<a href="<?php echo esc_url( get_the_permalink( $job_id ) ); ?>">
										<?php echo esc_html( $job_title ); ?>
										<?php
										if ( $is_featured ) {
											?>
											<span class="gn-status-tag-fill gn-warning">
											<?php echo esc_html__( 'Featured', 'gigneo' ); ?>
											</span>
											<?php
										}
										?>
									</a>
								</h2>
								<span class="gn-budget">
					<?php
					echo esc_html( gigneo_price_format( $price, true ) );
					?>
				</span>
				</div>
				        <div class="gn-info-wrapper">
								<?php if ( 'yes' === $settings['show_meta'] ) { ?>
									<div class="gn-meta">
										<?php if ( $work_mode ) { ?>
											<div class="gn-mode">
												<i class="hi hi-map-pin" aria-hidden="true"></i>
												<?php echo esc_html( ucfirst( $work_mode ) ); ?>
											</div>
										<?php } ?>
										<?php
										if ( ! empty( $duration ) && ! empty( $duration_type ) ) {
											?>
											<div class="gn-dueration">
												<i class="hi hi-clock" aria-hidden="true"></i>
												<?php echo esc_html( gigneo_delivery_time( $duration, $duration_type ) ); ?>
											</div>
										<?php } ?>
										<?php if ( ! empty( $location_label ) ) { ?>
											<div class="gn-location">
												<i class="hi hi-map" aria-hidden="true"></i>
												<?php echo esc_html( $location_label ); ?>
											</div>
										<?php } ?>
									</div>
								<?php } ?>
							</div>
				    </div>
                    <div class="gn-body">
                        <?php if ( 'yes' === $settings['show_description'] ) { ?>
                            <p class="gn-description">
                                <?php
                                echo wp_kses( wp_trim_words( $description, 25, '...' ), gigneo_allowed_html_tags() );
                                ?>
                            </p>
                        <?php } ?>
                    </div>
                     <div class="gn-footer">
                        <div class="gn-profile">
                            <figure class="gn-avatar gn-<?php echo esc_attr( $online_status ? 'online' : 'offline' ); ?>">
                                <?php gigneo_attachment_image_src( $avatar_id, 'thumbnail', 'profile', '', '', $profile_id ); ?>
                            </figure>
                            <div class="gn-info">
                                <div class="gn-name-wrapper">
                                    <a href="<?php echo esc_url( get_the_permalink( $profile_id ) ); ?>" target="_blank"
                                        class="gn-name"><?php echo esc_html( gigneo_profile_name( $profile_id ) ); ?>
                                    </a>
                                    <?php gigneo_verification_badge( $profile_id, true ); ?>
                                </div>
                                <?php if ( 'yes' === $settings['show_rating'] ) { ?>
                                    <ul class="gn-meta">
                                        <li class="gn-ratings">
                                            <i class="hi hi-star-alt" aria-hidden="true"></i>
                                            <?php echo esc_html( $average_rating ?? 0 ); ?>
                                            <span class="gn-count">(<?php echo esc_html( $reviews ?? 0 ); ?>)</span>
                                        </li>
                                    </ul>
                                <?php } ?>
                            </div>
                        </div>
                        <div class="gn-actions">
                            <a href="<?php echo esc_url( get_the_permalink( $job_id ) ); ?>"
                                class="gn-btn gn-btn-outline-grey gn-btn-sm">
                                <i class="hi hi-eye" aria-hidden="true"></i>
                                <?php esc_html_e( 'View job', 'gigneo' ); ?>
                            </a>
                            <?php if ( 'yes' === $settings['show_save_button'] ) { ?>
                                <button class="gn-save-btn gn-btn gn-btn-outline-grey gn-btn-sm <?php echo esc_attr( $active_class ); ?>"
                                        data-gn-id="<?php echo intval( $job_id ); ?>"
                                        data-gn-type="<?php echo esc_attr( 'job' ); ?>"
                                        aria-label="<?php esc_attr_e( 'Save', 'gigneo' ); ?>">
                                    <?php gigneo_saved_icon( true ); ?>
                                </button>
                            <?php } ?>
                        </div>
                    </div>
                    </div>
				</div>
				<?php
			}
			wp_reset_postdata();
		}
		?>
	</div>
</div>
