<?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 ]
			);
		}
	}

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

				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':
				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 );

				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;
		}

		if ( 'dropdown' === $facet_type ) {
			// "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 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() {
		if ( is_admin() || defined( 'DOING_AJAX' ) && DOING_AJAX ) {
			return;
		}

		if ( is_page() || is_singular( 'community' ) ) {
			global $post;

			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'] ) );
			$current_query_args = [];
			wp_parse_str( wp_parse_url( $current_url, PHP_URL_QUERY ), $current_query_args );

			$new_query_args = $current_query_args;

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

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

				$query_key = "_{$facet_name}";
				$current_value = $current_query_args[ $query_key ] ?? '';

				// Build expected
				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( ',', array_map( 'strval', [$from, $to] ));
					} else {
						$expected_value = implode( ',', array_map( 'strval', $preselected_value ));
					}
				} else {
					$expected_value = (string) $preselected_value;
				}

				// Normalize comparison
				$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;
					}
				}

				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;
					}
				}
			}

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

			// Compare raw arrays (NOT encoded yet)
			if ( $new_query_args !== $current_query_args ) {

				// Now encode each value BEFORE building URL
				$encoded_query_args = [];
				foreach ( $new_query_args as $key => $value ) {
					if ( is_string( $value ) ) {
						$encoded_query_args[ $key ] = rawurlencode( $value );
					} else {
						$encoded_query_args[ $key ] = $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 ( ! 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 ) {
			$facets_for_request = [];

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

			if ( empty( $facets_for_request ) ) continue;

			$facetwp_remote_site_filtered_data = $facet_wp_remote_data_handler_instance->get_remote_site_facetwp_filtered_data( null, null, $facets_for_request );

			$posts_data = $facet_wp_remote_data_handler_instance->get_remote_site_posts( $facetwp_remote_site_filtered_data['results'] ?? [] );

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

			$facets_for_transient_key = array_combine(
				array_map( fn( $key ) => '_' . $key, array_keys( $facets_for_request ) ),
				array_map( fn( $value ) => is_array( $value ) ? implode( ',', $value ) : $value, $facets_for_request )
			);

			$transient_key = Facet_Wp_Remote_Data_Cache::remote_site_facet_search_data( $facets_for_transient_key );

			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(): ?array {
		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 ) {
				$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 );

				$choices = array_map( function ( $row ) {
					return [
						'value' => $row['facet_value'],
						'label' => $row['facet_display_value'],
					];
				}, $results );

				$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;
	}

}