<?php
/**
 * DESCRIPTION: Server-side render class for the nemtly/booking-calendar Gutenberg block.
 * Enqueues booking form assets and outputs the React mount container for a single event.
 *
 * @since   PBOOKING_SINCE
 * @package NemtlyBooking\Blocks
 */

namespace NemtlyBooking\Blocks;

/**
 * Booking Calendar Block class
 *
 * Renders an inline booking calendar (date picker, time slots, attendee form)
 * for a single event. Reuses the existing BookingForm frontend component.
 *
 * @since PBOOKING_SINCE
 */
class Booking_Calendar extends Abstract_Block {

	/**
	 * Block name
	 *
	 * @var string
	 */
	protected $block_name = 'booking-calendar';

	/**
	 * Render the block on the frontend.
	 *
	 * @since PBOOKING_SINCE
	 *
	 * @param array     $attributes Block attributes.
	 * @param string    $content    Inner block content (unused — dynamic block).
	 * @param \WP_Block $block      Block instance.
	 *
	 * @return string HTML output.
	 */
	public function render( $attributes, $content, $block ) {
		$event_id = ! empty( $attributes['eventId'] ) ? absint( $attributes['eventId'] ) : 0;

		if ( ! $event_id ) {
			return '';
		}

		// Verify event exists and is published.
		$post = get_post( $event_id );
		if ( ! $post || 'nemtly_event' !== $post->post_type || 'publish' !== $post->post_status ) {
			return '';
		}

		$this->enqueue_booking_form_assets();

		$container_id = 'nb-booking-form-' . $event_id . '-' . wp_rand( 1000, 9999 );

		$wrapper_attributes = get_block_wrapper_attributes(
			[
				'id'            => $container_id,
				'class'         => 'nemtly-booking-form-container',
				'data-event-id' => $event_id,
			]
		);

		return sprintf(
			'<div %s><div class="nb-loading">%s</div></div>',
			$wrapper_attributes,
			esc_html__( 'Loading booking form...', 'nemtly-booking' )
		);
	}

	/**
	 * Enqueue the booking form JS/CSS bundle and localize config.
	 *
	 * Guarded by wp_script_is() so repeated calls don't re-enqueue.
	 *
	 * @since PBOOKING_SINCE
	 *
	 * @return void
	 */
	private function enqueue_booking_form_assets() {
		if ( wp_script_is( 'nemtly-booking-form', 'enqueued' ) ) {
			return;
		}

		$plugin_url  = plugin_dir_url( dirname( __DIR__ ) );
		$plugin_path = plugin_dir_path( dirname( __DIR__ ) );

		wp_enqueue_style(
			'nemtly-booking-form-styles',
			$plugin_url . 'assets/css/booking-form.css',
			[],
			NEMTLY_BOOKING_VERSION
		);

		$asset_path = $plugin_path . 'assets/js/booking-form.asset.php';
		$asset      = file_exists( $asset_path ) ? require $asset_path : [
			'dependencies' => [ 'wp-element', 'wp-api-fetch', 'wp-i18n' ],
			'version'      => NEMTLY_BOOKING_VERSION,
		];

		wp_enqueue_script(
			'nemtly-booking-form',
			$plugin_url . 'assets/js/booking-form.js',
			$asset['dependencies'],
			$asset['version'],
			true
		);

		$plugin_settings = get_option( 'nemtly_booking_settings', [] );

		wp_localize_script(
			'nemtly-booking-form',
			'nemtlyBookingAjax',
			[
				'nonce'     => wp_create_nonce( 'nemtly_nonce' ),
				'ajaxUrl'   => admin_url( 'admin-ajax.php' ),
				'restUrl'   => rest_url( 'nemtly-booking/v1/' ),
				'restNonce' => wp_create_nonce( 'wp_rest' ),
				'legal'     => [
					'terms_url'   => esc_url( (string) apply_filters( 'nemtly_booking_terms_url', '' ) ),
					'privacy_url' => esc_url( (string) apply_filters( 'nemtly_booking_privacy_url', (string) get_privacy_policy_url() ) ),
				],
				'strings'   => [
					'loading'        => __( 'Loading...', 'nemtly-booking' ),
					'processing'     => __( 'Processing...', 'nemtly-booking' ),
					'error'          => __( 'An error occurred. Please try again.', 'nemtly-booking' ),
					'success'        => __( 'Booking successful!', 'nemtly-booking' ),
					'confirmBooking' => __( 'Confirm Booking', 'nemtly-booking' ),
					'cancel'         => __( 'Cancel', 'nemtly-booking' ),
					'requiredField'  => __( 'This field is required.', 'nemtly-booking' ),
					'invalidEmail'   => __( 'Please enter a valid email address.', 'nemtly-booking' ),
				],
				'captcha'   => [
					'type'          => $plugin_settings['captcha_type'] ?? 'disabled',
					'site_key'      => 'turnstile' === ( $plugin_settings['captcha_type'] ?? '' )
						? esc_attr( $plugin_settings['turnstile_site_key'] ?? '' )
						: '',
					'site_key_name' => 'turnstile',
				],
			]
		);

		wp_add_inline_script(
			'nemtly-booking-form',
			sprintf(
				'wp.apiFetch.use( wp.apiFetch.createNonceMiddleware( %s ) );',
				wp_json_encode( wp_create_nonce( 'wp_rest' ) )
			),
			'before'
		);

		wp_set_script_translations( 'nemtly-booking-form', 'nemtly-booking' );
	}
}
