<?php
namespace JET_APB\Rest_API;

use JET_APB\Plugin;

class Endpoint_Service_Providers extends \Jet_Engine_Base_API_Endpoint {

	/**
	 * Returns route name
	 *
	 * @return string
	 */
	public function get_name() {
		return 'appointment-service-providers';
	}

	/**
	 * API callback
	 *
	 */
	public function callback( $request ) {

		$params                    = $request->get_params();
		$service                   = ! empty( $params['service'] ) ? absint( $params['service'] ) : 0;
		$custom_template           = ! empty( $params['custom_template'] ) ? absint( $params['custom_template'] ) : 0;
		$args_str                  = ! empty( $params['args_str'] ) ? $params['args_str'] : '';
		$is_ajax                   = ! empty( $params['is_ajax'] ) ? $params['is_ajax'] : false;
		$namespace                 = ! empty( $params['namespace'] ) ? $params['namespace'] : 'jet-form';
		$default                   = ! empty( $params['default'] ) ? $params['default'] : '';
		$calculated_value_from_key = ! empty( $params['calculated_value_from_key'] ) ? sanitize_key( $params['calculated_value_from_key'] ) : '';

		if ( ! $service ) {
			return rest_ensure_response( array(
				'success' => false,
			) );
		}

		$providers = Plugin::instance()->tools->get_providers_for_service( $service, $calculated_value_from_key );

		if ( ! $custom_template ) {
			return rest_ensure_response( array(
				'success' => true,
				'data'    => $providers,
			) );
		} else {

			$builder = $this->get_namespace_provider( $namespace );
			$checked = null;
			$result  = array();

			if ( $is_ajax && $custom_template ) {

				$is_blocks_template   = Plugin::instance()->blocks->is_blocks_template( $custom_template );
				$is_bricks_template   = Plugin::instance()->bricks->is_bricks_template( $custom_template );
				$has_template_runtime = Plugin::instance()->elementor->has_template_runtime();
				
				ob_start();
				
				if ( ! $is_blocks_template && ! $is_bricks_template && $has_template_runtime ) {
					Plugin::instance()->elementor->print_template_css( $custom_template );
				}

				if ( $is_blocks_template ) {
					Plugin::instance()->blocks->print_template_styles( $custom_template );
				}

				$result[] = ob_get_clean();
			}

			foreach ( $providers as $provider ) {

				$calculated_value = null;
				if ( isset( $provider->meta_value ) && '' !== $provider->meta_value ) {
					$calculated_value = $provider->meta_value;
				} else {
					$calculated_value = get_post_meta( $provider->ID, $calculated_value_from_key, true );
				}
				$checked = checked( $default, $provider->ID, false );
				$args    = array(
					'field_options_from'      => 'posts',
					'custom_item_template_id' => $custom_template,
				);

				ob_start();

				$template    = $builder->get_custom_template( $provider->ID, $args, $checked );
				$data_switch = null;

				?>
                <div class="<?= esc_html( $namespace ) ?>__field-wrap radio-wrap checkradio-wrap">
					<?php if ( $template ) {
						echo $template; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
					} ?>
                    <label class="<?= esc_html( $namespace ) ?>__field-label">
                        <input
                                type="radio"
                                class="<?= esc_html( $namespace ) ?>__field radio-field checkradio-field"
                                value="<?php echo esc_html( $provider->ID ); ?>"
								data-calculate="<?php echo esc_attr( $calculated_value ) ?>"
							<?php echo wp_kses_data( $checked ); ?>
							<?php echo wp_kses_data( $args_str ); ?>
							<?php echo esc_attr( $data_switch ); ?>
                        >
                    </label>
                </div>
				<?php

				$result[] = ob_get_clean();

			}


			return rest_ensure_response( array(
				'success' => true,
				'data'    => implode( '', $result ),
			) );

		}


	}

	/**
	 * Returns endpoint request method - GET/POST/PUT/DELTE
	 *
	 * @return string
	 */
	public function get_method() {
		return 'GET';
	}

	/**
	 * Returns arguments config
	 *
	 * @return array
	 */
	public function get_args() {
		return array(
			'service'                   => array(
				'default'  => '',
				'required' => true,
			),
			'custom_template'           => array(
				'default'  => '',
				'required' => false,
			),
			'args_str'                  => array(
				'default'  => '',
				'required' => false,
			),
			'calculated_value_from_key' => array(
				'default'           => '',
				'required'          => false,
				'sanitize_callback' => 'sanitize_key',
				'validate_callback' => function ( $value ) {
					return true;
				},
			),
		);
	}

	private function get_namespace_provider( $namespace ) {
		if ( 'jet-form-builder' === $namespace && class_exists( '\Jet_Form_Builder\Classes\Builder_Helper' ) ) {
			return new \Jet_Form_Builder\Classes\Builder_Helper();
		}

		if ( ! class_exists( '\Jet_Engine_Booking_Forms_Builder' ) ) {
			require_once jet_engine()->modules->modules_path( 'forms/builder.php' );
		}

		return new \Jet_Engine_Booking_Forms_Builder();
	}

}
