<?php
/** Native Beaver Builder column-group creation. */

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

function wpagent_ability_create_beaver_column_group(): array {
	$properties                  = wpagent_beaver_hash_input_properties();
	$properties['parent_id']     = array( 'type' => 'string' );
	$properties['layout']        = array( 'type' => 'string' );
	$properties['position']      = array( 'type' => 'integer', 'minimum' => 0 );
	return wpagent_beaver_write_ability_definition(
		__( 'Beaver-Builder-Spaltengruppe erstellen', 'wp-agent-companion' ),
		__( 'Erstellt eine native Spaltengruppe in einer Zeile oder als einfach verschachtelte Gruppe in einer Spalte.', 'wp-agent-companion' ),
		$properties,
		array( 'post_id', 'parent_id', 'layout', 'expected_hash' ),
		'wpagent_exec_create_beaver_column_group',
		false
	);
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_create_beaver_column_group( $input ) {
	$input         = is_array( $input ) ? $input : array();
	$post_id       = absint( $input['post_id'] ?? 0 );
	$raw_parent_id = is_string( $input['parent_id'] ?? null ) ? $input['parent_id'] : '';
	$raw_layout    = is_string( $input['layout'] ?? null ) ? $input['layout'] : '';
	$parent_id     = sanitize_key( $raw_parent_id );
	$layout        = sanitize_key( $raw_layout );
	$expected_hash = is_string( $input['expected_hash'] ?? null ) ? strtolower( $input['expected_hash'] ) : '';
	$position      = null;
	$post          = wpagent_beaver_editable_post( $post_id );
	if ( is_wp_error( $post ) ) {
		return $post;
	}
	if ( '' === $parent_id || $parent_id !== $raw_parent_id ) {
		return new WP_Error( 'wpagent_beaver_bad_parent', __( 'Ungültige Beaver-Builder-Eltern-ID.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	if ( '' === $layout || $layout !== $raw_layout ) {
		return new WP_Error( 'wpagent_beaver_bad_layout', __( 'Unbekanntes Beaver-Builder-Spaltenlayout.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	if ( array_key_exists( 'position', $input ) ) {
		if ( ! is_int( $input['position'] ) || $input['position'] < 0 ) {
			return new WP_Error( 'wpagent_beaver_bad_position', __( 'Die angeforderte Beaver-Builder-Position ist ungültig.', 'wp-agent-companion' ), array( 'status' => 400 ) );
		}
		$position = $input['position'];
	}
	if ( ! isset( FLBuilderModel::$row_layouts[ $layout ] ) || ! is_array( FLBuilderModel::$row_layouts[ $layout ] ) ) {
		return new WP_Error( 'wpagent_beaver_bad_layout', __( 'Unbekanntes Beaver-Builder-Spaltenlayout.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$parent = wpagent_beaver_node( $post_id, $parent_id );
	if ( is_wp_error( $parent ) ) {
		return $parent;
	}
	if ( ! in_array( $parent->type ?? '', array( 'row', 'column' ), true ) || ! empty( $parent->global ) || ! empty( $parent->template_id ) ) {
		return new WP_Error( 'wpagent_beaver_bad_parent', __( 'Spaltengruppen dürfen nur in lokalen Beaver-Builder-Zeilen oder -Spalten erstellt werden.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$data = FLBuilderModel::get_layout_data( 'published', $post_id );
	if ( 'column' === ( $parent->type ?? '' ) ) {
		$parent_group = $data[ sanitize_key( (string) ( $parent->parent ?? '' ) ) ] ?? null;
		$group_parent = is_object( $parent_group ) ? $data[ sanitize_key( (string) ( $parent_group->parent ?? '' ) ) ] ?? null : null;
		if ( ! is_object( $parent_group ) || 'column-group' !== ( $parent_group->type ?? '' ) || ! is_object( $group_parent ) || 'row' !== ( $group_parent->type ?? '' ) ) {
			return new WP_Error( 'wpagent_beaver_nesting_limit', __( 'Der sichere Beaver-Builder-Pfad erlaubt genau eine verschachtelte Spaltenebene.', 'wp-agent-companion' ), array( 'status' => 400 ) );
		}
		if ( ! empty( $parent_group->global ) || ! empty( $parent_group->template_id ) || ! empty( $group_parent->global ) || ! empty( $group_parent->template_id ) ) {
			return new WP_Error( 'wpagent_beaver_bad_parent', __( 'Spaltengruppen dürfen nur in lokalen Beaver-Builder-Zeilen oder -Spalten erstellt werden.', 'wp-agent-companion' ), array( 'status' => 400 ) );
		}
	}
	$layout_sizes = array_values( FLBuilderModel::$row_layouts[ $layout ] );
	$child_count  = count( $layout_sizes );
	if ( count( $data ) + 1 + $child_count > WPAGENT_BEAVER_MAX_NODES ) {
		return new WP_Error( 'wpagent_beaver_node_limit', __( 'Das Beaver-Builder-Layout überschreitet die sichere Knotengrenze.', 'wp-agent-companion' ), array( 'status' => 413 ) );
	}
	$sibling_count = count(
		array_filter(
			$data,
			static fn( $candidate ): bool => is_object( $candidate )
				&& $parent_id === sanitize_key( (string) ( $candidate->parent ?? '' ) )
		)
	);
	if ( null !== $position && $position > $sibling_count ) {
		return new WP_Error( 'wpagent_beaver_bad_position', __( 'Die angeforderte Beaver-Builder-Position liegt außerhalb des Zielknotens.', 'wp-agent-companion' ), array( 'status' => 400, 'maximum' => $sibling_count ) );
	}
	$expected_position = null === $position ? $sibling_count : $position;
	$result            = wpagent_beaver_mutate(
		$post_id,
		$expected_hash,
		static function () use ( $parent_id, $layout, $position, $expected_position, $child_count, $layout_sizes ) {
			$created = FLBuilderModel::add_col_group( $parent_id, $layout, null === $position ? false : $position );
			if ( ! is_object( $created ) || empty( $created->node ) ) {
				return new WP_Error( 'wpagent_beaver_create_group_failed', __( 'Beaver Builder konnte die Spaltengruppe nicht erstellen.', 'wp-agent-companion' ), array( 'status' => 500 ) );
			}
			$columns = array_values( FLBuilderModel::get_nodes( 'column', $created->node ) );
			if ( count( $columns ) !== $child_count ) {
				return new WP_Error( 'wpagent_beaver_create_group_failed', __( 'Beaver Builder hat nicht alle erwarteten Spalten erstellt.', 'wp-agent-companion' ), array( 'status' => 500 ) );
			}
			$nodes = array(
				$created->node => array(
					'type'     => 'column-group',
					'parent'   => $parent_id,
					'position' => $expected_position,
				),
			);
			foreach ( $columns as $index => $column ) {
				$nodes[ $column->node ] = array(
					'type'     => 'column',
					'parent'   => $created->node,
					'position' => $index,
					'settings' => (object) array( 'size' => $layout_sizes[ $index ] ),
				);
			}
			return array(
				'target_node_id' => $created->node,
				'_verification'   => array(
					'nodes'              => $nodes,
					'safe_subtree_roots' => array( $created->node ),
				),
			);
		}
	);
	return wpagent_beaver_attach_target_node( $result );
}
