<?php
/**
 * Form Shortcode
 *
 * @author    Wpayme <hi@wpayme.com>
 * @copyright 2024-2025 Wpayme
 * @license   GPL-3.0-or-later
 * @package   Wpayme\WordPress\Pay\Forms
 */

namespace Wpayme\WordPress\Pay\Forms;

/**
 * Form Shortcode
 *
 * @author  Remco Tolsma
 * @version 2.2.6
 * @since   3.7.0
 */
class FormShortcode {
	/**
	 * Forms integration.
	 *
	 * @var Integration
	 */
	private $integration;

	/**
	 * Constructs and initializes an post types object.
	 *
	 * @param Integration $integration Reference to the forms integration.
	 */
	public function __construct( Integration $integration ) {
		$this->integration = $integration;

		add_shortcode( 'wpayme_payment_form', [ $this, 'shortcode_form' ] );
		add_shortcode( 'wpayme_pay_form', [ $this, 'shortcode' ] );
		add_shortcode( 'wpayme_simple_form', [ $this, 'simple_shortcode' ] );
	}

	/**
	 * Shortcode form.
	 *
	 * @link https://github.com/WordImpress/Give/blob/1.1/includes/shortcodes.php#L39-L65
	 * @link https://github.com/WordImpress/Give/blob/1.1/includes/forms/template.php#L18-L140
	 *
	 * @param array $atts Shortcode attributes array.
	 *
	 * @return string
	 *
	 * @throws \Exception Throws exception if output buffering is not active.
	 */
	public function shortcode_form( $atts ) {
		$atts = shortcode_atts(
			[
				'id' => null,
			],
			$atts,
			'wpayme_payment_form'
		);

		if ( empty( $atts['id'] ) ) {
			return '';
		}

		return $this->integration->get_form_output_by_id( (int) $atts['id'] );
	}

	/**
	 * Shortcode
	 *
	 * @param array $atts Attributes.
	 * @return string
	 */
	public function shortcode($atts) {
		$atts = shortcode_atts(
			array(
				'id' => null,
			),
			$atts,
			'wpayme_pay_form'
		);

		if (empty($atts['id'])) {
			return '<p class="wpayme-pay-error">' . esc_html__('Error: Missing form ID.', 'wpayme') . '</p>';
		}

		$form_id = intval($atts['id']);

		// Get form output
		$integration = new Integration();
		$output = $integration->get_form_output_by_id($form_id);

		if (empty($output)) {
			return '<p class="wpayme-pay-error">' . esc_html__('Error: Form not found.', 'wpayme') . '</p>';
		}

		return $output;
	}

	/**
	 * Simple form shortcode
	 *
	 * @param array $atts Attributes.
	 * @return string
	 */
	public function simple_shortcode($atts) {
		$atts = shortcode_atts(
			array(
				'id' => null,
			),
			$atts,
			'wpayme_simple_form'
		);

		if (empty($atts['id'])) {
			return '<p class="wpayme-pay-error">' . esc_html__('Error: Missing form ID.', 'wpayme') . '</p>';
		}

		$form_id = intval($atts['id']);

		// Get form output
		return $this->integration->get_simple_form_output(array('form_id' => $form_id));
	}
}
