<?php
/** Formidable Forms discovery and read abilities. */

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

function wpagent_ability_list_formidable_forms(): array {
	return array(
		'label'       => __( 'Formidable-Forms-Formulare auflisten', 'wp-agent-companion' ),
		'description' => __( 'Listet Formidable-Forms-Formulare über die native Modell-API mit Suche, Status und Pagination.', 'wp-agent-companion' ),
		'category'    => 'wp-agent',
		'input_schema' => array(
			'type' => 'object', 'additionalProperties' => false,
			'properties' => array(
				'search' => array( 'type' => 'string', 'maxLength' => 255 ),
				'status' => array( 'type' => 'string', 'enum' => array( 'published', 'draft', 'trash', 'all' ), 'default' => 'all' ),
				'page' => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => 5000, 'default' => 1 ),
				'per_page' => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => 100, 'default' => 20 ),
			),
		),
		'output_schema' => array(
			'type' => 'object',
			'properties' => array(
				'forms' => array( 'type' => 'array', 'items' => array( 'type' => 'object' ) ),
				'total' => array( 'type' => 'integer' ), 'page' => array( 'type' => 'integer' ),
				'per_page' => array( 'type' => 'integer' ), 'last_page' => array( 'type' => 'integer' ),
			),
		),
		'execute_callback'    => 'wpagent_exec_list_formidable_forms',
		'permission_callback' => 'wpagent_perm_formidable_view',
		'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_formidable_forms( $input ) {
	if ( ! wpagent_formidable_available() ) {
		return wpagent_formidable_missing_error();
	}
	$input    = is_array( $input ) ? $input : array();
	$search   = trim( sanitize_text_field( (string) ( $input['search'] ?? '' ) ) );
	$status   = sanitize_key( (string) ( $input['status'] ?? 'all' ) );
	$page     = min( 5000, max( 1, absint( $input['page'] ?? 1 ) ) );
	$per_page = min( 100, max( 1, absint( $input['per_page'] ?? 20 ) ) );
	try {
		$forms = (array) FrmForm::getAll( array(), 'id DESC', 5001 );
	} catch ( Throwable $error ) {
		return new WP_Error( 'wpagent_formidable_forms_list_failed', __( 'Die Formidable-Forms-Formulare konnten nicht gelesen werden.', 'wp-agent-companion' ), array( 'status' => 500 ) );
	}
	if ( count( $forms ) > 5000 ) {
		return new WP_Error( 'wpagent_formidable_forms_too_many', __( 'Mehr als 5.000 Formulare gefunden. Schränke die Installation ein, bevor du sie über die Agent-Schnittstelle verwaltest.', 'wp-agent-companion' ), array( 'status' => 413 ) );
	}
	$forms = array_values(
		array_filter(
			$forms,
			static function ( $form ) use ( $search, $status ): bool {
				$data = is_object( $form ) ? get_object_vars( $form ) : array();
				if ( ! empty( $data['is_template'] ) ) {
					return false;
				}
				if ( 'all' !== $status && sanitize_key( (string) ( $data['status'] ?? '' ) ) !== $status ) {
					return false;
				}
				if ( '' !== $search ) {
					$haystack = (string) ( $data['name'] ?? '' ) . ' ' . (string) ( $data['form_key'] ?? '' );
					return false !== stripos( $haystack, $search );
				}
				return true;
			}
		)
	);
	$total = count( $forms );
	$forms = array_slice( $forms, ( $page - 1 ) * $per_page, $per_page );
	try {
		$rows = array_map( static fn( $form ): array => wpagent_formidable_form_payload( $form, false ), $forms );
	} catch ( OverflowException $error ) {
		return wpagent_formidable_payload_limit_error();
	} catch ( Throwable $error ) {
		return wpagent_formidable_provider_error();
	}
	return array(
		'forms'     => $rows,
		'total'     => $total,
		'page'      => $page,
		'per_page'  => $per_page,
		'last_page' => $total > 0 ? (int) ceil( $total / $per_page ) : 0,
	);
}

function wpagent_ability_get_formidable_form(): array {
	return array(
		'label'               => __( 'Formidable-Forms-Formular lesen', 'wp-agent-companion' ),
		'description'         => __( 'Liest ein Formidable-Forms-Formular über die native Modell-API. Unbekannte Add-on- und Optionsdaten werden nicht ausgegeben.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array( 'type' => 'object', 'additionalProperties' => false, 'properties' => array( 'form_id' => array( 'type' => 'integer', 'minimum' => 1 ) ), 'required' => array( 'form_id' ) ),
		'output_schema'       => wpagent_formidable_form_output_schema(),
		'execute_callback'    => 'wpagent_exec_get_formidable_form',
		'permission_callback' => 'wpagent_perm_formidable_view',
		'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_formidable_form( $input ) {
	$form = wpagent_formidable_get_authorized_form( $input, 'frm_view_forms' );
	if ( is_wp_error( $form ) ) {
		return $form;
	}
	try {
		return wpagent_formidable_form_payload( $form );
	} catch ( OverflowException $error ) {
		return wpagent_formidable_payload_limit_error();
	} catch ( Throwable $error ) {
		return wpagent_formidable_provider_error();
	}
}
