<?php
/**
 * Freemium capability checks.
 *
 * @package WPDudeProducts
 */

declare(strict_types=1);

namespace WPDude\Products\Licensing;

/**
 * Central Free / Pro feature gates.
 *
 * WordPress.org free builds must not lock built-in features (Guideline 5).
 * Pro-only extras live in the Freemius premium package and are stripped from the free .org zip.
 */
final class Capabilities {

	private Freemius $freemius;

	public function __construct( ?Freemius $freemius = null ) {
		$this->freemius = $freemius ?? Freemius::instance();
	}

	/**
	 * Shared instance.
	 */
	public static function instance(): self {
		static $instance = null;
		if ( null === $instance ) {
			$instance = new self();
		}
		return $instance;
	}

	/**
	 * Whether the site has an active Pro licence (or an explicit local bypass).
	 *
	 * Used only for premium-package features (stripped from free Freemius builds).
	 */
	public function is_pro(): bool {
		/**
		 * Force Pro capabilities (local development only).
		 *
		 * @param bool $allow Default false.
		 */
		if ( (bool) apply_filters( 'wpdude_dc_force_premium', false ) ) {
			return true;
		}

		if ( defined( 'WPDUDE_DC_DEV_MODE' ) && WPDUDE_DC_DEV_MODE ) {
			return true;
		}

		return $this->freemius->has_pro_access();
	}

	/**
	 * Outgoing integration webhooks (Pro package only).
	 */
	public function can_use_webhooks(): bool {
		return $this->is_pro();
	}

	/**
	 * Whether outgoing webhook settings/tools should appear in admin.
	 *
	 * Requires Pro and the premium Integrations code (stripped from the .org free build).
	 */
	public function can_manage_outgoing_webhooks(): bool {
		if ( ! $this->can_use_webhooks() ) {
			return false;
		}

		return class_exists( \WPDude\Products\Integrations\Outgoing_Webhook_Dispatcher::class );
	}

	/**
	 * CSV order export (Pro package only).
	 */
	public function can_export_csv(): bool {
		return $this->is_pro();
	}

	/**
	 * Administrative REST API (Pro package only).
	 */
	public function can_use_admin_rest_api(): bool {
		return $this->is_pro();
	}

	/**
	 * Custom customer email subject/body and admin sale notify (Pro package only).
	 */
	public function can_customize_emails(): bool {
		return $this->is_pro();
	}

	/**
	 * Admin sale notification emails (Pro package only).
	 */
	public function can_use_admin_notifications(): bool {
		return $this->is_pro();
	}

	/**
	 * Sales reports admin UI (Pro package only).
	 */
	public function can_use_advanced_reporting(): bool {
		return $this->is_pro();
	}

	/**
	 * Upgrade URL for Freemius pricing (or empty).
	 */
	public function upgrade_url(): string {
		$fs = $this->freemius->fs();
		if ( $fs && method_exists( $fs, 'get_upgrade_url' ) ) {
			$url = (string) $fs->get_upgrade_url();
			return $url;
		}
		return '';
	}
}
