<?php

namespace SugarCalendarBookings\Payments\Gateways\Onsite;

use SugarCalendarBookings\Plugin;
use SugarCalendarBookings\Services\ServiceModel;
use SugarCalendarBookings\Support\Bootable;

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

/**
 * Class OnSiteProvider.
 *
 * @since 1.0.0
 */
class OnSiteProvider implements Bootable {

	/**
	 * Payment gateway.
	 *
	 * @since 1.0.0
	 *
	 * @var OnSitePaymentGateway
	 */
	private $gateway;

	/**
	 * Constructor.
	 *
	 * @since 1.0.0
	 *
	 * @param OnSitePaymentGateway $gateway Payment gateway.
	 */
	public function __construct( $gateway ) {

		$this->gateway = $gateway;
	}

	/**
	 * Register hooks.
	 *
	 * @since 1.0.0
	 */
	public function hooks() {

		add_filter(
			'sugar_calendar_bookings_booking_form_payment_gateways',
			[ $this, 'get_booking_form_gateway_data' ]
		);

		add_filter(
			'sugar_calendar_bookings_booking_form_service_payment_gateways',
			[ $this, 'get_booking_form_service_gateway_data' ],
			10,
			2
		);
	}

	/**
	 * Get booking form payment gateway data.
	 *
	 * @since 1.0.0
	 *
	 * @param array $payment_gateways Payment gateways data.
	 *
	 * @return array
	 */
	public function get_booking_form_gateway_data( $payment_gateways ) {

		$payment_gateways[ $this->gateway::get_id() ] = [];

		return $payment_gateways;
	}

	/**
	 * Get booking form service payment gateway data.
	 *
	 * @since 1.0.0
	 *
	 * @param array        $payment_gateways Payment gateways data.
	 * @param ServiceModel $service          Service model instance.
	 *
	 * @return array
	 */
	public function get_booking_form_service_gateway_data( $payment_gateways, $service ) {

		// Only add onsite if it's explicitly in the service's payment gateways
		// or if the service has override enabled and onsite is in the selection.
		$override_enabled = Plugin::instance()->is_pro() && ( $service->override_payment_methods ?? false );

		if ( $override_enabled && in_array( $this->gateway::get_id(), $service->payment_gateways, true ) ) {
			$payment_gateways[ $this->gateway::get_id() ] = [];
		} elseif ( ! $override_enabled && isset( $payment_gateways[ $this->gateway::get_id() ] ) ) {
			// When override is disabled, only add if it's already in the global defaults.
			$payment_gateways[ $this->gateway::get_id() ] = [];
		}

		return $payment_gateways;
	}
}
