<?php
/** Read-only Beaver Builder user-template and primitive global-settings abilities. */

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

/** @return array<string,mixed> */
function wpagent_beaver_user_template_output_schema(): array {
	$properties = array(
		'post_id'            => array( 'type' => 'integer' ),
		'template_id'        => array( 'type' => 'string' ),
		'name'               => array( 'type' => 'string' ),
		'content'            => array( 'type' => 'string' ),
		'status'             => array( 'type' => 'string' ),
		'is_global'          => array( 'type' => 'boolean' ),
		'is_dynamic_editing' => array( 'type' => 'boolean' ),
		'writable'           => array( 'type' => 'boolean' ),
		'hash'               => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
		'node_count'         => array( 'type' => 'integer' ),
		'nodes'              => array( 'type' => 'array', 'items' => wpagent_beaver_node_output_schema() ),
		// Die statische Provider-Settings-Map ist bei Beaver versionsabhängig.
		// Ihre Werte sind vor dem Output bereits auf nicht ausführbare Primitive begrenzt.
		'settings'           => array( 'type' => 'object', 'additionalProperties' => true ),
		'revision_count'     => array( 'type' => 'integer' ),
	);
	return array(
		'type'       => 'object',
		'properties' => $properties,
		'required'   => array_keys( $properties ),
		'additionalProperties' => false,
	);
}

/** @return array<string,mixed> */
function wpagent_beaver_global_settings_output_schema(): array {
	$settings_properties = array();
	foreach ( wpagent_beaver_global_settings_field_catalog() as $name => $field ) {
		$settings_properties[ $name ] = 'select' === $field['type']
			? array( 'type' => 'string', 'enum' => $field['values'] )
			: array( 'type' => 'string', 'pattern' => '^(?:0|[1-9][0-9]{0,3})$' );
	}
	$properties = array(
		'settings' => array( 'type' => 'object', 'properties' => $settings_properties, 'required' => array_keys( $settings_properties ), 'additionalProperties' => false ),
		'hash'     => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
		'version'  => array( 'type' => 'string' ),
		'fields'   => array( 'type' => 'array', 'items' => array( 'type' => 'string' ) ),
	);
	return array(
		'type'       => 'object',
		'properties' => $properties,
		'required'   => array_keys( $properties ),
		'additionalProperties' => false,
	);
}

function wpagent_ability_list_beaver_user_templates(): array {
	return array(
		'label'               => __( 'Beaver-Builder-Templates auflisten', 'wp-agent-companion' ),
		'description'         => __( 'Liest native Beaver-Builder-Benutzer-Templates. Globale und dynamische Templates bleiben als nicht schreibbare Metadaten erkennbar.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array(
			'type'       => 'object',
			'properties' => array( 'type' => array( 'type' => 'string', 'enum' => wpagent_beaver_user_template_types() ) ),
		),
		'output_schema'       => array(
			'type'       => 'object',
			'properties' => array( 'templates' => array( 'type' => 'array', 'items' => wpagent_beaver_user_template_output_schema() ), 'total' => array( 'type' => 'integer' ), 'type' => array( 'type' => 'string' ), 'version' => array( 'type' => 'string' ) ),
			'required'   => array( 'templates', 'total', 'type', 'version' ),
			'additionalProperties' => false,
		),
		'execute_callback'    => 'wpagent_exec_list_beaver_user_templates',
		'permission_callback' => 'wpagent_perm_edit_posts',
		'meta'                => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true ) ),
	);
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_list_beaver_user_templates( $input = array() ) {
	if ( ! wpagent_beaver_user_templates_available() ) {
		return wpagent_beaver_user_templates_unavailable_error();
	}
	if ( ! current_user_can( 'edit_posts' ) ) {
		return new WP_Error( 'wpagent_beaver_forbidden', __( 'Keine Berechtigung zum Lesen der Beaver-Builder-Templates.', 'wp-agent-companion' ), array( 'status' => 403 ) );
	}
	$input = is_array( $input ) ? $input : array();
	$type  = sanitize_key( is_string( $input['type'] ?? null ) ? $input['type'] : 'layout' );
	if ( ! in_array( $type, wpagent_beaver_user_template_types(), true ) ) {
		return new WP_Error( 'wpagent_beaver_template_type', __( 'Der Beaver-Builder-Template-Typ ist nicht unterstützt.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$native = FLBuilderModel::get_user_templates( $type );
	if ( ! is_array( $native ) ) {
		return new WP_Error( 'wpagent_beaver_template_read_failed', __( 'Beaver Builder lieferte keine gültige Template-Liste.', 'wp-agent-companion' ), array( 'status' => 502 ) );
	}
	$templates = array();
	foreach ( array_slice( is_array( $native['templates'] ?? null ) ? $native['templates'] : array(), 0, WPAGENT_BEAVER_TEMPLATE_MAX ) as $template ) {
		if ( ! is_array( $template ) ) {
			continue;
		}
		$post_id = absint( $template['postId'] ?? 0 );
		$post    = $post_id > 0 ? get_post( $post_id ) : null;
		if ( ! $post || 'fl-builder-template' !== $post->post_type ) {
			continue;
		}
		$is_global  = ! empty( $template['isGlobal'] ) || ( method_exists( 'FLBuilderModel', 'is_post_global_node_template' ) && FLBuilderModel::is_post_global_node_template( $post_id ) );
		$is_dynamic = ! empty( $template['isDynamicEditing'] ) || ( method_exists( 'FLBuilderModel', 'is_post_dynamic_editing_node_template' ) && FLBuilderModel::is_post_dynamic_editing_node_template( $post_id ) );
		$templates[] = array(
			'post_id'            => $post_id,
			'template_id'        => sanitize_key( (string) ( $template['id'] ?? get_post_meta( $post_id, '_fl_builder_template_id', true ) ) ),
			'name'               => wp_html_excerpt( sanitize_text_field( (string) ( $template['name'] ?? get_the_title( $post_id ) ) ), WPAGENT_BEAVER_TEMPLATE_MAX_NAME_BYTES, '' ),
			'content'            => sanitize_key( (string) ( $template['content'] ?? $type ) ),
			'status'             => (string) get_post_status( $post_id ),
			'is_global'          => $is_global,
			'is_dynamic_editing' => $is_dynamic,
			'writable'           => ! $is_global && ! $is_dynamic && current_user_can( 'edit_post', $post_id ),
			'hash'               => '',
			'node_count'         => 0,
			'nodes'              => array(),
			'settings'           => array(),
			'revision_count'     => 0,
		);
	}
	return array( 'templates' => $templates, 'total' => count( $templates ), 'type' => $type, 'version' => defined( 'FL_BUILDER_VERSION' ) ? (string) FL_BUILDER_VERSION : '' );
}

function wpagent_ability_get_beaver_user_template(): array {
	return array(
		'label'               => __( 'Beaver-Builder-Template lesen', 'wp-agent-companion' ),
		'description'         => __( 'Liest ein natives Beaver-Builder-Benutzer-Template mit Hash und sicherem, nicht ausführbarem Read-back.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array( 'type' => 'object', 'properties' => array( 'post_id' => array( 'type' => 'integer' ) ), 'required' => array( 'post_id' ) ),
		'output_schema'       => wpagent_beaver_user_template_output_schema(),
		'execute_callback'    => 'wpagent_exec_get_beaver_user_template',
		'permission_callback' => 'wpagent_perm_edit_posts',
		'meta'                => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true ) ),
	);
}

/** @return array<string,mixed>|WP_Error */
function wpagent_beaver_user_template_state( int $post_id ) {
	$post = wpagent_beaver_user_template_post( $post_id );
	if ( is_wp_error( $post ) ) {
		return $post;
	}
	$data     = FLBuilderModel::get_layout_data( 'published', $post_id );
	$settings = FLBuilderModel::get_layout_settings( 'published', $post_id );
	if ( ! is_array( $data ) ) {
		return new WP_Error( 'wpagent_beaver_template_read_failed', __( 'Beaver Builder lieferte keine gültigen Template-Layoutdaten.', 'wp-agent-companion' ), array( 'status' => 502 ) );
	}
	$type       = FLBuilderModel::get_user_template_type( $post_id );
	$is_global  = method_exists( 'FLBuilderModel', 'is_post_global_node_template' ) && FLBuilderModel::is_post_global_node_template( $post_id );
	$is_dynamic = method_exists( 'FLBuilderModel', 'is_post_dynamic_editing_node_template' ) && FLBuilderModel::is_post_dynamic_editing_node_template( $post_id );
	$guard      = ( ! $is_global && ! $is_dynamic && in_array( $type, wpagent_beaver_user_template_types(), true ) ) ? wpagent_beaver_template_validate_state( $data, $settings ) : new WP_Error( 'wpagent_beaver_template_linked', __( 'Globale oder dynamische Beaver-Builder-Templates sind nicht schreibbar.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	$nodes      = array();
	if ( ! is_wp_error( $guard ) ) {
		$public_nodes = wpagent_beaver_public_nodes( $data );
		if ( ! is_wp_error( $public_nodes ) ) {
			$nodes = $public_nodes;
		}
	}
	$revisions = wp_get_post_revisions( $post_id, array( 'numberposts' => WPAGENT_BEAVER_TEMPLATE_MAX ) );
	return array(
		'post_id'            => $post_id,
		'template_id'        => sanitize_key( (string) get_post_meta( $post_id, '_fl_builder_template_id', true ) ),
		'name'               => sanitize_text_field( (string) get_the_title( $post_id ) ),
		'content'            => sanitize_key( (string) $type ),
		'status'             => (string) get_post_status( $post_id ),
		'is_global'          => (bool) $is_global,
		'is_dynamic_editing' => (bool) $is_dynamic,
		'writable'           => ! is_wp_error( $guard ) && current_user_can( 'edit_post', $post_id ),
		'hash'               => wpagent_beaver_state_hash( $data, $settings ),
		'node_count'         => count( $data ),
		'nodes'              => $nodes,
		'settings'           => wpagent_beaver_template_public_layout_settings( $settings ),
		'revision_count'     => is_array( $revisions ) ? count( $revisions ) : 0,
	);
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_get_beaver_user_template( $input ) {
	if ( ! wpagent_beaver_user_templates_available() ) {
		return wpagent_beaver_user_templates_unavailable_error();
	}
	if ( ! current_user_can( 'edit_posts' ) ) {
		return new WP_Error( 'wpagent_beaver_forbidden', __( 'Keine Berechtigung zum Lesen der Beaver-Builder-Templates.', 'wp-agent-companion' ), array( 'status' => 403 ) );
	}
	$input = is_array( $input ) ? $input : array();
	return wpagent_beaver_user_template_state( absint( $input['post_id'] ?? 0 ) );
}

function wpagent_ability_get_beaver_global_settings(): array {
	return array(
		'label'               => __( 'Beaver-Builder-Global-Settings lesen', 'wp-agent-companion' ),
		'description'         => __( 'Liest ausschließlich den realen primitiven Allowlist-Ausschnitt der globalen Beaver-Builder-Einstellungen.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array( 'type' => 'object', 'properties' => array(), 'additionalProperties' => false ),
		'output_schema'       => wpagent_beaver_global_settings_output_schema(),
		'execute_callback'    => 'wpagent_exec_get_beaver_global_settings',
		'permission_callback' => 'wpagent_perm_edit_posts',
		'meta'                => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true ) ),
	);
}

/** @return array<string,mixed>|WP_Error */
function wpagent_beaver_global_settings_state() {
	if ( ! wpagent_beaver_available() ) {
		return wpagent_beaver_unavailable_error();
	}
	$settings = FLBuilderModel::get_global_settings( false );
	$safe     = wpagent_beaver_global_settings_safe_values( $settings );
	if ( is_wp_error( $safe ) ) {
		return $safe;
	}
	return array(
		'settings' => $safe,
		'hash'     => wpagent_beaver_state_hash( array(), $settings ),
		'version'  => defined( 'FL_BUILDER_VERSION' ) ? (string) FL_BUILDER_VERSION : '',
		'fields'   => array_keys( wpagent_beaver_global_settings_field_catalog() ),
	);
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_get_beaver_global_settings( $input = array() ) {
	if ( ! current_user_can( 'edit_posts' ) ) {
		return new WP_Error( 'wpagent_beaver_forbidden', __( 'Keine Berechtigung zum Lesen der globalen Beaver-Builder-Einstellungen.', 'wp-agent-companion' ), array( 'status' => 403 ) );
	}
	return wpagent_beaver_global_settings_state();
}
