<?php
// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

/**
 * WooCommerce One Page Checkout integration class.
 * https://woocommerce.com/products/woocommerce-one-page-checkout/
 *
 * Last compatibility check: 2.8.2
 */
class WC_Appointments_Integration_WCOPC implements WC_Appointments_Integration_Interface {

	/**
	 * Constructor
	 */
	public function __construct() {
		$this->add_hooks();
	}

	/**
	 * Register WordPress hooks for this integration.
	 *
	 * @return void
	 */
	public function add_hooks(): void {
		add_action( 'wcopc_appointment_add_to_cart', [ self::class, 'opc_single_add_to_cart_appointment' ] );

		// Unhook 'WC_Appointments_Cart::add_to_cart_redirect'
		// from 'add_to_cart_redirect' in OPC pages, to prevent redirection
		// to the default cart when checking appointment availability
		if (
			isset( $_POST['is_opc'] )
			&& (
			    ( isset( $_REQUEST['action'] ) && 'woocommerce_checkout' === $_REQUEST['action'] )
				||
				( isset( $_REQUEST['wc-ajax'] ) && 'checkout' === $_REQUEST['wc-ajax'] )
			)
		) {
			remove_action( 'add_to_cart_redirect', 'WC_Appointments_Cart::add_to_cart_redirect' );
		}
	}

 	/**
      * OPC Single-product appointments add-to-cart template
      *
      * @param  int  $opc_post_id
      */
     public static function opc_single_add_to_cart_appointment( $opc_post_id ): void {
 		global $product;

 		ob_start();

 		// Prepare form
 		$appointment_form = new WC_Appointment_Form( $product );

		// Get template
		wc_get_template(
		    'single-product/add-to-cart/appointment.php',
		    [
				'appointment_form' => $appointment_form,
			],
		    '',
		    WC_APPOINTMENTS_TEMPLATE_PATH,
		);

 		echo str_replace(
 		    [ '<form class="cart" method="post" enctype=\'multipart/form-data\'', '</form>' ],
 		    [ '<div class="cart" ', '</div>' ],
 		    ob_get_clean(),
 		); // WPCS: XSS ok.
 	}
}
