<?php

namespace Licenzo\Modules\EDD;

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

/**
 * Detect the EDD Recurring Payments paid addon and shield Licenzo from
 * creating a second, parallel subscription state machine on top of it.
 *
 * EDD Recurring owns its own subscription lifecycle: creation from
 * `edd_recurring` cart items, renewal via its own cron, cancellation via
 * its own REST endpoints, and Stripe PaymentIntent management. If
 * Licenzo's order handler also runs, the same purchase produces two
 * subscription records — each with its own renewal schedule — on the
 * same card. That is a billing correctness issue, not a feature gap.
 *
 * Default behavior when the conflict is detected:
 *  - Licenzo's EDD bootstrap is short-circuited (no hooks attached).
 *  - A non-dismissible admin notice explains the conflict and the
 *    escape hatch to the site operator.
 *
 * Escape hatch: filter `licenzo_edd_recurring_coexistence` can be
 * returned true by an opt-in integration that has decided, knowing the
 * trade-offs, to let Licenzo take over subscription orchestration and
 * treat EDD Recurring purchases as one-off orders. This is not exposed
 * in UI and not supported by default.
 */
class EddRecurringDetector
{
    public const COEXISTENCE_FILTER = 'licenzo_edd_recurring_coexistence';

    /**
     * Returns true when the paid EDD Recurring Payments addon is active
     * on the site and the operator has not explicitly opted in to
     * Licenzo coexistence.
     */
    public static function hasBlockingConflict(): bool
    {
        if (!static::isEddRecurringActive()) {
            return false;
        }

        // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.DynamicHooknameFound -- Constant resolves to 'licenzo_edd_recurring_coexistence'.
        return !(bool) apply_filters(static::COEXISTENCE_FILTER, false);
    }

    /**
     * Returns true when the EDD Recurring Payments addon is loaded,
     * regardless of the coexistence override.
     */
    public static function isEddRecurringActive(): bool
    {
        return class_exists('EDD_Recurring') || class_exists('\\EDD_Recurring');
    }

    /**
     * Wire up the admin notice. Safe to call unconditionally — the
     * notice only renders when a blocking conflict exists.
     */
    public static function registerAdminNotice(): void
    {
        add_action('admin_notices', [static::class, 'renderNotice']);
    }

    public static function renderNotice(): void
    {
        if (!static::hasBlockingConflict()) {
            return;
        }

        if (!current_user_can('manage_options')) {
            return;
        }

        $title = esc_html__('Licenzo has paused its Easy Digital Downloads integration', 'licenzo');
        $body = esc_html__(
            'EDD Recurring Payments is active on this site and already manages subscription renewals and Stripe billing. To avoid double-charging customers, Licenzo will not create subscriptions for EDD purchases until the conflict is resolved. License entitlements for EDD Recurring purchases are not tracked by Licenzo while this notice is shown.',
            'licenzo'
        );
        $guidance = esc_html__(
            'Resolution: choose one billing owner. Either deactivate EDD Recurring Payments to let Licenzo drive subscriptions, or keep EDD Recurring and leave licensing out of Licenzo until we ship a license-only coexistence mode.',
            'licenzo'
        );

        printf(
            '<div class="notice notice-error"><p><strong>%1$s</strong></p><p>%2$s</p><p>%3$s</p></div>',
            esc_html($title),
            esc_html($body),
            esc_html($guidance)
        );
    }
}
