<?php
/** Read-only Kadence Blocks advanced-form settings abilities. */

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

/** @return array<string,mixed> */
function wpagent_kadence_form_email_schema(): array {
	return array(
		'type'                 => 'object',
		'additionalProperties' => false,
		'properties'           => array(
			'enabled' => array( 'type' => 'boolean' ),
			'to' => array( 'type' => 'string' ),
			'subject' => array( 'type' => 'string' ),
			'from_email' => array( 'type' => 'string' ),
			'from_name' => array( 'type' => 'string' ),
			'reply_to' => array( 'type' => 'string', 'enum' => array( 'email_field', 'from_email' ) ),
			'html' => array( 'type' => 'boolean' ),
			'advanced_headers_present' => array( 'type' => 'boolean' ),
		),
		'required' => array( 'enabled', 'to', 'subject', 'from_email', 'from_name', 'reply_to', 'html', 'advanced_headers_present' ),
	);
}

/** @return array<string,mixed> */
function wpagent_kadence_form_payload_schema(): array {
	return array(
		'type'                 => 'object',
		'additionalProperties' => false,
		'properties'           => array(
			'form_id' => array( 'type' => 'integer' ),
			'title' => array( 'type' => 'string' ),
			'status' => array( 'type' => 'string' ),
			'provider_version' => array( 'type' => 'string' ),
			'field_count' => array( 'type' => 'integer' ),
			'field_types' => array( 'type' => 'array', 'items' => array( 'type' => 'string' ) ),
			'description' => array( 'type' => 'string' ),
			'browser_validation' => array( 'type' => 'boolean' ),
			'redirect' => array( 'type' => 'string' ),
			'hide_after_submit' => array( 'type' => 'boolean' ),
			'email' => wpagent_kadence_form_email_schema(),
			'advanced_actions_present' => array( 'type' => 'boolean' ),
			'hash' => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
		),
		'required' => array( 'form_id', 'title', 'status', 'provider_version', 'field_count', 'field_types', 'description', 'browser_validation', 'redirect', 'hide_after_submit', 'email', 'advanced_actions_present', 'hash' ),
	);
}

/** @return array<string,mixed>|WP_Error */
function wpagent_kadence_form_payload( WP_Post $post ) {
	$snapshot = wpagent_kadence_form_snapshot( $post->ID );
	if ( is_wp_error( $snapshot ) ) {
		return $snapshot;
	}
	$stable_post               = clone $post;
	$stable_post->post_title   = $snapshot['post_title'];
	$stable_post->post_status  = $snapshot['post_status'];
	$stable_post->post_content = $snapshot['post_content'];
	$stable_post->post_author  = $snapshot['post_author'];
	$field_types               = wpagent_kadence_form_field_types( $stable_post );
	if ( is_wp_error( $field_types ) ) {
		return $field_types;
	}
	$values = array();
	foreach ( array( '_kad_form_actions', '_kad_form_email', '_kad_form_browserValidation', '_kad_form_redirect', '_kad_form_submitHide', '_kad_form_description' ) as $key ) {
		$value = wpagent_kadence_form_meta_value_from_rows( $snapshot['meta'], $key );
		if ( is_wp_error( $value ) ) {
			return $value;
		}
		$values[ $key ] = $value;
	}
	$actions_valid = is_array( $values['_kad_form_actions'] )
		&& wp_is_numeric_array( $values['_kad_form_actions'] )
		&& count( array_filter( $values['_kad_form_actions'], 'is_string' ) ) === count( $values['_kad_form_actions'] );
	$actions = $actions_valid
		? array_values( array_filter( $values['_kad_form_actions'], 'is_string' ) )
		: array();
	$email = is_array( $values['_kad_form_email'] ) ? $values['_kad_form_email'] : array();
	$has_advanced_header = static function ( string $key ) use ( $email ): bool {
		if ( ! array_key_exists( $key, $email ) || '' === $email[ $key ] ) {
			return false;
		}
		return ! is_string( $email[ $key ] ) || '' !== trim( $email[ $key ] );
	};
	$reply_to = is_string( $email['replyTo'] ?? null ) && in_array( $email['replyTo'], array( 'email_field', 'from_email' ), true )
		? $email['replyTo']
		: 'email_field';
	$payload = array(
		'form_id'                  => (int) $post->ID,
		'title'                    => (string) $snapshot['post_title'],
		'status'                   => (string) $snapshot['post_status'],
		'provider_version'         => WPAGENT_KADENCE_FORM_VERSION,
		'field_count'              => count( $field_types ),
		'field_types'              => $field_types,
		'description'              => is_string( $values['_kad_form_description'] ) ? $values['_kad_form_description'] : '',
		'browser_validation'       => (bool) $values['_kad_form_browserValidation'],
		'redirect'                 => is_string( $values['_kad_form_redirect'] ) ? $values['_kad_form_redirect'] : '',
		'hide_after_submit'        => (bool) $values['_kad_form_submitHide'],
		'email'                    => array(
			'enabled'                  => in_array( 'email', $actions, true ),
			'to'                       => is_string( $email['emailTo'] ?? null ) ? $email['emailTo'] : '',
			'subject'                  => is_string( $email['subject'] ?? null ) ? $email['subject'] : '',
			'from_email'               => is_string( $email['fromEmail'] ?? null ) ? $email['fromEmail'] : '',
			'from_name'                => is_string( $email['fromName'] ?? null ) ? $email['fromName'] : '',
			'reply_to'                 => $reply_to,
			'html'                     => ! array_key_exists( 'html', $email ) || true === $email['html'],
			'advanced_headers_present' => $has_advanced_header( 'cc' ) || $has_advanced_header( 'bcc' ),
		),
		'advanced_actions_present' => ! $actions_valid
			|| count( array_unique( $actions ) ) !== count( $actions )
			|| array() !== array_values( array_diff( $actions, array( 'email', 'redirect' ) ) ),
		'hash'                     => $snapshot['hash'],
	);
	$verified = wpagent_kadence_form_snapshot( $post->ID );
	if ( is_wp_error( $verified ) || ! hash_equals( (string) $snapshot['hash'], (string) ( $verified['hash'] ?? '' ) ) ) {
		return new WP_Error(
			'wpagent_kadence_form_conflict',
			__( 'Das Kadence-Formular wurde parallel verändert.', 'wp-agent-companion' ),
			array( 'status' => 409, 'current_hash' => is_array( $verified ) ? ( $verified['hash'] ?? '' ) : '' )
		);
	}
	return $payload;
}

function wpagent_ability_list_kadence_forms(): array {
	return array(
		'label' => __( 'Kadence-Formulare auflisten', 'wp-agent-companion' ),
		'description' => __( 'Listet native Kadence-Blocks-Free-Formulare begrenzt und paginiert auf, ohne Zustellungsdaten offenzulegen.', 'wp-agent-companion' ),
		'category' => 'wp-agent',
		'input_schema' => array(
			'type' => 'object', 'additionalProperties' => false,
			'properties' => array(
				'search' => array( 'type' => 'string', 'maxLength' => 100 ),
				'page' => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => 100000 ),
				'per_page' => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => 100 ),
			),
		),
		'output_schema' => array(
			'type' => 'object', 'additionalProperties' => false,
			'properties' => array(
				'items' => array(
					'type' => 'array',
					'items' => array(
						'type' => 'object', 'additionalProperties' => false,
						'properties' => array(
							'form_id' => array( 'type' => 'integer' ), 'title' => array( 'type' => 'string' ),
							'status' => array( 'type' => 'string' ), 'provider_version' => array( 'type' => 'string' ),
						),
						'required' => array( 'form_id', 'title', 'status', 'provider_version' ),
					),
				),
				'page' => array( 'type' => 'integer' ), 'per_page' => array( 'type' => 'integer' ),
				'total' => array( 'type' => 'integer' ), 'total_pages' => array( 'type' => 'integer' ),
			),
			'required' => array( 'items', 'page', 'per_page', 'total', 'total_pages' ),
		),
		'execute_callback' => 'wpagent_exec_list_kadence_forms',
		'permission_callback' => 'wpagent_perm_kadence_forms_list',
		'meta' => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true ) ),
	);
}

/** @param mixed $input @return array<string,mixed>|WP_Error */
function wpagent_exec_list_kadence_forms( $input ) {
	$runtime = wpagent_kadence_form_runtime();
	if ( is_wp_error( $runtime ) ) {
		return $runtime;
	}
	if ( ! current_user_can( 'edit_kadence_forms' ) ) {
		return new WP_Error( 'wpagent_forbidden', __( 'Keine Berechtigung für Kadence-Formulare.', 'wp-agent-companion' ), array( 'status' => 403 ) );
	}
	$input    = is_array( $input ) ? $input : array();
	$page     = max( 1, (int) ( $input['page'] ?? 1 ) );
	$per_page = min( 100, max( 1, (int) ( $input['per_page'] ?? 20 ) ) );
	$query = new WP_Query(
		array(
			'post_type' => 'kadence_form', 'post_status' => array( 'publish', 'draft', 'pending', 'private', 'future' ),
			'posts_per_page' => $per_page, 'paged' => $page, 'orderby' => 'ID', 'order' => 'ASC',
			's' => is_string( $input['search'] ?? null ) ? $input['search'] : '',
		)
	);
	$items = array();
	foreach ( $query->posts as $post ) {
		if ( $post instanceof WP_Post && current_user_can( 'edit_post', $post->ID ) ) {
			$items[] = array( 'form_id' => (int) $post->ID, 'title' => (string) $post->post_title, 'status' => (string) $post->post_status, 'provider_version' => WPAGENT_KADENCE_FORM_VERSION );
		}
	}
	return array( 'items' => $items, 'page' => $page, 'per_page' => $per_page, 'total' => (int) $query->found_posts, 'total_pages' => (int) $query->max_num_pages );
}

function wpagent_ability_get_kadence_form_settings(): array {
	return array(
		'label' => __( 'Kadence-Formulareinstellungen lesen', 'wp-agent-companion' ),
		'description' => __( 'Liest begrenzte Zustellungs- und Verhaltensoptionen eines nativen Kadence-Blocks-Free-Formulars mit vollständigem Konflikthash.', 'wp-agent-companion' ),
		'category' => 'wp-agent',
		'input_schema' => array( 'type' => 'object', 'properties' => array( 'form_id' => array( 'type' => 'integer', 'minimum' => 1 ) ), 'required' => array( 'form_id' ), 'additionalProperties' => false ),
		'output_schema' => wpagent_kadence_form_payload_schema(),
		'execute_callback' => 'wpagent_exec_get_kadence_form_settings',
		'permission_callback' => 'wpagent_perm_kadence_form',
		'meta' => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true ) ),
	);
}

/** @param mixed $input @return array<string,mixed>|WP_Error */
function wpagent_exec_get_kadence_form_settings( $input ) {
	$post = wpagent_kadence_form_get_authorized( (int) ( is_array( $input ) ? ( $input['form_id'] ?? 0 ) : 0 ) );
	return is_wp_error( $post ) ? $post : wpagent_kadence_form_payload( $post );
}
