<?php

class Facet_Wp_Remote_Data_Cache {

	public const PREFIX_PROPERTY_REMOTE_SITE_DATA = 'facetwp_property_remote_site_data_';
	public const PREFIX_REMOTE_SITE_DATA = 'facetwp_remote_site_data_';
	public const PROPERTY_FACETWP_WITH_CHOICES = 'facetwp_property_remote_site_facetwp_with_choices_data';
	public const FACETWP_MAP_FACET_SETTINGS = 'facet_wp_map_facet_settings';
	public const PROPERTY_POSTS_REMOTE_SITE_DATA = 'acf_property_posts_remote_site_data_';
	public const FACETWP_LATEST_LISTINGS_REMOTE_SITE_DATA = 'facetwp_latest_listings_remote_site_data_';

	public static function get_cache_prefixes() {
		return [
			self::PREFIX_PROPERTY_REMOTE_SITE_DATA,
			self::PREFIX_REMOTE_SITE_DATA,
			self::PROPERTY_FACETWP_WITH_CHOICES,
			self::FACETWP_MAP_FACET_SETTINGS,
			self::PROPERTY_POSTS_REMOTE_SITE_DATA,
			self::FACETWP_LATEST_LISTINGS_REMOTE_SITE_DATA,
		];
	}

	public static function property_remote_site_data( $property_id ) {
		return self::PREFIX_PROPERTY_REMOTE_SITE_DATA . $property_id;
	}

	public static function remote_site_data( $query_args ) {
		return self::PREFIX_REMOTE_SITE_DATA . md5( is_array( $query_args ) ? wp_json_encode( $query_args ) : $query_args );
	}

	public static function property_posts_remote_site_data( $post_ids ) {
		return self::PROPERTY_POSTS_REMOTE_SITE_DATA . md5( serialize( $post_ids ) );
	}

	public static function remote_site_data_latest_listings( $posts_per_page, $paged ) {
		return self::FACETWP_LATEST_LISTINGS_REMOTE_SITE_DATA . $posts_per_page . '_' . $paged;
	}

	public static function set( $transient_key, $data, $expiration = 30 * MINUTE_IN_SECONDS ) {
		if ( wp_using_ext_object_cache() ) {
			wp_cache_set( $transient_key, $data, 'transient', $expiration );
		} else {
			set_transient( $transient_key, $data, $expiration );
		}
	}

	public static function get( $key ) {
		if ( wp_using_ext_object_cache() ) {
			return wp_cache_get( $key, 'transient' );
		}

		return get_transient( $key );
	}

	public static function delete( $key ) {
		if ( wp_using_ext_object_cache() ) {
			return wp_cache_delete( $key, 'transient' );
		}

		return delete_transient( $key );
	}

	public function facetwp_cache_warmup_event() {
		if ( ! wp_next_scheduled( 'facetwp_remote_data_cache_warmup_event' ) ) {
			wp_schedule_event( time(), 'every_15_minutes', 'facetwp_remote_data_cache_warmup_event' );
		}
	}

	public function cron_schedules( $schedules ) {
		$schedules['every_15_minutes'] = [
			'interval' => 15 * MINUTE_IN_SECONDS,
			'display' => 'Every 15 Minutes',
		];

		return $schedules;
	}

	public static function warmup_cache() {
		$url = $_ENV('WP_HOME') ?? null;

		if ( ! $url ) return;

		$response = wp_remote_get(
			$url,
			[
				'timeout' => 30,
				'user-agent' => 'Cache-Warmup',
				'redirection' => 5,
				'sslverify' => Facet_Wp_Remote_Data_Utils::should_ssl_verify(),
			]
		);

		if ( is_wp_error( $response ) ) {
			error_log( '[Cache Warmup] Error: ' . $response->get_error_message() );

			return false;
		}

		$code = wp_remote_retrieve_response_code( $response );

		if ( $code !== 200 ) {
			error_log( "[Cache Warmup] Unexpected response code: $code" );

			return false;
		}

		return true;
	}

	public static function delete_property_cached_data( $post_id ) {
		$transient_key = self::property_remote_site_data( $post_id );

		$deleted_transient = self::delete( $transient_key );

		return $deleted_transient
			? true
			: new WP_Error( 'no_rows', 'No cached data.', ['status' => 204] );
	}

	public static function delete_cache() {
		global $wpdb;

		$prefixes = self::get_cache_prefixes();

		$deleted = 0;

		if ( wp_using_ext_object_cache() ) {
			// Delete transients stored in the object cache (if not stored in the DB)
			if ( function_exists( 'wp_cache_flush_group' ) ) {
				$deleted = wp_cache_flush_group( 'transient' );
			}
		} else {
			// Delete transients stored in the DB
			if ( $prefixes ) {
				foreach ( $prefixes as $prefix ) {
					$result = $wpdb->query(
						$wpdb->prepare(
							"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s",
							$wpdb->esc_like( '_transient_' . $prefix ) . '%'
						)
					);

					$deleted += $result ?: 0;
				}
			}
		}

		return $deleted ? true : new WP_Error( 'no_rows', 'No cached data.', ['status' => 204] );
	}

}
