<?php
namespace JET_ABAF\Render;

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

class Booking_Form extends Base {

	/**
	 * Render booking form widget content.
	 *
	 * @since 4.1.0
	 *
	 * @return void
	 * @throws \Exception
	 */
	public function render() {

		$settings = wp_parse_args( $this->get_settings(), $this->get_default_settings() );
		$post_id  = absint( $settings['booking_instance_id'] ?: get_the_ID() );

		$this->setup_post_context( $post_id );

		$field_data = $this->prepare_field_data( $settings, $post_id );

		wp_localize_script( 'jquery-date-range-picker', 'JetABAFInput', [
			'layout'        => $settings['field_layout'],
			'field_format'  => $field_data['field_format'],
			'start_of_week' => $settings['field_start_of_week'],
			'options'       => $field_data['options'],
		] );

		wp_enqueue_style( 'jet-booking-widget-booking-form' );

		$this->render_form( $settings, $field_data, $post_id );

	}

	/**
	 * Get default booking form settings.
	 *
	 * @since 4.1.0
	 *
	 * @return array
	 */
	private function get_default_settings() {
		return [
			'booking_instance_id'         => '',
			'disable_email_field'         => false,
			'field_layout'                => 'single',
			'field_position'              => 'inline',
			'field_label'                 => '',
			'field_placeholder'           => 'YYYY-MM-DD',
			'check_in_field_label'        => '',
			'check_in_field_placeholder'  => 'YYYY-MM-DD',
			'check_out_field_label'       => '',
			'check_out_field_placeholder' => 'YYYY-MM-DD',
			'field_description'           => '',
			'field_date_format'           => 'YYYY-MM-DD',
			'field_separator'             => '-',
			'field_start_of_week'         => 'monday',
			'submit_button_label'         => __( 'Book', 'jet-booking' ),
			'is_preview'                  => false,
		];
	}

	/**
	 * Prepare rendered field values and metadata.
	 *
	 * @since 4.1.0
	 *
	 * @param array $settings Widget settings.
	 * @param int   $post_id  Booking instance ID.
	 *
	 * @return array
	 * @throws \Exception
	 */
	private function prepare_field_data( $settings, $post_id ) {

		$field_format    = $settings['field_date_format'];
		$field_separator = $settings['field_separator'];

		if ( $field_separator ) {
			$field_separator = 'space' === $field_separator ? ' ' : $field_separator;
			$field_format    = str_replace( '-', $field_separator, $field_format );
		}

		$default_value = '';
		$options       = jet_abaf()->tools->get_field_default_value( $default_value, $field_format, $post_id );
		$checkin       = '';
		$checkout      = '';

		if ( ! empty( $options ) ) {
			$checkin  = $options['checkin'] ?? '';
			$checkout = $options['checkout'] ?? '';

			if ( $checkin && $checkout ) {
				$default_value = jet_abaf()->settings->is_one_day_bookings( $post_id ) ? $checkin : $checkin . ' - ' . $checkout;
			}
		}

		return [
			'field_format'  => $field_format,
			'options'       => $options,
			'default_value' => $default_value,
			'checkin'       => $checkin,
			'checkout'      => $checkout,
		];

	}

	/**
	 * Render booking form.
	 *
	 * @since 4.1.0
	 *
	 * @param array $settings   Widget settings.
	 * @param array $field_data Prepared field data.
	 * @param int   $post_id    Booking instance ID.
	 *
	 * @return void
	 */
	private function render_form( $settings, $field_data, $post_id ) {

		$is_preview = filter_var( $settings['is_preview'], FILTER_VALIDATE_BOOLEAN );
		?>
		<div class="jet-abaf-booking-form-wrap">
			<div class="jet-abaf-booking-form__general-notices" aria-live="polite">
				<?php $this->render_general_notices( $settings ); ?>
			</div>

			<form class="jet-booking-form" method="post" data-is-preview="<?php echo esc_attr( $is_preview ? '1' : '0' ); ?>" novalidate>
				<input type="hidden" name="jet_abaf_booking_instance_id" value="<?php echo esc_attr( $post_id ); ?>"/>

				<?php
					wp_nonce_field( 'jet_abaf_booking_form_' . absint( $post_id ), 'jet_abaf_booking_form_nonce', false );

					$this->render_date_field( $settings, $field_data );

					if ( ! filter_var( $settings['disable_email_field'], FILTER_VALIDATE_BOOLEAN ) ) {
						include JET_ABAF_PATH . 'templates/form-fields/email-field.php';
					}
				?>

				<button type="<?php echo esc_attr( ! $is_preview ? 'submit' : 'button' ); ?>" class="jet-abaf-booking-form__submit">
					<span class="jet-abaf-booking-form__submit-label"><?php echo esc_html( $settings['submit_button_label'] ); ?></span>
				</button>
			</form>

			<div class="jet-abaf-booking-form__submit-notices" aria-live="polite"></div>
		</div>
		<?php
	}

	/**
	 * Render the date field using shared templates.
	 *
	 * @since 4.1.0
	 *
	 * @param array $settings   Widget settings.
	 * @param array $field_data Prepared field data.
	 *
	 * @return void
	 */
	private function render_date_field( $settings, $field_data ) {

		$field_classes = [ 'jet-abaf-field__input', 'input-text', 'text' ];
		$args          = [ 'name' => 'jet_abaf_field', 'required' => true ];
		$attrs         = '';

		echo '<div class="jet-abaf-product-check-in-out">';

		if ( 'single' === $settings['field_layout'] ) {
			$classes     = [ 'jet-abaf-field' ];
			$placeholder = $settings['field_placeholder'];
			$label       = $settings['field_label'];

			if ( jet_abaf()->settings->get( 'timepicker' ) ) {
				$classes[] = 'jet-abaf-field--has-timepicker';
			}

			if ( $label ) {
				printf(
					'<div class="jet-abaf-field__label"><label for="jet_abaf_field">%1$s <span class="jet-abaf-field__required">&nbsp;<abbr class="required" title="required">*</abbr></span></label></div>',
					esc_html( $label )
				);
			}

			$field_format  = $field_data['field_format'];
			$default_value = $field_data['default_value'];

			include JET_ABAF_PATH . 'templates/form-field-single.php';
		} else {
			$fields_position      = $settings['field_position'];
			$checkin_label        = $settings['check_in_field_label'];
			$checkin_placeholder  = $settings['check_in_field_placeholder'];
			$checkout_label       = $settings['check_out_field_label'];
			$checkout_placeholder = $settings['check_out_field_placeholder'];
			$label_classes        = [ 'jet-abaf-separate-field__label' ];
			$required_classes     = [ 'jet-abaf-field__required' ];
			$col_classes          = [ 'jet-abaf-separate-field' ];
			$field_format         = $field_data['field_format'];
			$default_value        = $field_data['default_value'];
			$checkin              = $field_data['checkin'];
			$checkout             = $field_data['checkout'];

			if ( 'list' === $fields_position ) {
				$col_classes[] = 'jet-abaf-separate-field__list';
			} else {
				$col_classes[] = 'jet-abaf-separate-field__inline';
			}

			if ( jet_abaf()->settings->get( 'timepicker' ) ) {
				$col_classes[] = 'jet-abaf-separate-field--has-timepicker';
			}

			include JET_ABAF_PATH . 'templates/form-field-separate.php';
		}

		if ( $settings['field_description'] ) {
			printf( '<div class="jet-abaf-field__desc"><small>%1$s</small></div>', esc_html( $settings['field_description'] ) );
		}

		echo '</div>';

	}

	/**
	 * Render general notices displayed above the form.
	 *
	 * @since 4.1.0
	 *
	 * @param array $settings Widget settings.
	 *
	 * @return void
	 */
	private function render_general_notices( $settings ) {

		if ( ! jet_abaf()->workflows->collection->can_print_form_notice( ! filter_var( $settings['disable_email_field'], FILTER_VALIDATE_BOOLEAN ) ) ) {
			return;
		}

		printf(
			'<div class="jet-abaf-booking-form__notice jet-abaf-booking-form__notice--warning">%s</div>',
			__( 'Workflows are enabled. To ensure proper notification delivery, enable the email field in the Booking Form widget settings.', 'jet-booking' )
		);

	}

}
