<?php
/** Read-only native Spectra administration abilities. */

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

/** @return array<string,mixed> */
function wpagent_spectra_read_ability( string $label, string $description, array $input, array $output, string $callback ): array {
	return array(
		'label' => $label, 'description' => $description, 'category' => 'wp-agent',
		'input_schema' => $input, 'output_schema' => $output, 'execute_callback' => $callback,
		'permission_callback' => 'wpagent_perm_manage_options',
		'meta' => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true ) ),
	);
}

function wpagent_ability_list_spectra_blocks(): array {
	return wpagent_spectra_read_ability(
		__( 'Spectra-Blöcke auflisten', 'wp-agent-companion' ),
		__( 'Liest Spectras sichtbare Blockbibliothek und den nativen Aktivierungsstatus samt Konflikt-Hash.', 'wp-agent-companion' ),
		array(
			'type' => 'object',
			'properties' => array(
				'search' => array( 'type' => 'string', 'maxLength' => 200, 'default' => '' ),
				'status' => array( 'type' => 'string', 'enum' => array( 'all', 'enabled', 'disabled' ), 'default' => 'all' ),
				'page' => array( 'type' => 'integer', 'minimum' => 1, 'default' => 1 ),
				'per_page' => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => 100, 'default' => 50 ),
			),
			'additionalProperties' => false, 'default' => array(),
		),
		array(
			'type' => 'object', 'properties' => array(
				'version' => array( 'type' => 'string' ), 'items' => array( 'type' => 'array', 'items' => wpagent_spectra_block_schema() ),
				'total' => array( 'type' => 'integer' ), 'page' => array( 'type' => 'integer' ), 'per_page' => array( 'type' => 'integer' ),
				'total_pages' => array( 'type' => 'integer' ), 'hash' => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
			),
			'required' => array( 'version', 'items', 'total', 'page', 'per_page', 'total_pages', 'hash' ), 'additionalProperties' => false,
		),
		'wpagent_exec_list_spectra_blocks'
	);
}

function wpagent_ability_list_spectra_popups(): array {
	return wpagent_spectra_read_ability(
		__( 'Spectra-Popups auflisten', 'wp-agent-companion' ),
		__( 'Listet Spectra-Popups und Banner mit sicher ausgewählten Einstellungen und Zustands-Hashes auf.', 'wp-agent-companion' ),
		array(
			'type' => 'object', 'properties' => array(
				'search' => array( 'type' => 'string', 'maxLength' => 200, 'default' => '' ),
				'status' => array( 'type' => 'string', 'enum' => array( 'any', 'draft', 'pending', 'private', 'publish', 'trash' ), 'default' => 'any' ),
				'type' => array( 'type' => 'string', 'enum' => array( 'any', 'unset', 'popup', 'banner' ), 'default' => 'any' ),
				'enabled' => array( 'type' => 'boolean' ), 'page' => array( 'type' => 'integer', 'minimum' => 1, 'default' => 1 ),
				'per_page' => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => 100, 'default' => 50 ),
				'order' => array( 'type' => 'string', 'enum' => array( 'asc', 'desc' ), 'default' => 'desc' ),
				'order_by' => array( 'type' => 'string', 'enum' => array( 'id', 'date', 'modified', 'title' ), 'default' => 'modified' ),
			), 'additionalProperties' => false, 'default' => array(),
		),
		array(
			'type' => 'object', 'properties' => array(
				'items' => array( 'type' => 'array', 'items' => wpagent_spectra_popup_summary_schema() ),
				'total' => array( 'type' => 'integer' ), 'page' => array( 'type' => 'integer' ), 'per_page' => array( 'type' => 'integer' ),
				'total_pages' => array( 'type' => 'integer' ),
			), 'required' => array( 'items', 'total', 'page', 'per_page', 'total_pages' ), 'additionalProperties' => false,
		),
		'wpagent_exec_list_spectra_popups'
	);
}

function wpagent_ability_get_spectra_popup(): array {
	return wpagent_spectra_read_ability(
		__( 'Spectra-Popup lesen', 'wp-agent-companion' ),
		__( 'Liest ein Spectra-Popup samt Blockstruktur, sicheren Einstellungen und Konflikt-Hash, aber ohne fremde Metadaten.', 'wp-agent-companion' ),
		array( 'type' => 'object', 'properties' => array( 'id' => array( 'type' => 'integer', 'minimum' => 1 ) ), 'required' => array( 'id' ), 'additionalProperties' => false ),
		wpagent_spectra_popup_schema(),
		'wpagent_exec_get_spectra_popup'
	);
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_list_spectra_blocks( $input ) {
	$input     = is_array( $input ) ? $input : array();
	$registry  = wpagent_spectra_block_registry();
	$snapshot  = wpagent_spectra_block_option_snapshot();
	if ( is_wp_error( $registry ) ) return $registry;
	if ( is_wp_error( $snapshot ) ) return $snapshot;
	$search = isset( $input['search'] ) ? trim( sanitize_text_field( (string) $input['search'] ) ) : '';
	$requested_status = $input['status'] ?? 'all';
	$status = in_array( $requested_status, array( 'all', 'enabled', 'disabled' ), true ) ? $requested_status : 'all';
	$page = max( 1, absint( $input['page'] ?? 1 ) );
	$per_page = max( 1, min( 100, absint( $input['per_page'] ?? 50 ) ) );
	$items = array();
	foreach ( $registry as $definition ) {
		$item = wpagent_spectra_block_state( $definition, $snapshot['value'] );
		if ( '' !== $search && false === stripos( implode( "\n", array( $item['slug'], $item['title'], $item['description'], implode( ' ', $item['categories'] ) ) ), $search ) ) continue;
		if ( 'enabled' === $status && ! $item['enabled'] ) continue;
		if ( 'disabled' === $status && $item['enabled'] ) continue;
		$items[] = $item;
	}
	$total = count( $items );
	return array(
		'version' => wpagent_spectra_version(), 'items' => array_slice( $items, ( $page - 1 ) * $per_page, $per_page ),
		'total' => $total, 'page' => $page, 'per_page' => $per_page, 'total_pages' => (int) ceil( $total / $per_page ), 'hash' => $snapshot['hash'],
	);
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_list_spectra_popups( $input ) {
	$available = wpagent_spectra_require_available();
	if ( is_wp_error( $available ) ) return $available;
	$input = is_array( $input ) ? $input : array();
	$page = max( 1, absint( $input['page'] ?? 1 ) );
	$per_page = max( 1, min( 100, absint( $input['per_page'] ?? 50 ) ) );
	$requested_status = $input['status'] ?? 'any';
	$status = in_array( $requested_status, array( 'any', 'draft', 'pending', 'private', 'publish', 'trash' ), true ) ? $requested_status : 'any';
	$requested_type = $input['type'] ?? 'any';
	$type = in_array( $requested_type, array( 'any', 'unset', 'popup', 'banner' ), true ) ? $requested_type : 'any';
	$order = 'asc' === ( $input['order'] ?? 'desc' ) ? 'ASC' : 'DESC';
	$order_by_map = array( 'id' => 'ID', 'date' => 'date', 'modified' => 'modified', 'title' => 'title' );
	$order_by = $order_by_map[ $input['order_by'] ?? 'modified' ] ?? 'modified';
	$args = array(
		'post_type' => 'spectra-popup', 'post_status' => 'any' === $status ? array( 'draft', 'pending', 'private', 'publish', 'trash' ) : $status,
		'posts_per_page' => $per_page, 'paged' => $page, 'orderby' => $order_by, 'order' => $order,
		's' => trim( sanitize_text_field( (string) ( $input['search'] ?? '' ) ) ), 'no_found_rows' => false,
		'update_post_meta_cache' => true, 'update_post_term_cache' => false,
	);
	$meta_query = array( 'relation' => 'AND' );
	if ( 'popup' === $type || 'banner' === $type ) {
		$meta_query[] = array( 'key' => 'spectra-popup-type', 'value' => $type, 'compare' => '=' );
	} elseif ( 'unset' === $type ) {
		$meta_query[] = array(
			'relation' => 'OR',
			array( 'key' => 'spectra-popup-type', 'compare' => 'NOT EXISTS' ),
			array( 'key' => 'spectra-popup-type', 'value' => array( 'popup', 'banner' ), 'compare' => 'NOT IN' ),
		);
	}
	if ( array_key_exists( 'enabled', $input ) ) {
		$enabled = wpagent_spectra_boolean( $input['enabled'], 'enabled' );
		if ( is_wp_error( $enabled ) ) return $enabled;
		$meta_query[] = $enabled
			? array( 'key' => 'spectra-popup-enabled', 'value' => array( '', '0', 'false' ), 'compare' => 'NOT IN' )
			: array(
				'relation' => 'OR',
				array( 'key' => 'spectra-popup-enabled', 'compare' => 'NOT EXISTS' ),
				array( 'key' => 'spectra-popup-enabled', 'value' => array( '', '0', 'false' ), 'compare' => 'IN' ),
			);
	}
	if ( count( $meta_query ) > 1 ) $args['meta_query'] = $meta_query;
	$query = new WP_Query( $args );
	$items = array();
	foreach ( $query->posts as $post ) {
		$state = wpagent_spectra_popup_state( $post, false );
		if ( is_wp_error( $state ) ) return $state;
		$items[] = $state;
	}
	return array( 'items' => $items, 'total' => (int) $query->found_posts, 'page' => $page, 'per_page' => $per_page, 'total_pages' => (int) $query->max_num_pages );
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_get_spectra_popup( $input ) {
	$available = wpagent_spectra_require_available();
	if ( is_wp_error( $available ) ) return $available;
	$post_id = absint( is_array( $input ) ? ( $input['id'] ?? 0 ) : 0 );
	if ( ! current_user_can( 'edit_post', $post_id ) ) {
		return new WP_Error( 'wpagent_spectra_popup_forbidden', __( 'Keine Berechtigung, dieses Spectra-Popup zu lesen.', 'wp-agent-companion' ), array( 'status' => 403 ) );
	}
	$post = wpagent_spectra_get_popup( $post_id );
	if ( is_wp_error( $post ) ) {
		return new WP_Error( 'wpagent_spectra_popup_forbidden', __( 'Keine Berechtigung, dieses Spectra-Popup zu lesen.', 'wp-agent-companion' ), array( 'status' => 403 ) );
	}
	return wpagent_spectra_popup_state( $post, true );
}
