<?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 static function get_cache_prefixes() {
		return [
			self::PREFIX_PROPERTY_REMOTE_SITE_DATA,
			self::PREFIX_REMOTE_SITE_DATA,
			self::PROPERTY_FACETWP_WITH_CHOICES
		];
	}

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

	public static function delete_cache() {
		global $wpdb;

		$prefixes = self::get_cache_prefixes();

		$deleted_rows = 0;
		$deleted = false;

		// Delete transients stored in the DB
		foreach ( $prefixes as $prefix ) {
			$result = $wpdb->query(
				$wpdb->prepare(
					"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s",
					$wpdb->esc_like( '_transient_' . $prefix ) . '%'
				)
			);

			$deleted_rows += $result ?: 0;
		}

		// Delete transients stored in the object cache (if not stored in the DB)
		if ( ! $deleted_rows && function_exists( 'wp_cache_flush_group' ) ) {
			$deleted = wp_cache_flush_group( 'transient' );
		}

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

}
