<?php
/** Privacy-bounded WooCommerce order and order-note reads. */

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

function wpagent_ability_list_orders(): array {
	return array(
		'label'               => __( 'WooCommerce-Bestellungen auflisten', 'wp-agent-companion' ),
		'description'         => __( 'Listet Bestellungen begrenzt über WooCommerce CRUD. Kunden-, Adress-, Zahlungs- und Positionsdaten werden nur mit den jeweiligen include-Schaltern ausgegeben.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array(
			'type'                 => 'object',
			'additionalProperties' => false,
			'properties'           => array(
				'status'           => array( 'type' => 'string', 'maxLength' => 64 ),
				'customer_id'      => array( 'type' => 'integer', 'minimum' => 1 ),
				'include_customer' => array( 'type' => 'boolean', 'default' => false ),
				'include_payment'  => array( 'type' => 'boolean', 'default' => false ),
				'include_items'    => array( 'type' => 'boolean', 'default' => false ),
				'page'             => array( 'type' => 'integer', 'minimum' => 1, 'default' => 1 ),
				'per_page'         => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => 100, 'default' => 20 ),
			),
		),
		'output_schema'       => array(
			'type'                 => 'object',
			'additionalProperties' => false,
			'properties'           => array(
				'orders'      => array( 'type' => 'array', 'items' => wpagent_wc_order_output_schema() ),
				'total'       => array( 'type' => 'integer' ),
				'total_pages' => array( 'type' => 'integer' ),
				'page'        => array( 'type' => 'integer' ),
				'per_page'    => array( 'type' => 'integer' ),
			),
			'required'             => array( 'orders', 'total', 'total_pages', 'page', 'per_page' ),
		),
		'execute_callback'    => 'wpagent_exec_list_orders',
		'permission_callback' => 'wpagent_perm_wc_orders_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_orders( $input ) {
	if ( ! wpagent_wc_orders_available() ) {
		return wpagent_wc_orders_missing_error();
	}
	if ( ! current_user_can( 'read_private_shop_orders' ) ) {
		return new WP_Error( 'wpagent_forbidden', __( 'Keine Berechtigung zum Lesen von WooCommerce-Bestellungen.', 'wp-agent-companion' ), array( 'status' => 403 ) );
	}
	$input    = is_array( $input ) ? $input : array();
	$page     = max( 1, absint( $input['page'] ?? 1 ) );
	$per_page = min( 100, max( 1, absint( $input['per_page'] ?? 20 ) ) );
	$args     = array(
		'limit'    => $per_page,
		'paged'    => $page,
		'paginate' => true,
		'orderby'  => 'date',
		'order'    => 'DESC',
		'return'   => 'objects',
	);
	$status = trim( (string) ( $input['status'] ?? '' ) );
	if ( '' !== $status && 'any' !== $status ) {
		$status = wpagent_wc_normalize_order_status( $status );
		if ( is_wp_error( $status ) ) {
			return $status;
		}
		$args['status'] = $status;
	}
	if ( isset( $input['customer_id'] ) ) {
		$customer_id = absint( $input['customer_id'] );
		if ( $customer_id <= 0 || ! get_user_by( 'id', $customer_id ) ) {
			return new WP_Error( 'wpagent_wc_bad_customer_id', __( 'customer_id muss auf einen vorhandenen WordPress-Nutzer zeigen.', 'wp-agent-companion' ), array( 'status' => 400 ) );
		}
		$args['customer_id'] = $customer_id;
	}
	try {
		$result = wc_get_orders( $args );
	} catch ( Throwable $error ) {
		return new WP_Error( 'wpagent_wc_order_query_failed', __( 'Die WooCommerce-Bestellungen konnten nicht sicher abgefragt werden.', 'wp-agent-companion' ), array( 'status' => 500 ) );
	}
	$rows = is_object( $result ) && is_array( $result->orders ?? null ) ? $result->orders : array();
	$orders = array();
	foreach ( $rows as $order ) {
		if ( $order instanceof WC_Order && ! $order instanceof WC_Order_Refund ) {
			$orders[] = wpagent_wc_order_payload(
				$order,
				wpagent_wc_input_is_true( $input['include_customer'] ?? false ),
				wpagent_wc_input_is_true( $input['include_payment'] ?? false ),
				wpagent_wc_input_is_true( $input['include_items'] ?? false )
			);
		}
	}
	return array(
		'orders'      => $orders,
		'total'       => absint( is_object( $result ) ? ( $result->total ?? 0 ) : count( $orders ) ),
		'total_pages' => absint( is_object( $result ) ? ( $result->max_num_pages ?? 0 ) : ( $orders ? 1 : 0 ) ),
		'page'        => $page,
		'per_page'    => $per_page,
	);
}

function wpagent_ability_get_order(): array {
	return array(
		'label'               => __( 'WooCommerce-Bestellung lesen', 'wp-agent-companion' ),
		'description'         => __( 'Liest eine Bestellung über WooCommerce CRUD. Personenbezogene Kunden- und Zahlungsdaten bleiben standardmäßig ausgeblendet.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array(
			'type'                 => 'object',
			'additionalProperties' => false,
			'properties'           => array(
				'order_id'         => array( 'type' => 'integer', 'minimum' => 1 ),
				'include_customer' => array( 'type' => 'boolean', 'default' => false ),
				'include_payment'  => array( 'type' => 'boolean', 'default' => false ),
				'include_items'    => array( 'type' => 'boolean', 'default' => false ),
			),
			'required'             => array( 'order_id' ),
		),
		'output_schema'       => wpagent_wc_order_output_schema(),
		'execute_callback'    => 'wpagent_exec_get_order',
		'permission_callback' => 'wpagent_perm_wc_orders_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_order( $input ) {
	$input = is_array( $input ) ? $input : array();
	$order = wpagent_wc_get_authorized_order( $input, 'read_private_shop_orders' );
	return is_wp_error( $order )
		? $order
		: wpagent_wc_order_payload(
			$order,
			wpagent_wc_input_is_true( $input['include_customer'] ?? false ),
			wpagent_wc_input_is_true( $input['include_payment'] ?? false ),
			wpagent_wc_input_is_true( $input['include_items'] ?? false )
		);
}

function wpagent_ability_list_order_notes(): array {
	return array(
		'label'               => __( 'WooCommerce-Bestellnotizen auflisten', 'wp-agent-companion' ),
		'description'         => __( 'Listet interne und auf Wunsch kundensichtbare Bestellnotizen begrenzt über die WooCommerce-API.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array(
			'type'                 => 'object',
			'additionalProperties' => false,
			'properties'           => array(
				'order_id' => array( 'type' => 'integer', 'minimum' => 1 ),
				'type'     => array( 'type' => 'string', 'enum' => array( 'all', 'internal', 'customer' ), 'default' => 'all' ),
				'limit'    => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => 100, 'default' => 20 ),
			),
			'required'             => array( 'order_id' ),
		),
		'output_schema'       => array(
			'type'                 => 'object',
			'additionalProperties' => false,
			'properties'           => array(
				'notes' => array( 'type' => 'array', 'items' => wpagent_wc_order_note_output_schema() ),
				'total' => array( 'type' => 'integer' ),
			),
			'required'             => array( 'notes', 'total' ),
		),
		'execute_callback'    => 'wpagent_exec_list_order_notes',
		'permission_callback' => 'wpagent_perm_wc_orders_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_order_notes( $input ) {
	$input = is_array( $input ) ? $input : array();
	$order = wpagent_wc_get_authorized_order( $input, 'read_private_shop_orders' );
	if ( is_wp_error( $order ) ) {
		return $order;
	}
	$type = sanitize_key( (string) ( $input['type'] ?? 'all' ) );
	if ( ! in_array( $type, array( 'all', 'internal', 'customer' ), true ) ) {
		return new WP_Error( 'wpagent_wc_bad_note_type', __( 'type muss all, internal oder customer sein.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$limit = min( 100, max( 1, absint( $input['limit'] ?? 20 ) ) );
	$args  = array( 'order_id' => $order->get_id(), 'limit' => $limit, 'orderby' => 'date_created', 'order' => 'DESC' );
	if ( 'all' !== $type ) {
		$args['type'] = $type;
	}
	$notes = array();
	foreach ( wc_get_order_notes( $args ) as $note ) {
		if ( is_object( $note ) ) {
			$notes[] = wpagent_wc_order_note_payload( $note );
		}
	}
	return array( 'notes' => $notes, 'total' => count( $notes ) );
}
