<?php
use Gigneo\Modules;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Search/filter parameters only.
$args = ! empty( $gn_params ) ? $gn_params : $_GET;

$active_profile_id   = gigneo_active_profile_id();
$active_profile_type = gigneo_profile_type( $active_profile_id );
$platform_type       = gigneo_profile_type();

$options  = get_query_var( 'gigneo_shortcode_options', array() );

$search_val       = ! empty( $args['search'] ) ? sanitize_text_field( $args['search'] ) : '';
$location         = ! empty( $args['location'] ) ? sanitize_text_field( $args['location'] ) : '';
$category         = ! empty( $args['category'] ) ? sanitize_text_field( $args['category'] ) : '';
$sub_category     = ! empty( $args['subcategory'] ) ? sanitize_text_field( $args['subcategory'] ) : '';
$specific_types   = ! empty( $args['specific_types'] ) ? array_map( 'sanitize_text_field', (array) $args['specific_types'] ) : array();
$skills           = ! empty( $args['skills'] ) ? array_map( 'sanitize_text_field', (array) $args['skills'] ) : array();
$budget_min       = ! empty( $args['budget_min'] ) && '' !== $args['budget_min'] ? floatval( $args['budget_min'] ) : '';
$budget_max       = ! empty( $args['budget_max'] ) && '' !== $args['budget_max'] ? floatval( $args['budget_max'] ) : '';
$job_mode         = ! empty( $args['mode'] ) ? sanitize_text_field( $args['mode'] ) : '';
$experience_level = ! empty( $args['experience_level'] ) ? sanitize_text_field( $args['experience_level'] ) : '';
$sort             = ! empty( $args['sort'] ) ? sanitize_text_field( $args['sort'] ) : 'newest';
$featured         = ! empty( $args['featured'] ) ? sanitize_text_field( $args['featured'] ) : false;
$verified         = ! empty( $args['verified'] ) ? sanitize_text_field( $args['verified'] ) : false;
$current_page     = ! empty( $args['step'] ) ? max( 1, absint( $args['step'] ) ) : 1;

$posts_per_page     = gigneo_option( '_gigneo_ts_jobs_per_page', 9 );
$country_state_list = gigneo_countries_with_states( 'active' );
$saved_items        = gigneo_post_meta( $active_profile_id, '_gigneo_pm_saved_job' );

$is_map_active  = false;

$posts_per_page = ! empty( $options['per_page'] ) ? absint( $options['per_page'] ) : $posts_per_page;

// Query args.
$job_args = array(
	'post_type'      => 'gigneo_job',
	'posts_per_page' => $posts_per_page,
	'paged'          => $current_page,
	's'              => $search_val,
	'post_status'    => 'publish',
);

// Tax query
$tax_query = array( 'relation' => 'AND' );

if ( ! empty( $category ) ) {
	$tax_query[] = array(
		'taxonomy' => 'gigneo_facet',
		'field'    => 'slug',
		'terms'    => $category,
	);
}

if ( ! empty( $sub_category ) ) {
	$tax_query[] = array(
		'taxonomy' => 'gigneo_facet',
		'field'    => 'slug',
		'terms'    => $sub_category,
	);
}

if ( ! empty( $specific_types ) ) {
	$tax_query[] = array(
		'taxonomy' => 'gigneo_facet',
		'field'    => 'slug',
		'terms'    => $specific_types,
		'operator' => 'IN',
	);
}

if ( ! empty( $skills ) ) {
	$tax_query[] = array(
		'taxonomy' => 'gigneo_skill',
		'field'    => 'slug',
		'terms'    => $skills,
		'operator' => 'IN',
	);
}

if ( count( $tax_query ) > 1 ) {
	// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
	$job_args['tax_query'] = $tax_query;
}
// Meta query.
$meta_query = array( 'relation' => 'AND' );

// Location (meta-based, non-map).
if ( $location ) {
	if ( strpos( $location, ':' ) !== false ) {
		$meta_query[] = array(
			'key'     => '_gigneo_pm_country_state',
			'value'   => $location,
			'compare' => '=',
		);
	} else {
		$meta_query[] = array(
			'relation' => 'OR',
			array(
				'key'     => '_gigneo_pm_country_state',
				'value'   => $location . ':',
				'compare' => 'LIKE',
			),
			array(
				'key'     => '_gigneo_pm_city',
				'value'   => $location,
				'compare' => '=',
			),
		);
	}
}

// Budget.
if ( '' !== $budget_min || '' !== $budget_max ) {

	$rate_query = array(
		'key'  => '_gigneo_pm_price',
		'type' => 'NUMERIC',
	);

	if ( '' !== $budget_min && '' !== $budget_max ) {

		$rate_query['value']   = array( $budget_min, $budget_max );
		$rate_query['compare'] = 'BETWEEN';

	} elseif ( '' !== $budget_min ) {

		$rate_query['value']   = $budget_min;
		$rate_query['compare'] = '>=';

	} else {

		$rate_query['value']   = $budget_max;
		$rate_query['compare'] = '<=';
	}

	$meta_query[] = $rate_query;
}

// Mode.
if ( ! empty( $job_mode ) ) {
	$meta_query[] = array(
		'key'     => '_gigneo_pm_type',
		'value'   => $job_mode,
		'compare' => '=',
	);
}

// Experience Level.
if ( ! empty( $experience_level ) ) {
	$meta_query[] = array(
		'key'     => '_gigneo_pm_experience_level',
		'value'   => $experience_level,
		'compare' => '=',
	);
}

// Featured.
if ( $featured ) {
	$meta_query[] = array(
		'key'     => '_gigneo_pm_featured',
		'value'   => true,
		'compare' => '=',
	);
}

//Verified
if ( ! empty( $verified ) ) {
	$job_args['author__in'] = gigneo_verified_users( 'employer' );
}

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

// Sorting.
switch ( $sort ) {
	case 'newest':
		// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
		$job_args['orderby'] = 'date';
		$job_args['order']   = 'DESC';
		break;
	case 'oldest':
		// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
		$job_args['orderby'] = 'date';
		$job_args['order']   = 'ASC';
		break;
	case 'rate_low_to_high':
		// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
		$job_args['meta_key'] = '_gigneo_pm_price';
		$job_args['orderby']  = 'meta_value_num';
		$job_args['order']    = 'ASC';
		break;
	case 'rate_high_to_low':
		// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
		$job_args['meta_key'] = '_gigneo_pm_price';
		$job_args['orderby']  = 'meta_value_num';
		$job_args['order']    = 'DESC';
		break;
}

$job_query   = new WP_Query( $job_args );
$filter_args = array(
	'search'           => $search_val,
	'location'         => $location,
	'category'         => $category,
	'subcategory'      => $sub_category,
	'specific_types'   => $specific_types,
	'skills'           => $skills,
	'budget_min'       => $budget_min,
	'budget_max'       => $budget_max,
	'job_mode'         => $job_mode,
	'experience_level' => $experience_level,
	'sort'             => $sort,
	'featured'         => $featured,
	'verified'         => $verified,
	'found_posts'      => $job_query->found_posts ?? 0,
);

?>
<div class="gn-archive-wrapper gn-job-archive-wrapper gn-job-archive-layout-1"
	data-archive-type="job" data-ajax-action="gigneo_filter_jobs" data-map-id="gn-job-archive-map"
	data-shortcode-options="<?php echo esc_attr( wp_json_encode( $options ) ); ?>">
	<?php gigneo_load_template( 'archive/job/parts/filter-layout-1', false, $filter_args ); ?>
	<div class="gn-archive-content gn-job-archive-content">
		<div class="gn-archive-content-inner">
			<div class="gn-archive-main gn-job-archive-main">
				<?php
				if ( $job_query->have_posts() ) {
					while ( $job_query->have_posts() ) {
						$job_query->the_post();
						$j_id = get_the_ID();

						$item_args = array(
							'job_id'             => $j_id,
							'profile_id'         => $active_profile_id,
							'profile_type'       => $active_profile_type,
							'country_state_list' => $country_state_list,
							'saved_items'        => $saved_items,
						);
						gigneo_load_template( 'archive/job/parts/card-layout-1', false, $item_args );
					}
				} else {
					gigneo_not_found( 'job_archive' );
				}
				?>
			</div>
		</div>
		<?php
		if ( $job_query->have_posts() ) {
			gigneo_pagination( $job_query, $current_page, 'gn-pagination-wrapper' );
			wp_reset_postdata();
		}
		?>
	</div>
</div>