<?php
/**
 * Cache module — Multisite helpers
 *
 * Centralises blog-id-aware path/URL construction so other components don't
 * need to think about multisite. On single-site installs this is a thin
 * pass-through to default WordPress behaviour.
 *
 * @package BlaminhorEssentials
 */

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

class Blaminhor_Essentials_Cache_Multisite {

	/**
	 * @return int Current blog ID (1 on single-site).
	 */
	public function get_current_blog_id() {
		return is_multisite() ? get_current_blog_id() : 1;
	}

	/**
	 * Per-blog cache base directory.
	 *
	 * Uses wp_upload_dir() so multisite installs naturally land in
	 * `uploads/sites/{N}/blaminhor-essentials/cache/`. Falls back to a plain
	 * subfolder on single-site.
	 *
	 * @param string $subdir Optional subdirectory under the base.
	 * @return string Trailing-slashed absolute path.
	 */
	public function get_cache_dir( $subdir = '' ) {
		$base = blaminhor_essentials_get_upload_dir( 'cache' );
		if ( ! empty( $subdir ) ) {
			$base = trailingslashit( $base ) . ltrim( $subdir, '/' );
		}
		return trailingslashit( $base );
	}

	/**
	 * Per-blog cache base URL (for serving precomputed assets via direct URL).
	 *
	 * @param string $subdir Optional subdirectory under the base.
	 * @return string Trailing-slashed URL.
	 */
	public function get_cache_url( $subdir = '' ) {
		$upload_dir = wp_upload_dir();
		$url        = trailingslashit( $upload_dir['baseurl'] ) . 'blaminhor-essentials/cache';
		if ( ! empty( $subdir ) ) {
			$url .= '/' . ltrim( $subdir, '/' );
		}
		return trailingslashit( $url );
	}

	/**
	 * Whether the module should run network-wide. Reserved for future drop-in
	 * coordination across sites; for now we always operate per-blog.
	 *
	 * @return bool
	 */
	public function is_network_active() {
		if ( ! is_multisite() ) {
			return false;
		}
		$network_plugins = (array) get_site_option( 'active_sitewide_plugins', array() );
		return isset( $network_plugins[ BLAMINHOR_ESSENTIALS_PLUGIN_BASENAME ] );
	}

	/**
	 * Iterate over all blog IDs in a multisite install (single-element array
	 * containing 1 on single-site). Useful for cleanup tasks at deactivation.
	 *
	 * @return array<int, int>
	 */
	public function get_all_blog_ids() {
		if ( ! is_multisite() ) {
			return array( 1 );
		}
		$sites = get_sites( array(
			'fields' => 'ids',
			'number' => 0, // No limit.
		) );
		return array_map( 'absint', $sites );
	}
}
