<?php

namespace Calio\Support;

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

/**
 * Centralizes free/pro access checks so widget registration and admin UI stay in sync.
 */
final class ProAccess
{
    private const DEFAULT_PRO_PLUGIN_BASENAME = 'calio-addon-pro/calio-addon-pro.php';
    private const DEFAULT_UPGRADE_ANCHOR = '#calio_addon_license_settings';

    public static function pro_plugin_basename(): string
    {
        $basename = apply_filters('calio/pro/plugin_basename', self::DEFAULT_PRO_PLUGIN_BASENAME);
        if (!is_string($basename) || trim($basename) === '') {
            return self::DEFAULT_PRO_PLUGIN_BASENAME;
        }

        return trim($basename);
    }

    public static function is_pro_plugin_active(): bool
    {
        $basename = self::pro_plugin_basename();
        $activePlugins = get_option('active_plugins', []);
        $isActive = is_array($activePlugins) && in_array($basename, array_map('strval', $activePlugins), true);

        if (!$isActive && is_multisite()) {
            $networkActivePlugins = get_site_option('active_sitewide_plugins', []);
            $isActive = is_array($networkActivePlugins) && array_key_exists($basename, $networkActivePlugins);
        }

        return (bool) apply_filters('calio/pro/is_plugin_active', $isActive, $basename);
    }

    public static function required_free_version(): string
    {
        $default = defined('CALIO_PRO_REQUIRES_FREE_VERSION') ? (string) CALIO_PRO_REQUIRES_FREE_VERSION : '';
        $required = apply_filters('calio/pro/required_free_version', $default);

        if (!is_string($required)) {
            return '';
        }

        return trim($required);
    }

    public static function is_free_version_compatible(): bool
    {
        $required = self::required_free_version();
        if ($required === '' || !defined('CALIO_VERSION')) {
            return true;
        }

        return version_compare((string) CALIO_VERSION, $required, '>=');
    }

    public static function is_license_active(): bool
    {
        // Never assume license is active by default.
        $default = false;
        return (bool) apply_filters('calio/pro/is_license_active', $default);
    }

    public static function is_pro_unlocked(): bool
    {
        if (!self::is_pro_plugin_active()) {
            return false;
        }

        if (!self::is_free_version_compatible()) {
            return false;
        }

        return self::is_license_active();
    }

    /**
     * @param array<string, mixed> $widget
     */
    public static function is_widget_locked(array $widget): bool
    {
        $tier = strtolower((string) ($widget['tier'] ?? 'free'));
        if ($tier !== 'pro') {
            return false;
        }

        return !self::is_pro_unlocked();
    }

    /**
     * @param array<string, mixed> $extension
     */
    public static function is_extension_locked(array $extension): bool
    {
        $tier = strtolower((string) ($extension['tier'] ?? 'free'));
        if ($tier !== 'pro') {
            return false;
        }

        return !self::is_pro_unlocked();
    }

    public static function lock_reason(): string
    {
        if (!self::is_pro_plugin_active()) {
            return 'pro_inactive';
        }

        if (!self::is_free_version_compatible()) {
            return 'free_outdated';
        }

        if (!self::is_license_active()) {
            return 'license_inactive';
        }

        return 'unlocked';
    }

    /**
     * @return object|null
     */
    private static function freemius_sdk()
    {
        if (function_exists('calio_pro_fs')) {
            $sdk = calio_pro_fs();
            if (is_object($sdk)) {
                return $sdk;
            }
        }

        if (function_exists('calio_fs')) {
            $sdk = calio_fs();
            if (is_object($sdk)) {
                return $sdk;
            }
        }

        if (function_exists('cal_fs')) {
            $sdk = cal_fs();
            if (is_object($sdk)) {
                return $sdk;
            }
        }

        return null;
    }

    public static function account_url(): string
    {
        $sdk = self::freemius_sdk();
        $url = '';

        if (is_object($sdk) && method_exists($sdk, 'get_account_url')) {
            $candidate = $sdk->get_account_url();
            if (is_string($candidate) && trim($candidate) !== '') {
                $url = trim($candidate);
            }
        }

        $url = apply_filters('calio/pro/account_url', $url);
        if (is_string($url) && trim($url) !== '') {
            return trim($url);
        }

        return '';
    }

    public static function activation_url(): string
    {
        $sdk = self::freemius_sdk();
        $url = '';

        if (is_object($sdk) && method_exists($sdk, 'get_activation_url')) {
            $candidate = $sdk->get_activation_url();
            if (is_string($candidate) && trim($candidate) !== '') {
                $url = trim($candidate);
            }
        }

        if ($url === '') {
            $url = self::account_url();
        }

        if ($url !== '' && function_exists('add_query_arg') && strpos($url, 'activate_license=') === false) {
            $url = add_query_arg('activate_license', 'true', $url);
        }

        $url = apply_filters('calio/pro/activation_url', $url);
        if (is_string($url) && trim($url) !== '') {
            return trim($url);
        }

        if (function_exists('admin_url')) {
            return admin_url('admin.php?page=' . CALIO_MENU_SLUG . self::DEFAULT_UPGRADE_ANCHOR);
        }

        return self::DEFAULT_UPGRADE_ANCHOR;
    }

    public static function upgrade_url(): string
    {
        $url = '';
        $sdk = self::freemius_sdk();
        if (is_object($sdk) && method_exists($sdk, 'get_upgrade_url')) {
            $candidate = $sdk->get_upgrade_url();
            if (is_string($candidate) && $candidate !== '') {
                $url = $candidate;
            }
        }

        $url = apply_filters('calio/pro/upgrade_url', $url);
        if (is_string($url) && trim($url) !== '') {
            return trim($url);
        }

        if (function_exists('admin_url')) {
            return admin_url('admin.php?page=' . CALIO_MENU_SLUG . self::DEFAULT_UPGRADE_ANCHOR);
        }

        return self::DEFAULT_UPGRADE_ANCHOR;
    }
}
