<?php
/**
 * @package Hafenstudios\Leadlotse
 */

namespace Hafenstudios\Leadlotse\Submit;

defined( 'ABSPATH' ) || exit;

/**
 * Klassischer POST-Fallback ohne JavaScript ueber admin-post.php (D8,
 * progressive enhancement). Nutzt exakt dieselbe Submit-Pipeline wie der
 * REST-Endpoint und leitet mit Ergebnis-Parametern auf die Ursprungsseite
 * zurueck (ll_success=1 bzw. ll_error=<code>).
 */
final class FallbackHandler {

	public const ACTION = 'leadlotse_submit';

	private SubmitHandler $handler;

	/**
	 * @param SubmitHandler $handler Submit-Pipeline.
	 */
	public function __construct( SubmitHandler $handler ) {
		$this->handler = $handler;
	}

	/**
	 * Registriert die admin-post-Hooks (eingeloggt und oeffentlich).
	 *
	 * @return void
	 */
	public function register(): void {
		add_action( 'admin_post_' . self::ACTION, array( $this, 'handle' ) );
		add_action( 'admin_post_nopriv_' . self::ACTION, array( $this, 'handle' ) );
	}

	/**
	 * Verarbeitet den klassischen POST.
	 *
	 * @return void
	 */
	public function handle(): void {
		// phpcs:disable WordPress.Security.NonceVerification.Missing -- Oeffentliches Formular; Schutz laeuft ueber die Spam-Kette (D7). Ein Nonce wuerde Seiten-Caches brechen.
		$form_id = isset( $_POST['form_id'] ) ? absint( wp_unslash( $_POST['form_id'] ) ) : 0;

		$fields = array();
		if ( isset( $_POST['fields'] ) && is_array( $_POST['fields'] ) ) {
			// Sanitizing je Feldtyp passiert in der Pipeline; hier nur unslash.
			$fields = map_deep( wp_unslash( $_POST['fields'] ), 'strval' ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		}
		foreach ( array( SpamGuard::TIMESTAMP_FIELD, \Hafenstudios\Leadlotse\Fields\Types\HoneypotField::FIELD_ID ) as $special ) {
			if ( isset( $_POST[ $special ] ) && ! isset( $fields[ $special ] ) ) {
				$fields[ $special ] = sanitize_text_field( wp_unslash( (string) $_POST[ $special ] ) );
			}
		}

		$referer = wp_get_referer();
		$referer = $referer ? $referer : home_url( '/' );

		$context = array(
			'source_url'   => esc_url_raw( $referer ),
			'utm_source'   => isset( $_POST['utm_source'] ) ? sanitize_text_field( wp_unslash( $_POST['utm_source'] ) ) : '',
			'utm_medium'   => isset( $_POST['utm_medium'] ) ? sanitize_text_field( wp_unslash( $_POST['utm_medium'] ) ) : '',
			'utm_campaign' => isset( $_POST['utm_campaign'] ) ? sanitize_text_field( wp_unslash( $_POST['utm_campaign'] ) ) : '',
		);
		// phpcs:enable

		$result = $this->handler->handle( $form_id, $fields, $context );

		if ( is_wp_error( $result ) ) {
			$redirect = add_query_arg(
				array(
					'll_error' => rawurlencode( $result->get_error_code() ),
					'll_form'  => $form_id,
				),
				$referer
			);
		} else {
			$target   = '' !== (string) ( $result['redirect_url'] ?? '' ) ? (string) $result['redirect_url'] : $referer;
			$redirect = add_query_arg(
				array(
					'll_success' => 1,
					'll_form'    => $form_id,
				),
				$target
			);
		}

		wp_safe_redirect( $redirect );
		exit;
	}
}
