<?php
namespace RadiusTheme\RadiusBooking\PaymentGateway;

use RadiusTheme\RadiusBooking\Interfaces\PaymentGatewayInterface;
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}
/**
 * Payment Gateway Factory
 *
 * Creates payment gateway instances based on payment method
 */
class PaymentGatewayFactory {

	/**
	 * Cached gateway instances
	 *
	 * @var array Cached gateway instances
	 */
	private static $gateways = array();

	/**
	 * Gateway configurations
	 *
	 * @var array
	 */
	private static $configs  = array();

	/**
	 * Register gateway configurations
	 *
	 * @param array $configs Configuration for all gateways
	 */
	public static function registerConfigs( array $configs ) {
		self::$configs = $configs;
	}

	/**
	 * Get payment gateway instance
	 *
	 * @param string $gatewayName Gateway name (stripe, paypal, offline)
	 *
	 * @return PaymentGatewayInterface|null
	 */
	public static function create( string $gatewayName ): ?PaymentGatewayInterface {
		// Return cached instance if available
		if ( isset( self::$gateways[ $gatewayName ] ) ) {
			return self::$gateways[ $gatewayName ];
		}

		// Get gateway configuration
		$config = self::$configs[ $gatewayName ] ?? array();

		// Create gateway instance based on name
		$gateway = null;

		switch ( $gatewayName ) {
			case 'paypal':
				$gateway = new PayPalPaymentGateway( $config );
				break;

			default:
				// Allow custom/pro gateways through filter (e.g. Stripe)
				$gateway = apply_filters(
					'rtrb_booking_custom_payment_gateway',
					null,
					$gatewayName,
					$config
				);
				break;
		}

		// Cache the instance
		if ( $gateway ) {
			self::$gateways[ $gatewayName ] = $gateway;
		}

		return $gateway;
	}

	/**
	 * Get all available gateways
	 *
	 * @return array Array of gateway names
	 */
	public static function getAvailableGateways(): array {
		$gateways = array( 'paypal', 'offline' );

		// Stripe is a Pro feature.
		if ( rtrb_pro_active() ) {
			array_unshift( $gateways, 'stripe' );
		}

		// Allow additional gateways through filter
		return apply_filters( 'rtrb_booking_available_payment_gateways', $gateways );
	}

	/**
	 * Check if gateway is configured
	 *
	 * @param string $gatewayName Gateway name
	 *
	 * @return bool
	 */
	public static function isGatewayConfigured( string $gatewayName ): bool {
		$gateway = self::create( $gatewayName );

		return $gateway ? $gateway->isConfigured() : false;
	}

	/**
	 * Clear cached gateways
	 */
	public static function clearCache() {
		self::$gateways = array();
	}
}
