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

namespace Hafenstudios\Leadlotse\Forms;

defined( 'ABSPATH' ) || exit;

/**
 * CPT `hs_form` (D4): Formulare als Custom Post Type, die eigentliche Feld- und
 * Einstellungsdefinition liegt als validiertes JSON in Post-Meta
 * `_leadlotse_definition`. Kein freier Post-Content-Editor.
 */
final class FormPostType {

	public const POST_TYPE = 'hs_form';

	public const META_DEFINITION = '_leadlotse_definition';

	/**
	 * Registriert CPT und Meta.
	 *
	 * @return void
	 */
	public function register(): void {
		register_post_type(
			self::POST_TYPE,
			array(
				'labels'                => array(
					'name'          => __( 'Formulare', 'leadlotse' ),
					'singular_name' => __( 'Formular', 'leadlotse' ),
					'add_new_item'  => __( 'Neues Formular', 'leadlotse' ),
					'edit_item'     => __( 'Formular bearbeiten', 'leadlotse' ),
					'not_found'     => __( 'Keine Formulare gefunden.', 'leadlotse' ),
				),
				'public'                => false,
				'show_ui'               => false,
				'show_in_rest'          => false,
				'supports'              => array( 'title', 'revisions' ),
				'capability_type'       => 'post',
				'capabilities'          => array(
					'edit_post'           => 'hs_manage_forms',
					'read_post'           => 'hs_manage_forms',
					'delete_post'         => 'hs_manage_forms',
					'edit_posts'          => 'hs_manage_forms',
					'edit_others_posts'   => 'hs_manage_forms',
					'publish_posts'       => 'hs_manage_forms',
					'read_private_posts'  => 'hs_manage_forms',
					'delete_posts'        => 'hs_manage_forms',
					'delete_others_posts' => 'hs_manage_forms',
				),
				'map_meta_cap'          => false,
				'rewrite'               => false,
				'query_var'             => false,
			)
		);

		register_post_meta(
			self::POST_TYPE,
			self::META_DEFINITION,
			array(
				'type'              => 'string',
				'single'            => true,
				'show_in_rest'      => false,
				'revisions_enabled' => true,
				'auth_callback'     => static function () {
					return current_user_can( 'hs_manage_forms' );
				},
			)
		);
	}

	/**
	 * Liefert die dekodierte Definition eines Formulars.
	 *
	 * @param int $form_id Formular-ID.
	 * @return array<string, mixed>|null Null, wenn Formular fehlt oder nicht veroeffentlichbar.
	 */
	public static function get_definition( int $form_id ): ?array {
		$post = get_post( $form_id );
		if ( ! $post || self::POST_TYPE !== $post->post_type ) {
			return null;
		}

		$raw = get_post_meta( $form_id, self::META_DEFINITION, true );
		if ( ! is_string( $raw ) || '' === $raw ) {
			return null;
		}

		$definition = json_decode( $raw, true );
		return is_array( $definition ) ? $definition : null;
	}

	/**
	 * Speichert eine (bereits validierte) Definition.
	 *
	 * @param int                  $form_id    Formular-ID.
	 * @param array<string, mixed> $definition Definition.
	 * @return bool
	 */
	public static function save_definition( int $form_id, array $definition ): bool {
		$json = wp_json_encode( $definition );
		if ( ! is_string( $json ) ) {
			// Encoding fehlgeschlagen (z. B. ungueltiges UTF-8): lieber nichts
			// schreiben als die bestehende Definition zerstoeren.
			return false;
		}

		// wp_slash ist Pflicht: WordPress entfernt beim Schreiben von Post-Meta
		// die Backslashes (wp_unslash, Magic-Quotes-Erbe). Ohne diesen Schutz
		// wuerden JSON-Escapes zerstoert - Umlaute (\uXXXX) wuerden zu Buchstaben-
		// salat und ein Anfuehrungszeichen im Text (\") macht das JSON ungueltig,
		// womit die ganze Formulardefinition verloren geht (L-F2, Live-Fund).
		return (bool) update_post_meta( $form_id, self::META_DEFINITION, wp_slash( $json ) );
	}
}
