<?php
/**
 * Forms Integration
 *
 * @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;

use Wpayme\WordPress\Number\Number;
use Wpayme\WordPress\Pay\AbstractPluginIntegration;
use Wpayme\WordPress\Pay\Payments\Payment;

/**
 * Forms Integration
 *
 * @author Remco Tolsma
 * @version 2.2.6
 * @since 3.7.0
 */
class Integration extends AbstractPluginIntegration {
	/**
	 * Construct and initialize a forms module object.
	 */
	public function __construct() {
		parent::__construct(
			[
				'name'                => __( 'WPayme Forms', 'wpayme' ),
				'version'             => '1.0.1',
				'version_option_name' => 'wpayme_pay_forms_version',
			]
		);

		// Upgrades.
		$version = $this->get_version();

		$upgrades = $this->get_upgrades();

		$upgrades->add( new Install( null === $version ? '1.0.0' : $version ) );

		// Add action to enqueue frontend styles
		add_action('wp_enqueue_scripts', array($this, 'enqueue_frontend_styles'));
		add_action('wp_enqueue_scripts', array($this, 'enqueue_frontend_scripts'));
	}

	/**
	 * Setup integration.
	 *
	 * @return void
	 */
	public function setup() {
		// Initialize objects
		new FormPostType();
		CouponPostType::instance();
		new FormProcessor();
		new FormScripts();

		// Shortcode.
		new FormShortcode( $this );

		// Actions.
		add_filter( 'the_content', [ $this, 'maybe_add_form_to_content' ] );

		add_filter( 'wpayme_payment_source_url_' . FormsSource::PAYMENT_FORM, [ $this, 'source_url' ], 10, 2 );
		add_filter( 'wpayme_payment_source_text_' . FormsSource::PAYMENT_FORM, [ $this, 'source_text' ], 10, 2 );
		add_filter( 'wpayme_payment_source_description_' . FormsSource::PAYMENT_FORM, [ $this, 'source_description' ], 10, 2 );

		// Blocks module.
		if ( function_exists( 'register_block_type' ) ) {
			$blocks_module = new BlocksModule( $this );
			$blocks_module->setup();
		}

		/**
		 * Admin
		 */
		if ( \is_admin() ) {
			new Admin();
		}
	}

	/**
	 * Maybe add form to content.
	 *
	 * @link https://developer.wordpress.org/reference/hooks/the_content/
	 *
	 * @param string $content Post content to maybe extend with a payment form.
	 *
	 * @return string
	 *
	 * @throws \Exception Throws exception if output buffering is not active.
	 */
	public function maybe_add_form_to_content( $content ) {
		if ( is_singular( 'wpayme_pay_form' ) && 'wpayme_pay_form' === get_post_type() ) {
			$content .= $this->get_form_output_by_id( (int) get_the_ID() );
		}

		return $content;
	}

	/**
	 * Enqueue frontend styles
	 */
	public function enqueue_frontend_styles() {
		wp_enqueue_style(
			'wpayme-pay-form-style',
			plugins_url('assets/css/form-style.css', dirname(__FILE__)),
			array(),
			filemtime(plugin_dir_path(dirname(__FILE__)) . 'assets/css/form-style.css')
		);
	}

	/**
	 * Enqueue frontend scripts
	 */
	public function enqueue_frontend_scripts() {
		wp_register_script(
			'wpayme-pay-form-script',
			plugins_url('assets/js/form.js', dirname(__FILE__)),
			array('jquery'),
			'1.0.0',
			true
		);
	}

	/**
	 * Get form output by ID
	 *
	 * @param int $form_id Form ID.
	 * @return string
	 */
	public function get_form_output_by_id($form_id) {
		if (empty($form_id)) {
			return '';
		}

		// Check if form exists
		$form = get_post($form_id);
		if (null === $form || 'wpayme_pay_form' !== $form->post_type) {
			return '';
		}

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

	/**
	 * Get form output
	 *
	 * @param array $args Arguments.
	 * @return string
	 */
	public function get_form_output($args = array()) {
		$defaults = array(
			'form_id' => null,
		);

		$args = wp_parse_args($args, $defaults);

		// Start output buffering
		ob_start();

		// Include form template
		include dirname(__DIR__) . '/views/form.php';

		// Get output buffer
		$output = ob_get_clean();

		return $output;
	}

	/**
	 * Source text filter.
	 *
	 * @param string  $text    The source text to filter.
	 * @param Payment $payment The payment for the specified source text.
	 * @return string
	 */
	public function source_text( $text, Payment $payment ) {
		$text = __( 'Payment Form', 'wpayme' );

		if ( empty( $payment->source_id ) ) {
			return $text;
		}

		$link = get_edit_post_link( intval( $payment->source_id ) );

		if ( null === $link ) {
			return $text;
		}

		$text .= '<br />';

		$text .= sprintf(
			'<a href="%s">%s</a>',
			esc_url( $link ),
			esc_html( strval( $payment->source_id ) )
		);

		return $text;
	}

	/**
	 * Source description filter.
	 *
	 * @param string  $text    The source text to filter.
	 * @param Payment $payment The payment for the specified source text.
	 * @return string
	 */
	public function source_description( $text, Payment $payment ) {
		$text = __( 'Payment Form', 'wpayme' ) . '<br />';

		return $text;
	}

	/**
	 * Source URL.
	 *
	 * @link https://developer.wordpress.org/reference/functions/get_edit_post_link/
	 *
	 * @param string  $url     Source URL.
	 * @param Payment $payment Payment.
	 *
	 * @return string
	 */
	public function source_url( $url, Payment $payment ) {
		if ( empty( $payment->source_id ) ) {
			return $url;
		}

		$link = get_edit_post_link( intval( $payment->source_id ) );

		if ( null === $link ) {
			return $url;
		}

		return $link;
	}

	/**
	 * Debug form rendering
	 *
	 * @param int $form_id Form ID.
	 * @return string
	 */
	public function debug_form_rendering($form_id) {
		if (empty($form_id)) {
			return 'Error: Empty form ID';
		}

		// Check if form exists
		$form = get_post($form_id);
		if (null === $form) {
			return 'Error: Form not found';
		}

		if ('wpayme_pay_form' !== $form->post_type) {
			return 'Error: Invalid post type: ' . $form->post_type;
		}

		// Get form data for debugging
		$debug_info = array(
			'form_id' => $form_id,
			'post_type' => $form->post_type,
			'post_status' => $form->post_status,
			'amount_method' => get_post_meta($form_id, '_wpayme_payment_form_amount_method', true),
			'fixed_price' => get_post_meta($form_id, '_wpayme_fixed_price', true),
			'gateway_id' => get_post_meta($form_id, '_wpayme_payment_form_gateway', true),
			'gateways' => apply_filters('wpayme_pay_gateways', array()),
		);

		// return '<pre>' . print_r($debug_info, true) . '</pre>';
		return '';
	}

	/**
	 * Display test form
	 *
	 * @param int $form_id Form ID.
	 * @return void
	 */
	public function display_test_form($form_id) {
		echo '<div class="wpayme-test-form-container">';
		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		echo $this->get_form_output_by_id($form_id);
		echo '</div>';
	}

	/**
	 * Get simple form output
	 *
	 * @param array $args Arguments.
	 * @return string
	 */
	public function get_simple_form_output($args = array()) {
		$defaults = array(
			'form_id' => null,
		);

		$args = wp_parse_args($args, $defaults);

		// Start output buffering
		ob_start();

		// Include simple form template
		include dirname(__DIR__) . '/views/form-simple.php';

		// Get output buffer
		$output = ob_get_clean();

		return $output;
	}

	/**
	 * Display simple test form
	 *
	 * @param int $form_id Form ID.
	 * @return void
	 */
	public function display_simple_test_form($form_id) {
		echo '<div class="wpayme-test-form-container">';
		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		echo $this->get_simple_form_output(array('form_id' => $form_id));
		echo '</div>';
	}
}
