<?php
/**
 * Cache Manager.
 *
 * One shared implementation of "clear all Platform Helm caches," so the Tools
 * page, the admin-bar button, and anything else call the same code rather than
 * duplicating the transient-clearing logic.
 *
 * Only clears Helm's own transients (pulse, health report, persona-dashboard
 * data). Never touches other plugins' caches.
 *
 * @package Platform\Helm\Core
 */

declare( strict_types = 1 );

namespace Platform\Helm\Core;

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

final class CacheManager {

	/** Transient name prefixes Helm owns. */
	private const PREFIXES = [
		'platform_helm_pulse',
		'platform_helm_health_report',
		'platform_helm_pd_',
	];

	/**
	 * Delete all Helm transients. Returns the number cleared.
	 */
	public static function clear_all(): int {
		global $wpdb;
		$cleared = 0;

		foreach ( self::PREFIXES as $prefix ) {
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
			$names = $wpdb->get_col( $wpdb->prepare(
				"SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s",
				'_transient_' . $wpdb->esc_like( $prefix ) . '%'
			) );
			foreach ( (array) $names as $name ) {
				$transient = preg_replace( '/^_transient_/', '', (string) $name );
				if ( $transient && delete_transient( $transient ) ) {
					$cleared++;
				}
			}
		}

		/**
		 * Fires after Helm caches are cleared, so modules can flush any
		 * in-process caches of their own.
		 */
		do_action( 'platform_helm_caches_cleared' );

		return $cleared;
	}
}
