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

	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 set( $transient_key, $data, $expiration = 30 * MINUTE_IN_SECONDS ) {
		set_transient( $transient_key, $data, $expiration );
	}

	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() {
		$response = wp_remote_get(
			home_url(),
			[
				'timeout' => 30,
				'user-agent' => 'Cache-Warmup',
			]
		);

		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 = delete_transient( $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] );
	}

}
