<?php

declare(strict_types=1);

namespace Signocore\Multilanguage\Support;

if (!defined('ABSPATH')) {
	exit;
}

use Signocore\Multilanguage\Application\Constants;

final class TransientManager
{
	/**
	 * Delete a specific transient.
	 */
	public static function delete(string $key): void
	{
		delete_transient(Constants::TRANSIENT_PREFIX . $key);
	}

	/**
	 * Delete all transients matching a suffix pattern.
	 */
	public static function deleteByPrefix(string $prefix): void
	{
		global $wpdb;

		$fullPrefix = '_transient_' . Constants::TRANSIENT_PREFIX . $prefix;

		$wpdb->query(
			$wpdb->prepare(
				"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
				$wpdb->esc_like($fullPrefix) . '%',
				$wpdb->esc_like('_transient_timeout_' . Constants::TRANSIENT_PREFIX . $prefix) . '%'
			)
		);
	}

	/**
	 * Invalidate all language-related caches.
	 */
	public static function invalidateLanguages(): void
	{
		delete_transient(Constants::TRANSIENT_PREFIX . 'active_languages');
	}

	/**
	 * Invalidate translation caches for a specific element.
	 */
	public static function invalidateTranslations(int $elementId): void
	{
		self::delete('translations_' . $elementId);
	}

	/**
	 * Invalidate string translation caches.
	 */
	public static function invalidateStrings(): void
	{
		self::deleteByPrefix('strings_');
	}

	/**
	 * Invalidate the plugin update check cache.
	 */
	public static function invalidatePluginUpdate(): void
	{
		delete_site_transient(Constants::TRANSIENT_PREFIX . 'plugin_update');
	}

	/**
	 * Clear all plugin transients.
	 */
	public static function clearAll(): void
	{
		self::deleteByPrefix('');
	}
}
