<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
$platform_type = gigneo_option( '_gigneo_ts_platform_type', 'both' );

if ( 'jobs' === $platform_type ) {
	return;
}

// 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 );

$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();
$min_price      = ! empty( $args['min_price'] ) && '' !== $args['min_price'] ? floatval( $args['min_price'] ) : '';
$max_price      = ! empty( $args['max_price'] ) && '' !== $args['max_price'] ? floatval( $args['max_price'] ) : '';
$types          = ! empty( $args['type'] ) ? array_map( 'sanitize_text_field', (array) $args['type'] ) : array();
$delivery       = ! empty( $args['delivery'] ) ? array_map( 'sanitize_text_field', (array) $args['delivery'] ) : array();
$sort           = ! empty( $args['sort'] ) ? sanitize_text_field( $args['sort'] ) : 'recommended';
$current_page   = ! empty( $args['step'] ) ? max( 1, absint( $args['step'] ) ) : 1;
$featured       = ! empty( $args['featured'] ) ? sanitize_text_field( $args['featured'] ) : false;
$verified       = ! empty( $args['verified'] ) ? sanitize_text_field( $args['verified'] ) : false;
$rating         = ! empty( $args['rating'] ) && '' !== $args['rating'] ? absint( $args['rating'] ) : '';

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

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

// Query args.
$service_args = array(
	'post_type'      => 'gigneo_service',
	'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:disable WordPress.DB.SlowDBQuery.slow_db_query_tax_query
	$service_args['tax_query'] = $tax_query;
	// phpcs:enable WordPress.DB.SlowDBQuery.slow_db_query_tax_query
}

// Meta query
$meta_query = array( 'relation' => 'AND' );

if ( ! empty( $location ) ) {
	$meta_query[] = array(
		'key'     => 'carbon_fields:_gigneo_pm_locations',
		'value'   => '"' . $location . '"',
		'compare' => 'LIKE',
	);
}

if ( '' !== $min_price && floatval( $min_price ) > 0 ) {
	$meta_query[] = array(
		'key'     => '_gigneo_pm_price_plan_one_price',
		'value'   => $min_price,
		'compare' => '>=',
		'type'    => 'NUMERIC',
	);
}

if ( '' !== $max_price && floatval( $max_price ) < 10000 ) {
	$meta_query[] = array(
		'key'     => '_gigneo_pm_price_plan_one_price',
		'value'   => $max_price,
		'compare' => '<=',
		'type'    => 'NUMERIC',
	);
}

if ( ! empty( $types ) ) {
	$meta_query[] = array(
		'key'     => '_gigneo_pm_type',
		'value'   => $types,
		'compare' => 'IN',
	);
}

if ( ! empty( $delivery ) ) {
	$meta_query[] = array(
		'relation' => 'OR',
		array(
			'key'     => '_gigneo_pm_delivery_type',
			'value'   => $delivery,
			'compare' => 'IN',
		),
		array(
			'key'     => '_gigneo_pm_delivery_type',
			'value'   => 'both',
			'compare' => '=',
		),
	);
}

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

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

if ( ! empty( $rating ) ) {
	$meta_query[] = array(
		'key'     => '_gigneo_pm_average_rating',
		'value'   => $rating,
		'compare' => '>=',
		'type'    => 'NUMERIC',
	);
}

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

// Sorting
switch ( $sort ) {
	case 'recommended':
		// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
		$service_args['meta_key'] = '_gigneo_pm_total_completed_order';
		$service_args['orderby']  = 'meta_value_num';
		$service_args['order']    = 'DESC';
		break;
	case 'top_rated':
		// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
		$service_args['meta_key'] = '_gigneo_pm_average_rating';
		$service_args['orderby']  = 'meta_value_num';
		$service_args['order']    = 'DESC';
		break;
	case 'price_low_to_high':
		// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
		$service_args['meta_key'] = '_gigneo_pm_price_plan_one_price';
		$service_args['orderby']  = 'meta_value_num';
		$service_args['order']    = 'ASC';
		break;
	case 'price_high_to_low':
		// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
		$service_args['meta_key'] = '_gigneo_pm_price_plan_one_price';
		$service_args['orderby']  = 'meta_value_num';
		$service_args['order']    = 'DESC';
		break;
}

$service_query = new WP_Query( $service_args );

$filter_args = array(
	'search'         => $search_val,
	'location'       => $location,
	'category'       => $category,
	'subcategory'    => $sub_category,
	'specific_types' => $specific_types,
	'skills'         => $skills,
	'min_price'      => $min_price,
	'max_price'      => $max_price,
	'types'          => $types,
	'delivery'       => $delivery,
	'sort'           => $sort,
	'featured'       => $featured,
	'verified'       => $verified,
	'rating'         => $rating,
	'found_posts'    => $service_query->found_posts ?? 0,
);

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

						$item_args = array(
							'service_id'         => $s_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/service/parts/card-layout-1', false, $item_args );
					}
				} else {
					gigneo_not_found( 'service_archive' );
				}
				?>
			</div>
		</div>
		<?php
		if ( $service_query->have_posts() ) {
			gigneo_pagination( $service_query, $current_page, 'gn-pagination-wrapper' );
			wp_reset_postdata();
		}
		?>
	</div>
</div>
