<?php
namespace RadiusTheme\RadiusBooking\PaymentGateway;

use RadiusTheme\RadiusBooking\Helpers\SettingsHelper;
use RadiusTheme\RadiusBooking\Models\Settings;
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}
/**
 * Payment Service
 *
 * Handles all payment operations through appropriate gateways
 */
class PaymentService {

	/**
	 * Initialize payment service with configurations
	 */
	public static function init() {
		$settings  = new Settings();
		$is_stripe = rtrb_pro_active() && $settings->getNestedKey( 'payment.stripe.enabled' );
		$is_test   = $settings->getNestedKey( 'payment.stripe.testMode' );
		$configs   = array();
		if ( $is_stripe ) {
			$configs['stripe'] = array(
				'test_mode'       => $is_test,
				'secret_key'      => $is_test ? $settings->getNestedKey( 'payment.stripe.testSecretKey' ) : $settings->getNestedKey( 'payment.stripe.liveSecretKey' ),
				'publishable_key' => $is_test ? $settings->getNestedKey( 'payment.stripe.testPublishableKey' ) : $settings->getNestedKey( 'payment.stripe.livePublishableKey' ),
			);
		}
		$is_paypal = $settings->getNestedKey( 'payment.paypal.enabled' );
		if ( $is_paypal ) {
			$is_test           = $settings->getNestedKey( 'payment.paypal.testMode' );
			$configs['paypal'] = array(
				'client_id'     => $is_test ? $settings->getNestedKey( 'payment.paypal.testClientId' ) : $settings->getNestedKey( 'payment.paypal.liveClientId' ),
				'client_secret' => $is_test ? $settings->getNestedKey( 'payment.paypal.testSecretKey' ) : $settings->getNestedKey( 'payment.paypal.liveSecretKey' ),
				'mode'          => $is_test ? 'sandbox' : 'live',
			);
		}
		PaymentGatewayFactory::registerConfigs( $configs );
	}

	/**
	 * Get Stripe publishable key
	 *
	 * @return array|mixed|string
	 */
	public static function getStripePublishableKey() {
		if ( ! rtrb_pro_active() ) {
			return '';
		}
		$settings  = new Settings();
		$is_stripe = $settings->getNestedKey( 'payment.stripe.enabled' );
		$is_test   = $settings->getNestedKey( 'payment.stripe.testMode' );
		if ( $is_stripe ) {
			return $is_test ? $settings->getNestedKey( 'payment.stripe.testPublishableKey' ) : $settings->getNestedKey( 'payment.stripe.livePublishableKey' );
		}
		return '';
	}

	/**
	 * Get PayPal client ID
	 *
	 * @return array|mixed|string
	 */
	public static function getPaypalClientID() {
		$settings  = new Settings();
		$is_paypal = $settings->getNestedKey( 'payment.paypal.enabled' );
		$is_test   = $settings->getNestedKey( 'payment.paypal.testMode' );
		if ( $is_paypal ) {
			return $is_test ? $settings->getNestedKey( 'payment.paypal.testClientId' ) : $settings->getNestedKey( 'payment.paypal.liveClientId' );
		}
		return '';
	}

	/**
	 * Process a payment
	 *
	 * @param string $gatewayName Payment gateway (stripe, paypal, offline)
	 * @param array $paymentData Payment data
	 *
	 * @return array Response from gateway
	 */
	public static function processPayment( string $gatewayName, array $paymentData ): array {
		self::init();
		$gateway = PaymentGatewayFactory::create( $gatewayName );
		if ( ! $gateway ) {
			return array(
				'success' => false,
				'message' => 'Invalid payment gateway: ' . $gatewayName,
			);
		}

		if ( ! $gateway->isConfigured() ) {
			return array(
				'success' => false,
				'message' => 'Payment gateway is not configured: ' . $gatewayName,
			);
		}

		return $gateway->processPayment( $paymentData );
	}

	/**
	 * Verify a payment
	 *
	 * @param string $gatewayName Payment gateway
	 * @param string $transactionId Transaction ID to verify
	 *
	 * @return array Verification result
	 */
	public static function verifyPayment( string $gatewayName, string $transactionId ): array {
		self::init();
		$gateway = PaymentGatewayFactory::create( $gatewayName );

		if ( ! $gateway ) {
			return array(
				'success' => false,
				'message' => 'Invalid payment gateway: ' . $gatewayName,
			);
		}

		return $gateway->verifyPayment( $transactionId );
	}

	/**
	 * Refund a payment
	 *
	 * @param string $gatewayName Payment gateway
	 * @param string $transactionId Transaction ID to refund
	 * @param float $amount Amount to refund (0 for full refund)
	 *
	 * @return array Refund result
	 */
	public static function refundPayment( string $gatewayName, string $transactionId, float $amount = 0 ): array {
		$gateway = PaymentGatewayFactory::create( $gatewayName );

		if ( ! $gateway ) {
			return array(
				'success' => false,
				'message' => 'Invalid payment gateway: ' . $gatewayName,
			);
		}

		return $gateway->refundPayment( $transactionId, $amount );
	}

	/**
	 * Capture PayPal order (after approval)
	 *
	 * @param string $orderId PayPal order ID
	 *
	 * @return array Capture result
	 */
	public static function capturePayPalOrder( string $orderId ): array {
		self::init();
		$gateway = PaymentGatewayFactory::create( 'paypal' );

		if ( ! $gateway || ! ( $gateway instanceof PayPalPaymentGateway ) ) {
			return array(
				'success' => false,
				'message' => 'PayPal gateway not available',
			);
		}

		return $gateway->captureOrder( $orderId );
	}

	/**
	 * Mark offline payment as completed
	 *
	 * @param string $transactionId Transaction ID
	 * @param array $details Additional details
	 *
	 * @return array Result
	 */
	public static function markOfflinePaymentCompleted( string $transactionId, array $details = array() ): array {
		$gateway = PaymentGatewayFactory::create( 'offline' );

		if ( ! $gateway || ! ( $gateway instanceof OfflinePaymentGateway ) ) {
			return array(
				'success' => false,
				'message' => 'Offline gateway not available',
			);
		}

		return $gateway->markAsCompleted( $transactionId, $details );
	}

	/**
	 * Get available payment methods
	 *
	 * @return array Array of available and configured payment methods
	 */
	public static function getAvailablePaymentMethods(): array {
		$methods  = array();
		$gateways = PaymentGatewayFactory::getAvailableGateways();

		foreach ( $gateways as $gatewayName ) {
			if ( PaymentGatewayFactory::isGatewayConfigured( $gatewayName ) ) {
				$methods[] = array(
					'id'         => $gatewayName,
					'label'      => self::getGatewayLabel( $gatewayName ),
					'configured' => true,
				);
			}
		}

		return $methods;
	}

	/**
	 * Get gateway label
	 *
	 * @param string $gatewayName Gateway name
	 *
	 * @return string Human-readable label
	 */
	private static function getGatewayLabel( string $gatewayName ): string {
		$labels = array(
			'stripe'  => 'Credit/Debit Card',
			'paypal'  => 'PayPal',
			'offline' => 'Pay at Location',
		);

		return $labels[ $gatewayName ] ?? ucfirst( $gatewayName );
	}
	/**
	 * Create Payment Intent (for frontend card collection)
	 *
	 * @param string $gatewayName Payment gateway
	 * @param array $intentData Intent data
	 *
	 * @return array Response with client_secret
	 */
	public static function createPaymentIntent( string $gatewayName, array $intentData ): array {
		self::init();
		$gateway = PaymentGatewayFactory::create( $gatewayName );
		if ( ! $gateway ) {
			return array(
				'success' => false,
				'message' => 'Invalid payment gateway: ' . $gatewayName,
				'error'   => true,
			);
		}

		if ( ! $gateway->isConfigured() ) {
			return array(
				'success' => false,
				'message' => 'Payment gateway is not configured: ' . $gatewayName,
				'error'   => true,
			);
		}

		// Only Stripe supports payment intents for now
		if ( $gatewayName === 'stripe' && method_exists( $gateway, 'createPaymentIntent' ) ) {
			return $gateway->createPaymentIntent( $intentData );
		}

		return array(
			'success' => false,
			'message' => 'Payment intent creation not supported for this gateway',
			'error'   => true,
		);
	}

	/**
	 * Confirm Payment Intent
	 *
	 * @param string $gatewayName Payment gateway
	 * @param string $paymentIntentId Payment Intent ID
	 *
	 * @return array Confirmation result
	 */
	public static function confirmPaymentIntent( string $gatewayName, string $paymentIntentId ): array {
		self::init();
		$gateway = PaymentGatewayFactory::create( $gatewayName );

		if ( ! $gateway ) {
			return array(
				'success' => false,
				'message' => 'Invalid payment gateway: ' . $gatewayName,
			);
		}

		if ( $gatewayName === 'stripe' && method_exists( $gateway, 'confirmPaymentIntent' ) ) {
			return $gateway->confirmPaymentIntent( $paymentIntentId );
		}

		return array(
			'success' => false,
			'message' => 'Payment intent confirmation not supported for this gateway',
		);
	}

	/**
	 * Creates a PayPal order using the provided order data.
	 *
	 * @param array $orderData An associative array containing order information required for creating a PayPal order.
	 *
	 * @return array An associative array indicating the success or failure of the operation,
	 *               including a success status and an optional message.
	 */
	public static function createPayPalOrder( array $orderData ): array {
		self::init();
		$gateway = PaymentGatewayFactory::create( 'paypal' );

		if ( ! $gateway || ! ( $gateway instanceof PayPalPaymentGateway ) ) {
			return array(
				'success' => false,
				'message' => 'PayPal gateway not available',
			);
		}

		if ( ! $gateway->isConfigured() ) {
			return array(
				'success' => false,
				'message' => 'PayPal is not configured',
			);
		}

		return $gateway->createOrder( $orderData );
	}
}
