<?php
/**
 * Form-source REST controller.
 *
 * @package RewindBrevoFormBridge
 */

namespace RewindBrevoFormBridge\Rest\Controllers;

use RewindBrevoFormBridge\Adapters\Registry;
use RewindBrevoFormBridge\Rest\BaseController;

defined( 'ABSPATH' ) || exit;

/**
 * GET /rbfb/v1/forms and GET /rbfb/v1/forms/{adapter}/{id}/fields.
 *
 * Every route here reads the installed form plugin locally. Nothing in this
 * controller touches Brevo.
 *
 * @since 0.4.0
 */
class FormsController extends BaseController {

	/**
	 * Adapter registry.
	 *
	 * @var Registry
	 */
	private Registry $registry;

	/**
	 * Constructor.
	 *
	 * @since 0.4.0
	 * @param Registry $registry Adapter registry.
	 */
	public function __construct( Registry $registry ) {
		parent::__construct( 'forms' );

		$this->registry = $registry;
	}

	/**
	 * Register routes.
	 *
	 * @since 0.4.0
	 * @return void
	 */
	public function register_routes(): void {
		register_rest_route(
			self::NAMESPACE_V1,
			'/' . $this->rest_base,
			array(
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_forms' ),
				'permission_callback' => array( $this, 'can_manage' ),
				'args'                => array(
					'adapter' => array(
						'type'              => 'string',
						'required'          => false,
						'sanitize_callback' => 'sanitize_key',
					),
				),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/' . $this->rest_base . '/(?P<adapter>[a-z0-9_-]+)/(?P<form_id>[A-Za-z0-9_-]+)/fields',
			array(
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_fields' ),
				'permission_callback' => array( $this, 'can_manage' ),
				'args'                => array(
					'adapter' => array(
						'type'              => 'string',
						'required'          => true,
						'sanitize_callback' => 'sanitize_key',
					),
					'form_id' => array(
						'type'              => 'string',
						'required'          => true,
						'sanitize_callback' => array( $this, 'sanitize_text' ),
					),
				),
			)
		);
	}

	/**
	 * Available adapters, and the forms of one adapter when asked.
	 *
	 * @since 0.4.0
	 * @param \WP_REST_Request $request Request.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public function get_forms( \WP_REST_Request $request ) {
		$adapters = array();

		foreach ( $this->registry->available() as $adapter ) {
			$adapters[] = array(
				'slug'  => $adapter->slug(),
				'label' => $adapter->label(),
			);
		}

		$slug = (string) $request->get_param( 'adapter' );

		if ( '' === $slug ) {
			return $this->respond(
				array(
					'adapters' => $adapters,
					'forms'    => array(),
				)
			);
		}

		$adapter = $this->registry->get( $slug );

		if ( null === $adapter || ! $adapter->is_available() ) {
			return $this->error(
				'rbfb_adapter_unavailable',
				__( 'That form plugin is not active on this site.', 'rewind-form-bridge-for-brevo' ),
				self::HTTP_NOT_FOUND
			);
		}

		return $this->respond(
			array(
				'adapters' => $adapters,
				'forms'    => $adapter->get_forms(),
			)
		);
	}

	/**
	 * The mappable fields of one form.
	 *
	 * @since 0.4.0
	 * @param \WP_REST_Request $request Request.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public function get_fields( \WP_REST_Request $request ) {
		$slug    = (string) $request->get_param( 'adapter' );
		$form_id = (string) $request->get_param( 'form_id' );

		$adapter = $this->registry->get( $slug );

		if ( null === $adapter || ! $adapter->is_available() ) {
			return $this->error(
				'rbfb_adapter_unavailable',
				__( 'That form plugin is not active on this site.', 'rewind-form-bridge-for-brevo' ),
				self::HTTP_NOT_FOUND
			);
		}

		$fields = $adapter->get_fields( $form_id );

		if ( 0 === count( $fields ) ) {
			return $this->error(
				'rbfb_form_not_found',
				__( 'That form has no mappable fields, or no longer exists in the form plugin.', 'rewind-form-bridge-for-brevo' ),
				self::HTTP_NOT_FOUND
			);
		}

		return $this->respond( array( 'fields' => $fields ) );
	}
}
