<?php
/** Fluent Forms entry discovery and bounded reads. */

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

function wpagent_ability_list_fluent_entries(): array {
	return array(
		'label'               => __( 'Fluent-Forms-Einträge auflisten', 'wp-agent-companion' ),
		'description'         => __( 'Listet Einträge eines berechtigten Fluent-Forms-Formulars begrenzt auf. Feldwerte bleiben standardmäßig verborgen.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array(
			'type'                 => 'object',
			'additionalProperties' => false,
			'properties'           => array(
				'form_id' => array( 'type' => 'integer', 'minimum' => 1 ),
				'search' => array( 'type' => 'string', 'maxLength' => 255 ),
				'status' => array( 'type' => 'string', 'maxLength' => 64, 'default' => 'all' ),
				'include_values' => array( 'type' => 'boolean', 'default' => false ),
				'page' => array( 'type' => 'integer', 'minimum' => 1, 'default' => 1 ),
				'per_page' => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => 100, 'default' => 20 ),
			),
			'required'             => array( 'form_id' ),
		),
		'output_schema'       => array(
			'type'                 => 'object',
			'additionalProperties' => false,
			'properties'           => array(
				'entries' => array( 'type' => 'array', 'items' => wpagent_fluent_entry_output_schema() ),
				'total' => array( 'type' => 'integer' ), 'page' => array( 'type' => 'integer' ),
				'per_page' => array( 'type' => 'integer' ), 'last_page' => array( 'type' => 'integer' ),
			),
		),
		'execute_callback'    => 'wpagent_exec_list_fluent_entries',
		'permission_callback' => 'wpagent_perm_fluent_entries_read',
		'meta'                => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true ) ),
	);
}

/** @param mixed $input @return array|WP_Error */
function wpagent_exec_list_fluent_entries( $input ) {
	if ( ! wpagent_fluent_entries_available() ) {
		return wpagent_fluent_entries_missing_error();
	}
	$input   = is_array( $input ) ? $input : array();
	$form_id = absint( $input['form_id'] ?? 0 );
	if ( $form_id <= 0 ) {
		return new WP_Error( 'wpagent_bad_form_id', __( 'form_id muss eine positive Ganzzahl sein.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	if ( ! wpagent_fluent_forms_has_permission( 'fluentform_entries_viewer', $form_id ) ) {
		return new WP_Error( 'wpagent_forbidden', __( 'Keine Berechtigung für die Einträge dieses Fluent-Forms-Formulars.', 'wp-agent-companion' ), array( 'status' => 403 ) );
	}
	$status   = sanitize_key( (string) ( $input['status'] ?? 'all' ) );
	$statuses = wpagent_fluent_entry_statuses( $form_id );
	if ( is_wp_error( $statuses ) ) {
		return $statuses;
	}
	if ( 'all' !== $status && ! isset( $statuses[ $status ] ) ) {
		return new WP_Error( 'wpagent_fluent_entry_bad_status', __( 'Der angeforderte Fluent-Forms-Eintragsstatus ist für dieses Formular nicht verfügbar.', 'wp-agent-companion' ), array( 'status' => 400, 'available_statuses' => array_keys( $statuses ) ) );
	}
	try {
		$form  = ( new \FluentForm\App\Services\Form\FormService() )->find( $form_id );
		$entry = new \FluentForm\App\Api\Entry( $form );
		$result = $entry->entries(
			array(
				'search' => sanitize_text_field( (string) ( $input['search'] ?? '' ) ),
				'entry_type' => $status,
				'page' => max( 1, absint( $input['page'] ?? 1 ) ),
				'per_page' => min( 100, max( 1, absint( $input['per_page'] ?? 20 ) ) ),
				'sort_type' => 'DESC',
			),
			false
		);
	} catch ( Throwable $error ) {
		return new WP_Error( 'wpagent_fluent_entries_list_failed', __( 'Die Fluent-Forms-Einträge konnten nicht gelesen werden.', 'wp-agent-companion' ), array( 'status' => 500 ) );
	}
	$result = is_array( $result ) ? $result : array();
	$rows   = array();
	foreach ( is_array( $result['data'] ?? null ) ? $result['data'] : array() as $item ) {
		$payload = wpagent_fluent_entry_payload( $item, ! empty( $input['include_values'] ) );
		if ( is_wp_error( $payload ) ) {
			return $payload;
		}
		$rows[] = $payload;
	}
	return array(
		'entries' => $rows, 'total' => absint( $result['total'] ?? count( $rows ) ),
		'page' => absint( $result['current_page'] ?? 1 ), 'per_page' => absint( $result['per_page'] ?? 20 ),
		'last_page' => absint( $result['last_page'] ?? ( $rows ? 1 : 0 ) ),
	);
}

function wpagent_ability_get_fluent_entry(): array {
	return array(
		'label'               => __( 'Fluent-Forms-Eintrag lesen', 'wp-agent-companion' ),
		'description'         => __( 'Liest die Feldwerte eines einzelnen berechtigten Fluent-Forms-Eintrags. IP, Browser, Zahlungen, Transaktionen und unbekannte Metadaten bleiben verborgen.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array( 'type' => 'object', 'additionalProperties' => false, 'properties' => array( 'entry_id' => array( 'type' => 'integer', 'minimum' => 1 ) ), 'required' => array( 'entry_id' ) ),
		'output_schema'       => array( 'type' => 'object', 'additionalProperties' => false, 'properties' => array( 'entry' => wpagent_fluent_entry_output_schema(), 'version' => array( 'type' => 'string' ) ) ),
		'execute_callback'    => 'wpagent_exec_get_fluent_entry',
		'permission_callback' => 'wpagent_perm_fluent_entries_read',
		'meta'                => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true ) ),
	);
}

/** @param mixed $input @return array|WP_Error */
function wpagent_exec_get_fluent_entry( $input ) {
	$entry = wpagent_fluent_get_authorized_entry( $input, 'fluentform_entries_viewer' );
	if ( is_wp_error( $entry ) ) {
		return $entry;
	}
	$data    = wpagent_fluent_entry_model_array( $entry );
	$form_id = absint( $data['form_id'] ?? 0 );
	try {
		$form   = ( new \FluentForm\App\Services\Form\FormService() )->find( $form_id );
		$result = ( new \FluentForm\App\Api\Entry( $form ) )->entry( absint( $data['id'] ?? 0 ), false );
		$found  = is_array( $result ) ? ( $result['submission'] ?? null ) : null;
	} catch ( Throwable $error ) {
		return new WP_Error( 'wpagent_fluent_entry_read_failed', __( 'Der Fluent-Forms-Eintrag konnte nicht gelesen werden.', 'wp-agent-companion' ), array( 'status' => 500 ) );
	}
	$payload = wpagent_fluent_entry_payload( $found, true );
	return is_wp_error( $payload ) ? $payload : array( 'entry' => $payload, 'version' => $payload['version'] );
}
