<?php

namespace Fotogenic_AI;

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

/**
 * Durable lifecycle boundary for plugin-owned background scheduling.
 */
final class Background_Runtime_State {
	private const STATE_OPTION = 'fotogenic_ai_background_runtime_state';
	private const ENABLED      = 'enabled';
	private const DISABLED     = 'disabled';

	private function __construct() {}

	public static function enable(): void {
		update_option( self::STATE_OPTION, self::ENABLED, false );
	}

	public static function disable(): void {
		update_option( self::STATE_OPTION, self::DISABLED, false );
	}

	public static function is_enabled(): bool {
		$state = get_option( self::STATE_OPTION, null );
		if ( self::ENABLED === $state ) {
			return true;
		}
		if ( self::DISABLED === $state ) {
			return false;
		}

		return self::is_plugin_active();
	}

	private static function is_plugin_active(): bool {
		if ( ! defined( 'FOTOGENIC_AI_FILE' ) || ! function_exists( 'plugin_basename' ) ) {
			return false;
		}

		$basename = plugin_basename( FOTOGENIC_AI_FILE );
		$active   = get_option( 'active_plugins', [] );
		if ( is_array( $active ) && in_array( $basename, $active, true ) ) {
			return true;
		}

		if ( function_exists( 'is_multisite' ) && is_multisite() && function_exists( 'get_site_option' ) ) {
			$network_active = get_site_option( 'active_sitewide_plugins', [] );
			return is_array( $network_active ) && array_key_exists( $basename, $network_active );
		}

		return false;
	}
}
