<?php

namespace SugarCalendarBookings\Payments\Admin;

use SugarCalendarBookings\Options;
use SugarCalendarBookings\Payments\Gateways\Onsite\OnSitePaymentGateway;
use SugarCalendarBookings\Payments\Gateways\PaymentGatewayRegistry;
use SugarCalendarBookings\Plugin;
use SugarCalendarBookings\Support\Helpers\UI;

/**
 * Payment Methods Section.
 *
 * Displays the payment gateways overview section in the Payments Settings.
 *
 * @since 1.0.0
 */
class PaymentMethodsSection {

	/**
	 * Gateway icon mapping.
	 *
	 * @since 1.0.0
	 *
	 * @var array
	 */
	private $gateway_icons = [
		'stripe' => 'assets/images/icons/payment-gateways/stripe.svg',
		'onsite' => 'assets/images/icons/payment-gateways/onsite.svg',
	];

	/**
	 * Display section content.
	 *
	 * @since 1.0.0
	 */
	public function display_content() {

		// Display heading.
		UI::heading(
			[
				'title'       => esc_html__( 'Payment Methods', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
				'description' => esc_html__( 'Select the payment methods you wish to support for your services.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
			]
		);

		// Get registered payment gateways.
		$gateways = $this->get_gateways_data();

		// Display payment gateways list.
		$this->render_gateways_list( $gateways );
	}

	/**
	 * Get gateways data for rendering.
	 *
	 * @since 1.0.0
	 *
	 * @return array
	 */
	private function get_gateways_data() {

		$options = Plugin::get( Options::class );

		return array_map(
			function ( $gateway ) use ( $options ) {
				$gateway_id  = $gateway::get_id();
				$is_readonly = $this->is_gateway_readonly( $gateway_id, $options );
				$enabled     = (bool) $options->get( "payments.gateways.{$gateway_id}.enabled" );

				// If gateway is readonly, it must be shown as enabled.
				if ( $is_readonly ) {
					$enabled = true;
				}

				return [
					'id'         => $gateway_id,
					'name'       => $gateway::get_name(),
					'configured' => $gateway->is_configured(),
					'enabled'    => $enabled,
					'readonly'   => $is_readonly,
				];
			},
			array_values( Plugin::get( PaymentGatewayRegistry::class )->get_registered() )
		);
	}

	/**
	 * Determine if a gateway should be readonly.
	 *
	 * @since 1.0.0
	 *
	 * @param string  $gateway_id Gateway ID.
	 * @param Options $options    Options instance.
	 *
	 * @return bool
	 */
	private function is_gateway_readonly( $gateway_id, $options ) {

		// Only onsite gateway has readonly logic.
		if ( $gateway_id !== OnSitePaymentGateway::ID ) {
			return false;
		}

		$registry            = Plugin::get( PaymentGatewayRegistry::class );
		$registered_gateways = $registry->get_registered();

		// Check if Stripe gateway exists and is configured.
		$stripe_gateway = $registered_gateways['stripe'] ?? null;

		if ( ! $stripe_gateway ) {
			return true; // No Stripe gateway available, onsite should be readonly.
		}

		$stripe_configured = $stripe_gateway->is_configured();

		if ( ! $stripe_configured ) {
			return true; // Stripe not configured, onsite should be readonly.
		}

		$stripe_enabled = (bool) $options->get( 'payments.gateways.stripe.enabled' );

		if ( ! $stripe_enabled ) {
			return true; // Stripe configured but disabled, onsite should be readonly.
		}

		// Stripe is configured and enabled, onsite can be edited.
		return false;
	}

	/**
	 * Render payment gateways list.
	 *
	 * @since 1.0.0
	 *
	 * @param array $gateways List of gateways.
	 */
	private function render_gateways_list( $gateways ) {

		?>

		<div class="sugar-calendar-bookings-setting-row">
			<div class="sugar-calendar-bookings-payment-methods-table">
				<?php foreach ( $gateways as $gateway ) : ?>
					<?php $this->render_gateway_item( $gateway ); ?>
				<?php endforeach; ?>
			</div>
		</div>

		<?php
	}

	/**
	 * Render a single gateway item.
	 *
	 * @since 1.0.0
	 *
	 * @param array $gateway Gateway data.
	 */
	private function render_gateway_item( $gateway ) {

		$icon        = $this->get_gateway_icon( $gateway['id'] );
		$is_stripe   = $gateway['id'] === 'stripe';
		$description = $this->get_gateway_description( $gateway['id'] );
		?>

		<div class="sugar-calendar-bookings-payment-method-row">
			<div class="sugar-calendar-bookings-payment-method-content">
				<?php if ( ! empty( $icon ) ) : ?>
					<div class="sugar-calendar-bookings-payment-method-icon">
						<img src="<?php echo esc_url( $icon ); ?>" alt="<?php echo esc_attr( $gateway['name'] ); ?>" />
					</div>
				<?php endif; ?>

				<div class="sugar-calendar-bookings-payment-method-info">
					<div class="sugar-calendar-bookings-payment-method-title">
						<?php if ( $is_stripe ) : ?>
							<a href="#sugar-calendar-bookings-setting-row-stripe">
								<?php echo esc_html( $gateway['name'] ); ?>
							</a>
						<?php else : ?>
							<span><?php echo esc_html( $gateway['name'] ); ?></span>
						<?php endif; ?>
					</div>

					<?php if ( ! empty( $description ) ) : ?>
						<div class="sugar-calendar-bookings-payment-method-description">
							<?php echo esc_html( $description ); ?>
						</div>
					<?php endif; ?>
				</div>
			</div>

			<div class="sugar-calendar-bookings-payment-method-action">
				<?php $this->render_gateway_actions( $gateway ); ?>
			</div>
		</div>

		<?php
	}

	/**
	 * Render gateway actions based on type and state.
	 *
	 * @since 1.0.0
	 *
	 * @param array $gateway Gateway data.
	 */
	private function render_gateway_actions( $gateway ) {

		$gateway_id    = $gateway['id'];
		$is_stripe     = $gateway_id === 'stripe';
		$is_configured = ! empty( $gateway['configured'] );

		// Stripe: Not configured - Show Connect button.
		if ( $is_stripe && ! $is_configured ) {
			?>
			<a href="#sugar-calendar-bookings-setting-row-stripe" class="sugar-calendar-bookings-payment-method-connect">
				<?php esc_html_e( 'Connect', 'sugar-calendar-bookings-scheduling-appointments-lite' ); ?>
			</a>
			<?php

			return;
		}

		// Stripe: Configured - Show Edit button + Toggle.
		if ( $is_stripe && $is_configured ) {
			?>
			<a href="#sugar-calendar-bookings-setting-row-stripe" class="sugar-calendar-bookings-payment-method-edit">
				<?php esc_html_e( 'Edit', 'sugar-calendar-bookings-scheduling-appointments-lite' ); ?>
			</a>
			<?php
			$this->render_gateway_toggle( $gateway );

			return;
		}

		// On-Site: Always show Toggle.
		$this->render_gateway_toggle( $gateway );
	}

	/**
	 * Render gateway toggle control.
	 *
	 * @since 1.0.0
	 *
	 * @param array $gateway Gateway data.
	 */
	private function render_gateway_toggle( $gateway ) {

		$gateway_id = $gateway['id'];

		UI::toggle_control(
			[
				'id'       => "payment_gateway_{$gateway_id}_enabled",
				'name'     => "sugar-calendar-bookings[payments][gateways][{$gateway_id}][enabled]",
				'value'    => $gateway['enabled'],
				'disabled' => $gateway['readonly'],
			],
			true
		);
	}

	/**
	 * Get gateway icon URL.
	 *
	 * @since 1.0.0
	 *
	 * @param string $gateway_id Gateway ID.
	 *
	 * @return string
	 */
	private function get_gateway_icon( $gateway_id ) {

		if ( ! isset( $this->gateway_icons[ $gateway_id ] ) ) {
			return '';
		}

		return SCBOOKINGS_PLUGIN_URL . $this->gateway_icons[ $gateway_id ];
	}

	/**
	 * Get gateway description.
	 *
	 * @since 1.0.0
	 *
	 * @param string $gateway_id Gateway ID.
	 *
	 * @return string
	 */
	private function get_gateway_description( $gateway_id ) {

		$descriptions = [
			'onsite' => esc_html__( 'Enable to collect payments offline in person', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
			'stripe' => esc_html__( 'Enable to collect online payments via card and more', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
		];

		return $descriptions[ $gateway_id ] ?? '';
	}
}
