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

		$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 = ( new Facet_Wp_Remote_Data_Handler() )->get_remote_site_facetwp_filtered_data( null, 1 );

			if ( empty( $facets['facets'] ) ) return;

			$facet_with_choices = array_filter(
				$facets['facets'],
				fn ( $facet ) => ! empty( $facet['choices'] )
			);

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

		foreach ( $facet_with_choices as $facet ) {
			$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 );

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

		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;

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

			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;

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

			$filters = [];

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

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

				if ( ! empty( $preselected_value ) ) {
					if ( $facet_type === 'checkboxes' && is_array( $preselected_value ) ) {
						$filters["_{$facet_name}"] = implode(',', $preselected_value);
					} else {
						$filters["_{$facet_name}"] = $preselected_value;
					}
				}
			}

			if ( ! empty( $filters ) ) {
				$current_url = home_url( add_query_arg( [], $_SERVER['REQUEST_URI'] ) );

				$has_existing_filters = false;

				foreach ( $filters as $key => $value ) {
					if ( false !== strpos( $current_url, $key ) ) {
						$has_existing_filters = true;

						break;
					}
				}

				if ( ! $has_existing_filters ) {
					$new_url = add_query_arg( $filters, $current_url );

					wp_redirect( $new_url );

					exit;
				}
			}
		}
	}

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

		if ( is_page() ) {
			if ( ! 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 ) ) {
			$output = str_replace( "facetwp-{$facet_type}", "facetwp-{$facet_type} preselect-hidden", $output );
		}

		return $output;
	}

}