<?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_type = isset( $facet['type'] ) ? $facet['type'] : 'dropdown';

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

			$facet_name = $facet['name'];
			$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;

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

			// Save selected facet value
			if ( isset( $_POST[ $facet_name ] ) ) {
				if ( 'checkboxes' === $facet_type ) {
					$values = array_map( 'sanitize_text_field', (array) $_POST[ $facet_name ] );

					$updated = update_post_meta( $post_id, $meta_key, $values );
				} else {
					$updated = update_post_meta( $post_id, $meta_key, sanitize_text_field( $_POST[ $facet_name ] ) );
				}
			} else {
				if ( 'checkboxes' === $facet_type ) {
					$updated = 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 );
			}

			// Clear cached property data if anything updated
			if ( isset( $updated ) && $updated ) {
				Facet_Wp_Remote_Data_Cache::delete_property_cached_data( $post_id );
			}
		}
	}

	public function redirect_to_facetwp_filtered_url() {
		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 );

			$filters = [];
			$needs_redirect = false;

			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;
				$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 ] ?? null;
				$user_selected = isset( $current_value ) && '' !== $current_value;

				if ( ! empty( $show_preselected ) ) {
					// Checkbox is enabled: respect user's choice if they selected something
					if ( ! $user_selected ) {
						// No user selection, inject preselected
						if ( $facet_type === 'checkboxes' && is_array( $preselected_value ) ) {
							$filters[ $query_key ] = implode(',', $preselected_value);
						} else {
							$filters[ $query_key ] = $preselected_value;
						}
						$needs_redirect = true;
					}
				} else {
					// Checkbox is not enabled: always inject preselected (even overwriting)
					if ( $facet_type === 'checkboxes' && is_array( $preselected_value ) ) {
						$preselected_value_str = implode(',', $preselected_value);
						if ( (string) $current_value !== (string) $preselected_value_str ) {
							$filters[ $query_key ] = $preselected_value_str;
							$needs_redirect = true;
						}
					} else {
						if ( (string) $current_value !== (string) $preselected_value ) {
							$filters[ $query_key ] = $preselected_value;
							$needs_redirect = true;
						}
					}
				}
			}

			if ( $needs_redirect && ! empty( $filters ) ) {
				$new_query_args = array_merge( $current_query_args, $filters );
				$new_url = add_query_arg( $new_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 ) {
				if ( ! in_array( $facet['type'], [ 'dropdown', 'select', 'radio', 'fselect', 'checkboxes' ] ) ) {
					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 ( empty( $results ) ) {
					continue;
				}

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

}