<?php
/**
 * Bricks environment detection and version floor (Law 4).
 *
 * @package LolaCoreForBricks
 */

declare(strict_types=1);

namespace LolaCoreForBricks;

/**
 * Single version decision point for the Bricks bridge addon.
 */
class BricksEnv
{
    public const FLOOR_VERSION = '2.0';

    private static ?string $cssLoadingMode = null;

    public static function isAvailable(): bool
    {
        return self::isBricksThemeActive() && defined('BRICKS_VERSION');
    }

    public static function version(): string
    {
        return defined('BRICKS_VERSION') ? (string) BRICKS_VERSION : '';
    }

    public static function meetsFloor(): bool
    {
        if (!self::isAvailable()) {
            return false;
        }

        return version_compare(self::version(), self::FLOOR_VERSION, '>=');
    }

    public static function cssLoadingMode(): string
    {
        if (self::$cssLoadingMode !== null) {
            return self::$cssLoadingMode;
        }

        $settings = get_option('bricks_global_settings', []);
        $mode     = 'inline';

        if (is_array($settings) && isset($settings['cssLoading'])) {
            $mode = (string) $settings['cssLoading'];
        }

        if ($mode === '') {
            $mode = 'inline';
        }

        self::$cssLoadingMode = $mode;

        return $mode;
    }

    public static function canUseBuilder(int $postId = 0): bool
    {
        if (!self::isAvailable()) {
            return false;
        }

        if (class_exists(\Bricks\Capabilities::class)) {
            return (bool) \Bricks\Capabilities::current_user_can_use_builder($postId);
        }

        return current_user_can('manage_options');
    }

    public const BASE_ABILITY_COUNT = 65;

    public const WOO_ABILITY_COUNT = 4;

    /**
     * Registered abilities shipped in this addon (grows with later sprints).
     * WooCommerce shop abilities are counted only when WooCommerce is active.
     */
    public static function abilityCount(): int
    {
        return self::BASE_ABILITY_COUNT + (self::isWooCommerceActive() ? self::WOO_ABILITY_COUNT : 0);
    }

    /**
     * Runtime WooCommerce detection. Tests may override with $_test_woocommerce_active.
     */
    public static function isWooCommerceActive(): bool
    {
        if (array_key_exists('_test_woocommerce_active', $GLOBALS)) {
            return (bool) $GLOBALS['_test_woocommerce_active'];
        }

        return class_exists(\WooCommerce::class, false) || function_exists('WC');
    }

    public static function userCanReadDesignSystem(): bool
    {
        return current_user_can('manage_options');
    }

    private static function isBricksThemeActive(): bool
    {
        if (!function_exists('wp_get_theme')) {
            return false;
        }

        $theme = wp_get_theme();

        return $theme->get_template() === 'bricks' || $theme->get_stylesheet() === 'bricks';
    }
}
