<?php
/**
 * Schema Caching Layer
 *
 * Caches generated schema markup to improve performance.
 *
 * @package BW_Schema
 * @since 3.0.0-babel
 */

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

class BW_Schema_Cache {

	/**
	 * Cache key prefix
	 *
	 * @var string
	 */
	const CACHE_PREFIX = 'bw_schema_';

	/**
	 * Cache TTL (1 week)
	 *
	 * @var int
	 */
	const CACHE_TTL = 604800;

	/**
	 * Get cached schema or generate new one
	 *
	 * @return array Schema data
	 */
	public static function get_schema() {
		$cache_key = self::CACHE_PREFIX . 'schema';
		$cached = wp_cache_get( $cache_key );

		if ( false !== $cached ) {
			return $cached;
		}

		// Generate fresh schema
		$schema = BW_Schema_Generator::generate();

		// Cache it
		if ( ! empty( $schema ) ) {
			wp_cache_set( $cache_key, $schema, '', self::CACHE_TTL );
		}

		return $schema;
	}

	/**
	 * Invalidate schema cache
	 *
	 * Called when organization settings are saved.
	 *
	 * @return void
	 */
	public static function invalidate() {
		$cache_key = self::CACHE_PREFIX . 'schema';
		wp_cache_delete( $cache_key );
	}

	/**
	 * Get cached organization data
	 *
	 * @return array Organization data
	 */
	public static function get_org_data() {
		$cache_key = self::CACHE_PREFIX . 'org_data';
		$cached = wp_cache_get( $cache_key );

		if ( false !== $cached ) {
			return $cached;
		}

		// Get fresh data
		$data = get_option( 'bw_schema_organization', array() );

		// Cache it
		wp_cache_set( $cache_key, $data, '', self::CACHE_TTL );

		return $data;
	}

	/**
	 * Invalidate organization data cache
	 *
	 * @return void
	 */
	public static function invalidate_org_data() {
		$cache_key = self::CACHE_PREFIX . 'org_data';
		wp_cache_delete( $cache_key );
	}

	/**
	 * Get cache status info
	 *
	 * @return array Cache statistics
	 */
	public static function get_status() {
		$schema_key = self::CACHE_PREFIX . 'schema';
		$org_key = self::CACHE_PREFIX . 'org_data';

		$schema_cached = false !== wp_cache_get( $schema_key );
		$org_cached = false !== wp_cache_get( $org_key );

		return array(
			'schema_cached'     => $schema_cached,
			'org_data_cached'   => $org_cached,
			'cache_ttl'         => self::CACHE_TTL,
			'cache_ttl_hours'   => self::CACHE_TTL / 3600,
		);
	}

	/**
	 * Clear all caches
	 *
	 * Clears all schema and organization data caches.
	 *
	 * @return void
	 */
	public static function clear_all() {
		self::invalidate();
		self::invalidate_org_data();
	}

	/**
	 * Clear cache for a specific post
	 *
	 * @param int $post_id Post ID
	 * @return void
	 */
	public static function clear( $post_id ) {
		// Currently schema is global, not per-post
		// But this method is here for future per-post caching
		self::invalidate();
	}
}
