<?php
/**
 * Built-in form shortcode.
 *
 * @package SubmissionInbox
 */

namespace SUBIN\Forms;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Registers and renders the built-in form shortcode.
 */
class FormShortcode {
	/**
	 * Form repository.
	 *
	 * @var FormRepository
	 */
	private $forms;

	/**
	 * Field repository.
	 *
	 * @var FormFieldRepository
	 */
	private $fields;

	/**
	 * Renderer.
	 *
	 * @var FormRenderer
	 */
	private $renderer;

	/**
	 * Submission handler.
	 *
	 * @var FormSubmissionHandler
	 */
	private $submission_handler;

	/**
	 * Constructor.
	 *
	 * @param FormRepository        $forms Form repository.
	 * @param FormFieldRepository   $fields Field repository.
	 * @param FormRenderer          $renderer Renderer.
	 * @param FormSubmissionHandler $submission_handler Submission handler.
	 */
	public function __construct( FormRepository $forms, FormFieldRepository $fields, FormRenderer $renderer, FormSubmissionHandler $submission_handler ) {
		$this->forms              = $forms;
		$this->fields             = $fields;
		$this->renderer           = $renderer;
		$this->submission_handler = $submission_handler;
	}

	/**
	 * Register shortcode.
	 *
	 * @return void
	 */
	public function register() {
		add_shortcode( 'submission_inbox_form', array( $this, 'render_shortcode' ) );
	}

	/**
	 * Render shortcode.
	 *
	 * @param array<string,mixed> $atts Shortcode attributes.
	 * @return string
	 */
	public function render_shortcode( $atts ) {
		$atts = shortcode_atts(
			array(
				'id' => 0,
			),
			is_array( $atts ) ? $atts : array(),
			'submission_inbox_form'
		);

		$form_id = absint( $atts['id'] );
		if ( $form_id <= 0 ) {
			return $this->admin_message( __( 'InboxMend form was not found.', 'submission-inbox' ) );
		}

		$form = $this->forms->get( $form_id );
		if ( ! $form ) {
			return $this->admin_message( __( 'InboxMend form was not found.', 'submission-inbox' ) );
		}

		if ( FormRepository::STATUS_ACTIVE !== sanitize_key( $form['status'] ?? '' ) ) {
			return $this->admin_message( __( 'This InboxMend form is inactive.', 'submission-inbox' ) );
		}

		$fields = $this->fields->get_by_form_id( $form_id );
		$result = $this->submission_handler->consume_result_for_form( $form_id );

		return $this->renderer->render( $form, $fields, $result );
	}

	/**
	 * Return a safe admin-only message.
	 *
	 * @param string $message Message.
	 * @return string
	 */
	private function admin_message( $message ) {
		if ( ! current_user_can( 'manage_options' ) ) {
			return '';
		}

		return '<div class="subin-form-admin-message">' . esc_html( $message ) . '</div>';
	}
}
