<?php
/**
 * Property Query Handler
 *
 * @package Immowp_Gestion_Immobiliere
 */

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

// Sanitize query parameters (single values only)
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- This is a search/filter form, not a state-changing operation
$immowp_offre_sanitized = '';
if ( isset( $_GET['offre'] ) ) {
	$immowp_offre_sanitized = sanitize_text_field( wp_unslash( $_GET['offre'] ) );
} elseif ( ! empty( $a['offre'] ) ) {
	$immowp_offre_sanitized = sanitize_text_field( $a['offre'] );
}

$immowp_type_sanitized = '';
if ( isset( $_GET['type_bien'] ) ) {
	$immowp_type_sanitized = sanitize_text_field( wp_unslash( $_GET['type_bien'] ) );
} elseif ( ! empty( $a['type'] ) ) {
	$immowp_type_sanitized = sanitize_text_field( $a['type'] );
}

$immowp_localisation_sanitized = '';
if ( isset( $_GET['localisation'] ) ) {
	$immowp_localisation_sanitized = sanitize_text_field( wp_unslash( $_GET['localisation'] ) );
} elseif ( ! empty( $a['localisation'] ) ) {
	$immowp_localisation_sanitized = sanitize_text_field( $a['localisation'] );
}

// Sanitize other attributes from $a (assuming they are single values or already arrays of simple strings if applicable)
$immowp_caracteristiques_sanitized = !empty($a['caracteristiques']) ? array_map('sanitize_text_field', is_array($a['caracteristiques']) ? $a['caracteristiques'] : array_map('trim', explode(',', $a['caracteristiques']))) : array();
$immowp_agences_sanitized = !empty($a['agence']) ? array_map('sanitize_text_field', is_array($a['agence']) ? $a['agence'] : array_map('trim', explode(',', $a['agence']))) : array();
$immowp_agent_sanitized = !empty($a['agent']) ? array_map('sanitize_text_field', is_array($a['agent']) ? $a['agent'] : array_map('trim', explode(',', $a['agent']))) : array();
$immowp_region_sanitized = !empty($a['region']) ? array_map('sanitize_text_field', is_array($a['region']) ? $a['region'] : array_map('trim', explode(',', $a['region']))) : array();
$immowp_departement_sanitized = !empty($a['departement']) ? array_map('sanitize_text_field', is_array($a['departement']) ? $a['departement'] : array_map('trim', explode(',', $a['departement']))) : array();

$immowp_post_key_sanitized = !empty($a['post_key']) ? sanitize_key($a['post_key']) : ''; // sanitize_key for meta keys
$immowp_post_meta_sanitized = !empty($a['post_meta']) ? sanitize_text_field($a['post_meta']) : '';


// Sanitize remaining text inputs from GET or $a
$immowp_reference_sanitized = isset( $_GET['reference'] ) ? sanitize_text_field( wp_unslash( $_GET['reference'] ) ) : ( ! empty( $a['reference'] ) ? sanitize_text_field( $a['reference'] ) : '' );
// phpcs:enable WordPress.Security.NonceVerification.Recommended

$immowp_localisations = get_categories( 'taxonomy=immowp_localisation&type=immowp_gestion_immo' );
$immowp_offres        = get_categories( 'taxonomy=immowp_offre&type=immowp_gestion_immo' );
$immowp_types         = get_categories( 'taxonomy=immowp_type&type=immowp_gestion_immo' );

$immowp_meta_query = $immowp_tax_query = array();
if ( '' !== $immowp_offre_sanitized ) {
	$immowp_tax_query[] = array(
		'taxonomy' => 'immowp_offre',
		'field'    => 'slug',
		'terms'    => $immowp_offre_sanitized,
	);
}

if ( '' !== $immowp_localisation_sanitized ) {
	$immowp_tax_query[] = array(
		'taxonomy' => 'immowp_localisation',
		'field'    => 'slug',
		'terms'    => $immowp_localisation_sanitized,
	);
}
if ( '' !== $immowp_type_sanitized ) {
	$immowp_tax_query[] = array(
		'taxonomy' => 'immowp_type',
		'field'    => 'slug',
		'terms'    => $immowp_type_sanitized,
	);
}
if ( $immowp_caracteristiques_sanitized ) {
	$immowp_tax_query[] = array(
		'taxonomy' => 'immowp_caracteristiques',
		'field'    => 'slug',
		'terms'    => $immowp_caracteristiques_sanitized,
	);
}
if ( $immowp_post_key_sanitized && $immowp_post_meta_sanitized ) { // Use sanitized versions
	$immowp_meta_query[] = array(
		'key'     => $immowp_post_key_sanitized, // Use sanitized version
		'value'   => $immowp_post_meta_sanitized, // Use sanitized version
		'compare' => '=', // Hardcoded, safe
	);
}
if ( $immowp_reference_sanitized ) { // Use sanitized version
	$immowp_meta_query[] = array(
		'key'   => 'affNum', // Hardcoded, safe
		'value' => $immowp_reference_sanitized, // Use sanitized version
	);
}

$immowp_sort_sanitized = isset($_GET['sort']) ? sanitize_text_field(wp_unslash($_GET['sort'])) : (!empty($a['sort']) ? sanitize_text_field($a['sort']) : ''); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This is a search/filter form, not a state-changing operation

// Initialize final sorting parameters with plugin defaults or WordPress defaults
$immowp_orderby_final = array('date' => 'DESC'); // Default sort: newest first
$immowp_order_final = 'DESC';
$immowp_meta_key_final = '';

$immowp_default_sort_option = get_option('immowp_archive_order');

if (!empty($immowp_sort_sanitized)) { // User has chosen a sort option
    $immowp_sort_parts = explode('-', $immowp_sort_sanitized, 2);
    $immowp_potential_orderby_key = sanitize_key($immowp_sort_parts[0]);
    $immowp_potential_order = isset($immowp_sort_parts[1]) ? strtoupper(sanitize_key($immowp_sort_parts[1])) : 'ASC';

    // Whitelist of allowed keys for sorting and their types
    $immowp_allowed_orderby_options = array(
        'prix'             => 'meta_value_num',
        'loyer'            => 'meta_value_num', // Assuming loyer is also numeric for sorting
        'surfaceHabitable' => 'meta_value_num',
        'date'             => 'date', // Sort by post date
    );
    $immowp_allowed_orders = array('ASC', 'DESC');

    if (array_key_exists($immowp_potential_orderby_key, $immowp_allowed_orderby_options) && in_array($immowp_potential_order, $immowp_allowed_orders)) {
        $immowp_orderby_final = $immowp_allowed_orderby_options[$immowp_potential_orderby_key];
        $immowp_order_final = $immowp_potential_order;
        if ($immowp_orderby_final !== 'date') { // 'date' doesn't need a meta_key
            $immowp_meta_key_final = $immowp_potential_orderby_key;
        } else {
            $immowp_meta_key_final = ''; // Clear meta key if sorting by date
        }
    }
    // If the $immowp_sort_sanitized is not in allowlist, it falls back to defaults defined below or WP default.
} elseif ($immowp_default_sort_option == 'rand') {
    $immowp_orderby_final = 'rand';
    $immowp_order_final = ''; // RAND order does not use ASC/DESC typically
    $immowp_meta_key_final = '';
} elseif ($immowp_default_sort_option == 'price') { // Assuming 'price' from settings means price ascending
    $immowp_orderby_final = 'meta_value_num';
    $immowp_meta_key_final = 'prix'; // Consider if 'loyer' should also be a factor or a combined field
    $immowp_order_final = 'ASC';
} elseif ($immowp_default_sort_option == 'new') { // Default from settings: newest first
    $immowp_orderby_final = 'date';
    $immowp_order_final = 'DESC';
    $immowp_meta_key_final = '';
}
// If $immowp_orderby_final remains an array (e.g. initial default), WP_Query will handle it.

if ( isset( $a['page'] ) && ! empty( $a['page'] ) ) {
	$immowp_paged = absint($a['page']); // Sanitize page number from shortcode attribute
} else {
	$immowp_paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;
}

$immowp_args  = array(
	'post_type'      => 'immowp_gestion_immo',
	'paged'          => $immowp_paged,
	'posts_per_page' => isset($a['nombre_biens']) ? absint($a['nombre_biens']) : absint(get_option( 'immowp_archive_number' )), // Sanitize posts_per_page
	'tax_query'      => $immowp_tax_query, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query -- multi-taxonomy filtering is a core feature of this search form.
	'meta_query'     => $immowp_meta_query, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- numeric range filters are required for search precision.
	'order'          => $immowp_order_final,
	'orderby'        => $immowp_orderby_final,
	'meta_key'       => $immowp_meta_key_final, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- used only when sorting on numeric meta columns selected by the user.
);

$immowp_query = new WP_Query( $immowp_args );
