<?php
/** Fluent Forms submission-confirmation write ability. */

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

/** @return string|WP_Error */
function wpagent_fluent_forms_delivery_plain_message( $value, string $field, int $max_length ) {
	$text = is_string( $value ) ? trim( $value ) : '';
	if ( '' === $text || strlen( $text ) > $max_length ) {
		/* translators: 1: input field name, 2: maximum byte length. */
		return new WP_Error( 'wpagent_fluent_forms_delivery_text', sprintf( __( '%1$s muss zwischen 1 und %2$d Byte lang sein.', 'wp-agent-companion' ), $field, $max_length ), array( 'status' => 400 ) );
	}
	if ( str_contains( $text, '<' ) || str_contains( $text, '>' ) || preg_match( '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', $text ) ) {
		/* translators: %s: input field name. */
		return new WP_Error( 'wpagent_fluent_forms_delivery_markup', sprintf( __( '%s akzeptiert nur Text und Smartcodes, kein HTML oder Steuerzeichen.', 'wp-agent-companion' ), $field ), array( 'status' => 400 ) );
	}
	return wpautop( esc_html( $text ) );
}

/** @param array<string,mixed> $current @param array<string,mixed> $patch @return array<string,mixed>|WP_Error */
function wpagent_fluent_forms_prepare_confirmation( array $current, array $patch ) {
	$allowed = array( 'redirect_to', 'message', 'same_page_behavior', 'custom_page_id', 'custom_url', 'redirect_message', 'enable_query_string', 'query_strings' );
	if ( ! $patch || array_diff( array_keys( $patch ), $allowed ) ) {
		return new WP_Error( 'wpagent_fluent_forms_confirmation_fields', __( 'Übergebe mindestens ein unterstütztes Bestätigungsfeld.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$result = $current;
	if ( array_key_exists( 'redirect_to', $patch ) ) {
		$map = array( 'same_page' => 'samePage', 'custom_url' => 'customUrl', 'custom_page' => 'customPage' );
		$key = is_string( $patch['redirect_to'] ) ? $patch['redirect_to'] : '';
		if ( ! isset( $map[ $key ] ) ) {
			return new WP_Error( 'wpagent_fluent_forms_confirmation_redirect', __( 'redirect_to muss same_page, custom_url oder custom_page sein.', 'wp-agent-companion' ), array( 'status' => 400 ) );
		}
		$result['redirectTo'] = $map[ $key ];
	}
	if ( array_key_exists( 'message', $patch ) ) {
		$message = wpagent_fluent_forms_delivery_plain_message( $patch['message'], 'message', 100000 );
		if ( is_wp_error( $message ) ) {
			return $message;
		}
		$result['messageToShow'] = $message;
	}
	if ( array_key_exists( 'same_page_behavior', $patch ) ) {
		$behavior = is_string( $patch['same_page_behavior'] ) ? $patch['same_page_behavior'] : '';
		if ( ! in_array( $behavior, array( 'hide_form', 'reset_form' ), true ) ) {
			return new WP_Error( 'wpagent_fluent_forms_confirmation_behavior', __( 'same_page_behavior muss hide_form oder reset_form sein.', 'wp-agent-companion' ), array( 'status' => 400 ) );
		}
		$result['samePageFormBehavior'] = $behavior;
	}
	if ( array_key_exists( 'custom_page_id', $patch ) ) {
		$page_id = absint( $patch['custom_page_id'] );
		$post    = get_post( $page_id );
		if ( ! $post instanceof WP_Post || 'page' !== $post->post_type || 'trash' === $post->post_status ) {
			return new WP_Error( 'wpagent_fluent_forms_confirmation_page', __( 'custom_page_id muss auf eine vorhandene Seite außerhalb des Papierkorbs zeigen.', 'wp-agent-companion' ), array( 'status' => 400 ) );
		}
		$result['customPage'] = $page_id;
	}
	if ( array_key_exists( 'custom_url', $patch ) ) {
		$url    = is_string( $patch['custom_url'] ) ? trim( $patch['custom_url'] ) : '';
		$parsed = wp_parse_url( $url );
		if ( ! is_array( $parsed ) || ! in_array( strtolower( (string) ( $parsed['scheme'] ?? '' ) ), array( 'http', 'https' ), true ) || empty( $parsed['host'] ) || isset( $parsed['user'] ) || isset( $parsed['pass'] ) ) {
			return new WP_Error( 'wpagent_fluent_forms_confirmation_url', __( 'custom_url muss eine vollständige HTTP- oder HTTPS-URL ohne Zugangsdaten sein.', 'wp-agent-companion' ), array( 'status' => 400 ) );
		}
		$result['customUrl'] = esc_url_raw( $url );
	}
	if ( array_key_exists( 'redirect_message', $patch ) ) {
		$message = wpagent_fluent_forms_delivery_plain_message( $patch['redirect_message'], 'redirect_message', 20000 );
		if ( is_wp_error( $message ) ) {
			return $message;
		}
		$result['redirectMessage'] = $message;
	}
	if ( array_key_exists( 'enable_query_string', $patch ) ) {
		$result['enable_query_string'] = rest_sanitize_boolean( $patch['enable_query_string'] ) ? 'yes' : 'no';
	}
	if ( array_key_exists( 'query_strings', $patch ) ) {
		$query = is_string( $patch['query_strings'] ) ? trim( $patch['query_strings'] ) : '';
		$query = ltrim( $query, '?' );
		if ( strlen( $query ) > 4096 || str_contains( $query, '#' ) || preg_match( '/[\x00-\x20\x7F]/', $query ) ) {
			return new WP_Error( 'wpagent_fluent_forms_confirmation_query', __( 'query_strings darf höchstens 4.096 Byte lang sein und keine Leer-, Steuer- oder Fragmentzeichen enthalten.', 'wp-agent-companion' ), array( 'status' => 400 ) );
		}
		$result['query_strings'] = $query;
	}
	$redirect_to = (string) ( $result['redirectTo'] ?? 'samePage' );
	if ( 'customUrl' === $redirect_to && '' === (string) ( $result['customUrl'] ?? '' ) ) {
		return new WP_Error( 'wpagent_fluent_forms_confirmation_url', __( 'Für custom_url ist custom_url erforderlich.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	if ( 'customPage' === $redirect_to && absint( $result['customPage'] ?? 0 ) <= 0 ) {
		return new WP_Error( 'wpagent_fluent_forms_confirmation_page', __( 'Für custom_page ist custom_page_id erforderlich.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	return $result;
}

/** @param object $service @param array<string,mixed> $form_settings @param array<string,mixed> $advanced */
function wpagent_fluent_forms_save_general_settings( object $service, int $form_id, array $form_settings, array $advanced ): bool {
	$form_json = wp_json_encode( $form_settings );
	$advanced_json = wp_json_encode( $advanced );
	if ( false === $form_json || false === $advanced_json ) {
		return false;
	}
	try {
		$service->saveGeneral( array( 'form_id' => $form_id, 'formSettings' => $form_json, 'advancedValidationSettings' => $advanced_json ) );
		return true;
	} catch ( Throwable $error ) {
		return false;
	}
}

/** @param array<string,mixed> $snapshot */
function wpagent_fluent_forms_restore_general_settings( array $snapshot ): bool {
	if ( ! wpagent_fluent_forms_save_general_settings( $snapshot['service'], $snapshot['form_id'], $snapshot['form_settings'], $snapshot['advanced_settings'] ) ) {
		return false;
	}
	$fresh = wpagent_fluent_forms_delivery_state( $snapshot['form_id'] );
	return ! is_wp_error( $fresh ) && hash_equals( $snapshot['raw_hash'], $fresh['raw_hash'] );
}

function wpagent_ability_update_fluent_form_confirmation(): array {
	$properties = wpagent_fluent_forms_confirmation_schema()['properties'];
	$properties['message'] = array( 'type' => 'string', 'minLength' => 1, 'maxLength' => 100000 );
	$properties['custom_page_id'] = array( 'type' => 'integer', 'minimum' => 1 );
	$properties['custom_url'] = array( 'type' => 'string', 'minLength' => 1, 'maxLength' => 4096 );
	$properties['redirect_message'] = array( 'type' => 'string', 'minLength' => 1, 'maxLength' => 20000 );
	$properties['query_strings'] = array( 'type' => 'string', 'maxLength' => 4096 );
	return array(
		'label' => __( 'Fluent-Forms-Bestätigung aktualisieren', 'wp-agent-companion' ),
		'description' => __( 'Aktualisiert gezielt die Übermittlungsbestätigung. Ein Konflikt-Hash, eine Formularsperre, Read-back und Rollback schützen parallele und unvollständige Änderungen. Nachrichtentext wird sicher in HTML umgewandelt.', 'wp-agent-companion' ),
		'category' => 'wp-agent',
		'input_schema' => array(
			'type' => 'object', 'additionalProperties' => false,
			'properties' => array(
				'form_id' => array( 'type' => 'integer', 'minimum' => 1 ),
				'expected_hash' => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
				'confirmation' => array( 'type' => 'object', 'additionalProperties' => false, 'minProperties' => 1, 'properties' => $properties ),
			),
			'required' => array( 'form_id', 'expected_hash', 'confirmation' ),
		),
		'output_schema' => array( 'type' => 'object', 'properties' => array_merge( wpagent_fluent_forms_delivery_output_schema()['properties'], array( 'verified' => array( 'type' => 'boolean' ) ) ) ),
		'execute_callback' => 'wpagent_exec_update_fluent_form_confirmation',
		'permission_callback' => 'wpagent_perm_fluent_forms_manage',
		'meta' => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => false, 'destructive' => false, 'idempotent' => true ) ),
	);
}

/** @param mixed $input @return array<string,mixed>|WP_Error */
function wpagent_exec_update_fluent_form_confirmation( $input ) {
	$input = is_array( $input ) ? $input : array();
	$form_id = absint( $input['form_id'] ?? 0 );
	$expected_hash = wpagent_fluent_forms_delivery_expected_hash( $input['expected_hash'] ?? '' );
	if ( is_wp_error( $expected_hash ) ) {
		return $expected_hash;
	}
	$lock = wpagent_fluent_forms_delivery_acquire_lock( $form_id );
	if ( is_wp_error( $lock ) ) {
		return $lock;
	}
	try {
		$before = wpagent_fluent_forms_delivery_state( $form_id );
		if ( is_wp_error( $before ) ) {
			return $before;
		}
		if ( ! hash_equals( $before['confirmation_hash'], $expected_hash ) ) {
			return new WP_Error( 'wpagent_fluent_forms_delivery_conflict', __( 'Die Bestätigung wurde seit dem Lesen verändert.', 'wp-agent-companion' ), array( 'status' => 409, 'current_hash' => $before['confirmation_hash'] ) );
		}
		$current_native = wpagent_fluent_forms_delivery_array( $before['form_settings']['confirmation'] ?? array() );
		$prepared = wpagent_fluent_forms_prepare_confirmation( $current_native, is_array( $input['confirmation'] ?? null ) ? $input['confirmation'] : array() );
		if ( is_wp_error( $prepared ) ) {
			return $prepared;
		}
		$expected = wpagent_fluent_forms_confirmation_payload( $prepared );
		$next_settings = $before['form_settings'];
		$next_settings['confirmation'] = $prepared;
		if ( ! wpagent_fluent_forms_save_general_settings( $before['service'], $form_id, $next_settings, $before['advanced_settings'] ) ) {
			if ( ! wpagent_fluent_forms_restore_general_settings( $before ) ) {
				return new WP_Error( 'wpagent_fluent_forms_delivery_rollback_failed', __( 'Der fehlgeschlagene Speicherversuch konnte den Zustand verändert haben und der vorherige Zustand ließ sich nicht vollständig bestätigen. Prüfe das Formular sofort manuell.', 'wp-agent-companion' ), array( 'status' => 500 ) );
			}
			return new WP_Error( 'wpagent_fluent_forms_confirmation_save_failed', __( 'Die Fluent-Forms-Bestätigung konnte nicht gespeichert werden. Der vorherige Zustand wurde bestätigt.', 'wp-agent-companion' ), array( 'status' => 500 ) );
		}
		$fresh = wpagent_fluent_forms_delivery_state( $form_id );
		$expected_settings_hash = wpagent_fluent_forms_delivery_hash( array( $next_settings, $before['advanced_settings'] ) );
		if ( ! is_wp_error( $fresh ) && wpagent_fluent_forms_delivery_hash( $expected ) === wpagent_fluent_forms_delivery_hash( $fresh['confirmation'] ) && hash_equals( $expected_settings_hash, $fresh['confirmation_hash'] ) ) {
			$result = wpagent_fluent_forms_delivery_public( $fresh );
			$result['verified'] = true;
			return $result;
		}
		if ( ! wpagent_fluent_forms_restore_general_settings( $before ) ) {
			return new WP_Error( 'wpagent_fluent_forms_delivery_rollback_failed', __( 'Die Bestätigung konnte nicht verifiziert und der vorherige Zustand nicht vollständig wiederhergestellt werden. Prüfe das Formular sofort manuell.', 'wp-agent-companion' ), array( 'status' => 500 ) );
		}
		return new WP_Error( 'wpagent_fluent_forms_confirmation_unverified', __( 'Die Bestätigung wich nach dem Speichern ab und wurde zurückgerollt.', 'wp-agent-companion' ), array( 'status' => 500 ) );
	} finally {
		wpagent_fluent_forms_delivery_release_lock( $form_id, $lock );
	}
}
