<?php

class Facet_Wp_Remote_Data_Neighborhood_Page {

	public const PREFIX_FACET_WP_REMOTE_DATA_PRESELECTED__FACET = 'facet_wp_remote_data_preselected__';

	public function add_facetwp_choices_meta_boxes() {
		if ( ! function_exists( 'FWP' ) ) {
			return;
		}

		$facet_with_choices = $this->get_facets_with_choices();

		if ( empty( $facet_with_choices ) ) return;

		foreach ( $facet_with_choices as $facet ) {
			$facet_name = $facet['name'];
			$facet_type = isset( $facet['type'] ) ? $facet['type'] : 'dropdown';

			if ( ! in_array( $facet_type, ['dropdown', 'fselect', 'radio', 'checkboxes', 'number_range'] ) ) continue;

			if ( Facet_Wp_Remote_Data_Handler::PRICE_RANGE_LINKS_FACET_NAME === $facet_name ) continue;

			$facet_label = ! empty( $facet['label'] ) ? $facet['label'] : ucwords( str_replace( '_', ' ', $facet_name ) );

			add_meta_box(
				"facetwp_meta_{$facet_name}",
				"Preselected {$facet_label}",
				[ $this, 'facet_meta_box_callback' ],
				['page', 'community'],
				'side',
				'default',
				[ 'facet' => $facet ]
			);
		}

		$facets_from_options = ( new Facet_Wp_Remote_Data_Handler() )->get_facets_from_options();

		if ( ! empty( $facets_from_options ) ) {
			$sort_facet = array_filter( $facets_from_options, fn ( $facet ) => 'sort' === $facet['type'] );
			$sort_facet = ! empty( $sort_facet ) ? array_shift( $sort_facet ) : [];
		}

		if ( ! empty( $sort_facet ) ) {
			add_meta_box(
				"facetwp_meta_{$sort_facet['name']}",
				"Preselected {$sort_facet['label']}",
				[ $this, 'facet_sort_meta_box_callback' ],
				['page', 'community'],
				'side',
				'default',
				[ 'facet' => $sort_facet ]
			);
		}
	}

	public function facet_meta_box_callback( $post, $meta_box ) {
		$facet = $meta_box['args']['facet'];
		$facet_name = $facet['name'];
		$facet_choices = $facet['choices'];
		$facet_type = isset( $facet['type'] ) ? $facet['type'] : 'dropdown';

		$selected_value   = get_post_meta( $post->ID, self::PREFIX_FACET_WP_REMOTE_DATA_PRESELECTED__FACET . $facet_name, true );
		$show_preselected = get_post_meta( $post->ID, self::PREFIX_FACET_WP_REMOTE_DATA_PRESELECTED__FACET . $facet_name . '_show', true );

		if ( empty( $facet_choices ) && 'number_range' !== $facet_type ) return;

		switch ( $facet_type ) {
			case 'dropdown':
			case 'fselect':
				echo '<select name="' . esc_attr( $facet_name ) . '" id="' . esc_attr( $facet_name ) . '">';
				echo '<option value="">-- Select --</option>';

				usort( $facet_choices, function( $a, $b ) {
					return strcmp( $a['label'], $b['label'] );
				});

				foreach ( $facet_choices as $choice ) {
					$value = esc_attr( $choice['value'] );
					$label = esc_html( $choice['label'] );

					echo '<option value="' . $value . '" ' . selected( $selected_value, $value, false ) . '>' . $label . '</option>';
				}

				echo '</select>';

				break;

			case 'radio':
				usort( $facet_choices, function( $a, $b ) {
					return strcmp( $a['label'], $b['label'] );
				});

				foreach ( $facet_choices as $choice ) {
					$value = esc_attr( $choice['value'] );
					$label = esc_html( $choice['label'] );

					echo '<label><input type="radio" name="' . esc_attr( $facet_name ) . '" value="' . $value . '" ' . checked( $selected_value, $value, false ) . '> ' . $label . '</label><br>';
				}

				break;

			case 'checkboxes':
				$selected_values = is_array( $selected_value ) ? $selected_value : explode( ',', $selected_value );

				usort( $facet_choices, function( $a, $b ) {
					return strcmp( $a['label'], $b['label'] );
				});

				foreach ( $facet_choices as $choice ) {
					$value = esc_attr( $choice['value'] );
					$label = esc_html( $choice['label'] );

					echo '<label><input type="checkbox" name="' . esc_attr( $facet_name ) . '[]" value="' . $value . '" ' . checked( in_array( $value, $selected_values ), true, false ) . '> ' . $label . '</label><br>';
				}

				break;

			case 'number_range':
				$from_value = is_array( $selected_value ) && isset( $selected_value['from'] ) ? esc_attr( $selected_value['from'] ) : '';
				$to_value = is_array( $selected_value ) && isset( $selected_value['to'] ) ? esc_attr( $selected_value['to'] ) : '';

				echo '<p>';
				echo '<label>From: <input type="text" name="' . esc_attr( $facet_name ) . '[from]" value="' . $from_value . '" style="width:70px;"></label>';
				echo '</p>';
				echo '<p>';
				echo '<label>To: <input type="text" name="' . esc_attr( $facet_name ) . '[to]" value="' . $to_value . '" style="width:70px;"></label>';
				echo '</p>';
				break;

			default:
				echo '<p>Unsupported facet type: ' . esc_html( $facet_type ) . '</p>';

				break;
		}

		// "Show preselected facet" checkbox and description
		echo '<hr style="margin:15px 0;">';
		echo '<p style="margin-top:10px; margin-bottom:5px;">';
		echo '<label>';
		echo '<input type="checkbox" name="' . esc_attr( $facet_name ) . '_show" value="1"' . checked( $show_preselected, '1', false ) . '>';
		echo ' ' . esc_html__( 'Display preselected facet', 'your-textdomain' );
		echo '</label>';
		echo '</p>';

		echo '<p style="margin:0; font-size:12px; color:#666;">' . esc_html( 'Preselected facets are hidden by default. Check this box to show them on the page.' ) . '</p>';

		wp_nonce_field( 'facetwp_remote_data_meta_nonce_action', 'facetwp_remote_data_meta_nonce' );
	}

	public function facet_sort_meta_box_callback( $post, $meta_box ) {
		$facet = $meta_box['args']['facet'];
		$facet_name = $facet['name'];
		$facet_choices = $facet['sort_options'];

		$selected_value = get_post_meta( $post->ID, self::PREFIX_FACET_WP_REMOTE_DATA_PRESELECTED__FACET . $facet_name, true );

		echo '<select name="' . esc_attr( $facet_name ) . '" id="' . esc_attr( $facet_name ) . '">';
		echo '<option value="">-- Select --</option>';

		foreach ( $facet_choices as $choice ) {
			$value = esc_attr( $choice['name'] );
			$label = esc_html( $choice['label'] );

			echo '<option value="' . $value . '" ' . selected( $selected_value, $value, false ) . '>' . $label . '</option>';
		}

		echo '</select>';

		wp_nonce_field( 'facetwp_remote_data_meta_nonce_action', 'facetwp_remote_data_meta_nonce' );
	}

	public function save_custom_post_meta( $post_id ) {
		if (
			! isset( $_POST['facetwp_remote_data_meta_nonce'] )
			|| ! wp_verify_nonce( $_POST['facetwp_remote_data_meta_nonce'], 'facetwp_remote_data_meta_nonce_action' )
		) {
			return;
		}

		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;

		$facets = FWP()->helper->get_facets();

		foreach ( $facets as $facet ) {
			$facet_name = $facet['name'];
			$facet_type = isset( $facet['type'] ) ? $facet['type'] : 'dropdown';

			$meta_key = self::PREFIX_FACET_WP_REMOTE_DATA_PRESELECTED__FACET . $facet_name;
			$meta_key_show = $meta_key . '_show';

			$has_input = isset( $_POST[ $facet_name ] );

			// Sanitize and save or delete the value
			if ( $has_input ) {
				$value = $_POST[ $facet_name ];

				if ( 'checkboxes' === $facet_type ) {
					$sanitized = array_filter( array_map( 'sanitize_text_field', (array) $value ) );

					if ( ! empty( $sanitized ) ) {
						update_post_meta( $post_id, $meta_key, $sanitized );
					} else {
						delete_post_meta( $post_id, $meta_key );
					}
				} elseif ( 'number_range' === $facet_type ) {
					$from = isset( $value['from'] ) ? trim( $value['from'] ) : '';
					$to   = isset( $value['to'] ) ? trim( $value['to'] ) : '';

					if ( $from === '' || $to === '' ) {
						delete_post_meta( $post_id, $meta_key );
					} else {
						update_post_meta( $post_id, $meta_key, [
							'from' => is_numeric( $from ) ? sanitize_text_field( $from ) : '',
							'to'   => is_numeric( $to ) ? sanitize_text_field( $to ) : '',
						] );
					}
				} else {
					$sanitized = sanitize_text_field( $value );

					if ( $sanitized === '' ) {
						delete_post_meta( $post_id, $meta_key );
					} else {
						update_post_meta( $post_id, $meta_key, $sanitized );
					}
				}
			} else {
				// No value sent — delete any existing preselection
				delete_post_meta( $post_id, $meta_key );
			}

			// Save or delete the "show preselected" checkbox
			if ( isset( $_POST[ $facet_name . '_show' ] ) ) {
				update_post_meta( $post_id, $meta_key_show, '1' );
			} else {
				delete_post_meta( $post_id, $meta_key_show );
			}

			// Always clear cached property data after change
			Facet_Wp_Remote_Data_Cache::delete_property_cached_data( $post_id );
		}
	}

	public function redirect_to_facetwp_filtered_url() {
		global $post;

		if ( is_admin() || ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
			return;
		}

		if ( ! is_archive() && ( new Facet_Wp_Remote_Data_Handler )->should_use_main_site_facet_wp_data( $post->ID ) ) {
			if ( ! function_exists( 'FWP' ) || empty( $post ) ) {
				return;
			}

			$facets = FWP()->helper->get_facets();
			if ( empty( $facets ) ) {
				return;
			}

			$current_url = home_url( add_query_arg( [], $_SERVER['REQUEST_URI'] ) );
			wp_parse_str( wp_parse_url( $current_url, PHP_URL_QUERY ), $current_query_args );

			$new_query_args = $current_query_args;
			$preselected_facets = [];

			foreach ( $facets as $facet ) {
				$facet_name = $facet['name'];
				$facet_type = $facet['type'] ?? 'dropdown';

				$meta_key          = self::PREFIX_FACET_WP_REMOTE_DATA_PRESELECTED__FACET . $facet_name;
				$preselected_value = get_post_meta( $post->ID, $meta_key, true );
				$show_preselected  = get_post_meta( $post->ID, $meta_key . '_show', true );

				$query_key     = '_' . $facet_name;
				$current_value = $current_query_args[ $query_key ] ?? '';

				// --- Start user interaction detection logic
				$expected_value = '';
				if ( ( 'checkboxes' === $facet_type || 'number_range' === $facet_type ) && is_array( $preselected_value ) ) {
					if ( 'number_range' === $facet_type ) {
						$from = $preselected_value['from'] ?? '';
						$to   = $preselected_value['to'] ?? '';
						$expected_value = implode( ',', [ $from, $to ] );
					} else {
						$expected_value = implode( ',', $preselected_value );
					}
				} else {
					$expected_value = (string) $preselected_value;
				}

				$normalized_current = (string) $current_value;
				$user_selected = false;

				if ( ( 'checkboxes' === $facet_type || 'number_range' === $facet_type ) && '' !== $normalized_current ) {
					$current_array  = explode( ',', $normalized_current );
					$expected_array = explode( ',', $expected_value );
					sort( $current_array );
					sort( $expected_array );
					if ( $current_array !== $expected_array ) {
						$user_selected = true;
					}
				} else {
					if ( $normalized_current !== '' && $normalized_current !== $expected_value ) {
						$user_selected = true;
					}
				}
				// --- End user interaction detection

				// Inject global-level "Show Only These Property Types" if not set anywhere
				if (
					'property_type' === $facet_name &&
					empty( $preselected_value ) &&
					! $user_selected &&
					! array_key_exists( '_property_type', $current_query_args )
				) {
					$allowed_types = get_option( 'facetwp_remote_data_only_show_property_types', [] );
					if ( ! empty( $allowed_types ) ) {
						$preselected_value = $allowed_types;
						$expected_value    = implode( ',', $allowed_types );
						$show_preselected  = true;
					}
				}

				if ( empty( $preselected_value ) ) {
					continue;
				}

				$preselected_facets[] = $preselected_value;

				if ( ! empty( $show_preselected ) ) {
					if ( ! $user_selected && $normalized_current !== $expected_value ) {
						$new_query_args[ $query_key ] = $expected_value;
					}
				} else {
					if ( $normalized_current !== $expected_value ) {
						$new_query_args[ $query_key ] = $expected_value;
					}
				}
			}

			if ( empty( $preselected_facets ) ) {
				return;
			}

			// Only keep _facet keys
			$new_query_args = array_filter(
				$new_query_args,
				function( $value, $key ) {
					if ( strpos( $key, '_' ) !== 0 ) {
						return false;
					}
					$value = trim( (string) $value );
					return $value !== '' && $value !== ',' && $value !== '|' && $value !== '|,' && $value !== ',|';
				},
				ARRAY_FILTER_USE_BOTH
			);

			// Avoid redirect loops
			if ( $new_query_args !== $current_query_args ) {
				$encoded_query_args = [];
				foreach ( $new_query_args as $key => $value ) {
					$encoded_query_args[ $key ] = is_string( $value ) ? rawurlencode( $value ) : $value;
				}

				$new_url = add_query_arg( $encoded_query_args, home_url( wp_parse_url( $current_url, PHP_URL_PATH ) ) );
				wp_redirect( $new_url );
				exit;
			}
		}
	}

	public function add_facetwp_hidden_class( $output, $params ) {
		global $post;

		if ( ! is_page() || ! function_exists( 'FWP' ) || empty( $post ) ) {
			return $output;
		}

		$facet_name = $params['facet']['name'];
		$facet_type = $params['facet']['type'];

		$preselected_value = get_post_meta( $post->ID, self::PREFIX_FACET_WP_REMOTE_DATA_PRESELECTED__FACET . $facet_name, true );

		if ( empty( $preselected_value ) ) {
			return $output;
		}

		$show_preselected = get_post_meta( $post->ID, self::PREFIX_FACET_WP_REMOTE_DATA_PRESELECTED__FACET . $facet_name . '_show', true );

		if ( 'sort' !== $facet_type && ( ! empty( $preselected_value ) && empty( $show_preselected ) ) ) {
			$output = str_replace( "facetwp-{$facet_type}", "facetwp-{$facet_type} preselect-hidden", $output );
		}

		return $output;
	}

	public function remove_any_on_mls_facet( $output, $args ) {
		if ( 'mls' === $args['facet']['name'] ) {
			$output = str_replace( '<option value="">Any</option>', '', $output );
		}

		return $output;
	}

	public static function force_update_neighborhood_pages_cache() {
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
			WP_CLI::log( 'Facet_Wp_Remote_Data_Neighborhood_Page::force_update_neighborhood_pages_cache()' );
		}

		$posts_with_preselected_facets = self::get_posts_with_preselected_facet_meta();

		if ( empty( $posts_with_preselected_facets ) ) return;

		$facets = FWP()->helper->get_facets();

		if ( empty( $facets ) ) return;

		$facet_wp_remote_data_handler_instance = new Facet_Wp_Remote_Data_Handler();

		foreach ( $posts_with_preselected_facets as $post_id => $post ) {
			$facets_for_request = [];

			foreach ( $facets as $facet ) {
				if ( array_key_exists( $facet['name'], $post ) ) {
					if ( is_array( $post[ $facet['name'] ] ) ) {
						$facets_for_request[ $facet['name'] ] = $post[ $facet['name'] ];
					} else {
						$facets_for_request[ $facet['name'] ][] = $post[ $facet['name'] ];
					}
				}
			}

			if ( empty( $facets_for_request ) ) continue;

			// Allowed property types
			$allowed_property_types = get_option( 'facetwp_remote_data_only_show_property_types' );

			if ( ! empty( $allowed_property_types ) ) {
				$facets_for_request['property_type'] = $allowed_property_types;
			}

			// Get filtered posts data
			$facetwp_remote_site_filtered_data = $facet_wp_remote_data_handler_instance->get_remote_site_facetwp_filtered_data( null, null, $facets_for_request );

			// Find sort facet value
			$facets_from_options = $facet_wp_remote_data_handler_instance->get_facets_from_options();

			if ( ! empty( $facets_from_options ) ) {
				$sort_facet = array_filter( $facets_from_options, fn ( $facet ) => 'sort' === $facet['type'] );
				$sort_facet = ! empty( $sort_facet ) ? array_shift( $sort_facet ) : [];

				if ( ! empty( $sort_facet ) ) {
					$selected_value = get_post_meta(
						$post_id,
						Facet_Wp_Remote_Data_Neighborhood_Page::PREFIX_FACET_WP_REMOTE_DATA_PRESELECTED__FACET . $sort_facet['name'],
						true
					);

					if ( ! empty( $selected_value ) ) {
						$sort_facet_option = $selected_value;
					}
				}
			}

			// No manual sort selected, fallback to default from settings
			$sort_facet_option = $sort_facet_option ?? ( get_option( 'facetwp_remote_data_default_sort_option' ) ?: null );

			// Get posts
			$filtered_post_results = $facetwp_remote_site_filtered_data['results'] ?? [];

			$posts_data = $facet_wp_remote_data_handler_instance->get_remote_site_posts(
				$filtered_post_results,
				false,
				1,
				apply_filters( 'facet_wp_remote_data_posts_per_page', Facet_Wp_Remote_Data_Handler::$posts_per_page ),
				$sort_facet_option
			);

			// Cache data
			$data_for_cache = [
				'facet_data' => $facetwp_remote_site_filtered_data,
				'posts' => $posts_data
			];

			$class = new stdClass();
			$class->http_params = [
				'get' => [],
				'uri' => '',
				'url_vars' => [],
			];

			foreach ( $facets_for_request as $facet_name => $facet_value ) {
				$class->http_params['get'][ '_' . $facet_name ] = is_array( $facet_value ) ? implode( ',', $facet_value ) : $facet_value;
				$class->http_params['url_vars'][ $facet_name ] = is_array( $facet_value ) ? array_values( $facet_value ) : $facet_value;
			}

			$class->http_params['uri'] = 'homes-for-sale/' . get_page_uri( $post_id );

			$transient_key = Facet_Wp_Remote_Data_Cache::remote_site_facet_search_data( $class->http_params );

			Facet_Wp_Remote_Data_Cache::set( $transient_key, $data_for_cache );
		}
	}

	public static function get_posts_with_preselected_facet_meta() {
		global $wpdb;

		$facets = FWP()->helper->get_facets();

		if ( empty( $facets ) ) {
			return [];
		}

		$meta_keys = [];

		foreach ( $facets as $facet ) {
			if ( empty( $facet['name'] ) ) {
				continue;
			}

			$meta_keys[] = self::PREFIX_FACET_WP_REMOTE_DATA_PRESELECTED__FACET . $facet['name'];
		}

		if ( empty( $meta_keys ) ) {
			return [];
		}

		$placeholders = implode( ', ', array_fill( 0, count( $meta_keys ), '%s' ) );

		$sql = " SELECT p.ID as post_id, pm.meta_key, pm.meta_value
			FROM {$wpdb->posts} p
			INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
			WHERE p.post_type IN ('page', 'community')
				AND p.post_status = 'publish'
				AND pm.meta_key IN ($placeholders)
				AND pm.meta_value != ''
			";

		$results = $wpdb->get_results( $wpdb->prepare( $sql, ...$meta_keys ), ARRAY_A );

		if ( empty( $results ) ) return [];

		$grouped = [];

		foreach ( $results as $row ) {
			$post_id = (int) $row['post_id'];
			$meta_key = $row['meta_key'];
			$facet_name = str_replace( self::PREFIX_FACET_WP_REMOTE_DATA_PRESELECTED__FACET, '', $meta_key );
			$meta_val = maybe_unserialize( $row['meta_value'] );

			if ( ! isset( $grouped[ $post_id ] ) ) {
				$grouped[ $post_id ] = [];
			}

			$grouped[ $post_id ][ $facet_name ] = $meta_val;
		}

		return $grouped;
	}

	public function get_facets_with_choices() {
		global $wpdb;

		$transient_key = Facet_Wp_Remote_Data_Cache::PROPERTY_FACETWP_WITH_CHOICES;
		$skip_cache    = apply_filters( 'facetwp_remote_data_skip_cache', false );

		$facet_with_choices = ! $skip_cache
			? Facet_Wp_Remote_Data_Cache::get( $transient_key )
			: false;

		if ( false === $facet_with_choices ) {
			$facets = FWP()->helper->get_facets();

			if ( empty( $facets ) ) {
				return null;
			}

			$post_ids = $wpdb->get_col( "SELECT DISTINCT post_id FROM {$wpdb->prefix}facetwp_index" );

			if ( empty( $post_ids ) ) {
				return null;
			}

			$facet_with_choices = [];

			foreach ( $facets as $facet ) {
				if ( in_array( $facet['type'], ['map', 'autocomplete'] ) ) continue;

				if ( Facet_Wp_Remote_Data_Handler::PRICE_RANGE_LINKS_FACET_NAME === $facet['name'] ) continue;

				$facet_name  = $facet['name'];
				$facet_label = $facet['label'] ?? ucfirst( $facet_name );

				$results = $wpdb->get_results( $wpdb->prepare(
					"SELECT facet_value, facet_display_value
					 FROM {$wpdb->prefix}facetwp_index
					 WHERE facet_name = %s AND post_id IN (" . implode( ',', array_map( 'absint', $post_ids ) ) . ")
					 GROUP BY facet_value, facet_display_value",
					$facet_name
				), ARRAY_A );

				if ( in_array( $facet['type'], ['dropdown', 'fselect', 'radio', 'checkboxes'] ) ) {
					$choices = array_map( function ( $row ) {
						return [
							'value' => $row['facet_value'],
							'label' => $row['facet_display_value'],
						];
					}, $results );
				} else {
					$choices = [];
				}


				$facet_with_choices[ $facet_name ] = [
					'name'     => $facet_name,
					'label'    => $facet_label,
					'type'     => $facet['type'],
					'settings' => $facet['settings'] ?? [],
					'choices'  => $choices,
				];
			}

			if ( ! empty( $facet_with_choices ) ) {
				$facet_with_choices = ( new Facet_Wp_Remote_Data_Handler )->sort_mls_facet( $facet_with_choices );

				Facet_Wp_Remote_Data_Cache::set( $transient_key, $facet_with_choices, HOUR_IN_SECONDS );
			}
		}

		return $facet_with_choices ?: null;
	}

}