<?php
/**
 * Gateway registry.
 *
 * @package Lucrativeit_Subscription_Recurring_Billing
 */

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

/**
 * Registers and resolves payment gateways.
 */
class LUCRSURE_Gateway_Manager {

	/**
	 * Singleton.
	 *
	 * @var LUCRSURE_Gateway_Manager|null
	 */
	private static $instance = null;

	/**
	 * Registered gateways keyed by id.
	 *
	 * @var LUCRSURE_Gateway_Interface[]
	 */
	protected $gateways = array();

	/**
	 * Get the singleton.
	 *
	 * @return LUCRSURE_Gateway_Manager
	 */
	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Constructor: register the core gateways.
	 */
	private function __construct() {
		$this->register( new LUCRSURE_Stripe_Gateway() );
		$this->register( new LUCRSURE_PayPal_Gateway() );
		$this->register( new LUCRSURE_SSLCommerz_Gateway() );
		$this->register( new LUCRSURE_Razorpay_Gateway() );
		$this->register( new LUCRSURE_Manual_Gateway() );

		/**
		 * Allow third parties to register additional gateways.
		 *
		 * @param LUCRSURE_Gateway_Manager $manager Manager instance.
		 */
		do_action( 'lucrsure_register_gateways', $this );
	}

	/**
	 * Register a gateway.
	 *
	 * @param LUCRSURE_Gateway_Interface $gateway Gateway.
	 */
	public function register( LUCRSURE_Gateway_Interface $gateway ) {
		$this->gateways[ $gateway->get_id() ] = $gateway;
	}

	/**
	 * Get a gateway by id.
	 *
	 * @param string $id Gateway id.
	 * @return LUCRSURE_Gateway_Interface|null
	 */
	public function get( $id ) {
		return isset( $this->gateways[ $id ] ) ? $this->gateways[ $id ] : null;
	}

	/**
	 * Get all registered gateways.
	 *
	 * @return LUCRSURE_Gateway_Interface[]
	 */
	public function all() {
		return $this->gateways;
	}

	/**
	 * Get only enabled gateways.
	 *
	 * @return LUCRSURE_Gateway_Interface[]
	 */
	public function enabled() {
		return array_filter(
			$this->gateways,
			static function ( $gateway ) {
				return $gateway->is_enabled();
			}
		);
	}
}
