<?php
/** Bounded Gravity Forms entry search and read abilities. */

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

function wpagent_ability_list_gravity_entries(): array {
	return array(
		'label'               => __( 'Gravity-Forms-Einträge auflisten', 'wp-agent-companion' ),
		'description'         => __( 'Listet Gravity-Forms-Einträge begrenzt über GFAPI. Feldwerte und personenbezogene Detaildaten werden nur mit include_values=true ausgegeben.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array(
			'type'                 => 'object',
			'additionalProperties' => false,
			'properties'           => array(
				'form_id'        => array( 'type' => 'integer', 'minimum' => 1 ),
				'status'         => array( 'type' => 'string', 'enum' => array( 'active', 'spam', 'trash', 'all' ), 'default' => 'active' ),
				'search'         => array( 'type' => 'string', 'maxLength' => 255 ),
				'start_date'     => array( 'type' => 'string', 'maxLength' => 19 ),
				'end_date'       => array( 'type' => 'string', 'maxLength' => 19 ),
				'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_gravity_entry_output_schema() ),
				'total'    => array( 'type' => 'integer' ),
				'page'     => array( 'type' => 'integer' ),
				'per_page' => array( 'type' => 'integer' ),
			),
		),
		'execute_callback'    => 'wpagent_exec_list_gravity_entries',
		'permission_callback' => 'wpagent_perm_gravity_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_gravity_entries( $input ) {
	if ( ! wpagent_gravity_entries_available( array( 'get_entries' ) ) ) {
		return wpagent_gravity_entries_missing_error();
	}
	$input = is_array( $input ) ? $input : array();
	$form  = wpagent_gravity_get_authorized_form( $input, 'gravityforms_view_entries' );
	if ( is_wp_error( $form ) ) {
		return $form;
	}
	$status   = (string) ( $input['status'] ?? 'active' );
	if ( ! in_array( $status, array( 'active', 'spam', 'trash', 'all' ), true ) ) {
		return new WP_Error( 'wpagent_gravity_entry_bad_status', __( 'status muss active, spam, trash oder all sein.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$page     = max( 1, absint( $input['page'] ?? 1 ) );
	$per_page = min( 100, max( 1, absint( $input['per_page'] ?? 20 ) ) );
	$criteria = array();
	if ( 'all' !== $status ) {
		$criteria['status'] = $status;
	}
	$search = trim( (string) ( $input['search'] ?? '' ) );
	if ( '' !== $search ) {
		$criteria['field_filters'] = array( array( 'key' => 0, 'value' => $search, 'operator' => 'contains' ) );
	}
	foreach ( array( 'start_date', 'end_date' ) as $date_key ) {
		$value = wpagent_gravity_entry_date_filter( $input[ $date_key ] ?? '' );
		if ( is_wp_error( $value ) ) {
			return $value;
		}
		if ( '' !== $value ) {
			$criteria[ $date_key ] = $value;
		}
	}
	if ( isset( $criteria['start_date'], $criteria['end_date'] ) ) {
		$start_compare = $criteria['start_date'] . ( 10 === strlen( $criteria['start_date'] ) ? ' 00:00:00' : '' );
		$end_compare   = $criteria['end_date'] . ( 10 === strlen( $criteria['end_date'] ) ? ' 23:59:59' : '' );
		if ( $start_compare > $end_compare ) {
			return new WP_Error( 'wpagent_gravity_entry_bad_date_range', __( 'start_date darf nicht nach end_date liegen.', 'wp-agent-companion' ), array( 'status' => 400 ) );
		}
	}
	$paging = array( 'offset' => ( $page - 1 ) * $per_page, 'page_size' => $per_page );
	$total  = 0;
	$rows   = GFAPI::get_entries( absint( $form['id'] ?? 0 ), $criteria, array( 'key' => 'id', 'direction' => 'DESC' ), $paging, $total );
	if ( is_wp_error( $rows ) ) {
		return $rows;
	}
	$entries        = array();
	$include_values = ! empty( $input['include_values'] );
	$value_keys     = $include_values ? wpagent_gravity_entry_value_keys( $form ) : array();
	foreach ( is_array( $rows ) ? $rows : array() as $entry ) {
		if ( is_array( $entry ) ) {
			$entries[] = wpagent_gravity_entry_payload( $entry, $include_values, $value_keys );
		}
	}
	return array( 'entries' => $entries, 'total' => absint( $total ), 'page' => $page, 'per_page' => $per_page );
}

function wpagent_ability_get_gravity_entry(): array {
	return array(
		'label'               => __( 'Gravity-Forms-Eintrag lesen', 'wp-agent-companion' ),
		'description'         => __( 'Liest einen Gravity-Forms-Eintrag einschließlich Feldwerten und dokumentierten Zahlungsdaten. Unbekannte Add-on-Metadaten werden nicht ausgegeben.', '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'       => wpagent_gravity_entry_output_schema(),
		'execute_callback'    => 'wpagent_exec_get_gravity_entry',
		'permission_callback' => 'wpagent_perm_gravity_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_gravity_entry( $input ) {
	$entry = wpagent_gravity_get_authorized_entry( $input, 'gravityforms_view_entries' );
	return is_wp_error( $entry ) ? $entry : wpagent_gravity_entry_payload( $entry, true );
}
