<?php
namespace WpRigel\Commandify;

defined( 'ABSPATH' ) || exit;

/**
 * Register search commands for all post types and other content
 * Hooks into commandify_register_commands at priority 10 (before navigation at 20)
 */
add_action(
	'commandify_register_commands',
	function () {
		// Register search commands for all public post types dynamically.
		$post_types = get_post_types(
			array(
				'show_ui'      => true,
				'show_in_menu' => true,
				'public'       => true,
			),
			'objects'
		);

		foreach ( $post_types as $post_type ) {
			// Skip attachments as we handle them separately.
			if ( 'attachment' === $post_type->name ) {
				continue;
			}

			// Allow other integrations to exclude post types from auto-registration.
			$excluded_post_types = apply_filters( 'commandify_excluded_post_types', array() );
			if ( in_array( $post_type->name, $excluded_post_types, true ) ) {
				continue;
			}

			// Get post type labels.
			$label    = $post_type->labels->name;
			$singular = $post_type->labels->singular_name;

			// Determine icon.
			$icon = 'dashicons-admin-post';
			if ( isset( $post_type->menu_icon ) && ! empty( $post_type->menu_icon ) ) {
				$icon = $post_type->menu_icon;
			} elseif ( 'post' === $post_type->name ) {
				$icon = 'dashicons-admin-post';
			} elseif ( 'page' === $post_type->name ) {
				$icon = 'dashicons-admin-page';
			}

			// Determine capability.
			$capability = $post_type->cap->edit_posts ?? 'edit_posts';

			// Build keywords.
			$keywords   = array( 'search', 'find' );
			$keywords[] = strtolower( $label );
			$keywords[] = strtolower( $singular );
			if ( 'post' === $post_type->name ) {
				$keywords[] = 'articles';
				$keywords[] = 'blog';
			}

			// Determine priority.
			$priority = 50;
			if ( 'post' === $post_type->name ) {
				$priority = 70;
			} elseif ( 'page' === $post_type->name ) {
				$priority = 65;
			}

			// Determine context screens where this search is contextually relevant.
			$search_context = array(
				'edit-' . $post_type->name,
				$post_type->name,
				'post' === $post_type->name ? 'post-new' : $post_type->name . '-new',
			);

			commandify_register_command(
				array(
					'id'          => 'search-' . $post_type->name,
					/* translators: %s: Post type label (Posts, Pages, etc.) */
					'title'       => sprintf( __( 'Search %s', 'commandify' ), $label ),
					/* translators: %s: Post type label in lowercase */
					'description' => sprintf( __( 'Find %s by title or content', 'commandify' ), strtolower( $label ) ),
					'type'        => 'search',
					'callback'    => function ( $query, $context ) use ( $post_type ) {
						return search_post_type_callback( $query, $context, $post_type->name );
					},
					'category'    => 'content',
					'icon'        => $icon,
					'keywords'    => $keywords,
					'capability'  => $capability,
					'priority'    => $priority,
					/* translators: %s: Post type label in lowercase */
					'placeholder' => sprintf( __( 'Search %s...', 'commandify' ), strtolower( $label ) ),
					'min_chars'   => 2,
					'context'     => $search_context,
				)
			);
		}//end foreach

		// Search Users.
		commandify_register_command(
			array(
				'id'          => 'search-users',
				'title'       => __( 'Search Users', 'commandify' ),
				'description' => __( 'Find users by name or email', 'commandify' ),
				'type'        => 'search',
				'callback'    => 'WpRigel\Commandify\search_users_callback',
				'category'    => 'users',
				'icon'        => 'dashicons-admin-users',
				'keywords'    => array( 'search', 'users', 'find', 'people' ),
				'capability'  => 'list_users',
				'priority'    => 60,
				'placeholder' => __( 'Search users...', 'commandify' ),
				'min_chars'   => 2,
				'context'     => array( 'users', 'user-edit', 'user-new' ),
			)
		);

		// Search Media.
		commandify_register_command(
			array(
				'id'          => 'search-media',
				'title'       => __( 'Search Media', 'commandify' ),
				'description' => __( 'Find media files by name', 'commandify' ),
				'type'        => 'search',
				'callback'    => 'WpRigel\Commandify\search_media_callback',
				'category'    => 'content',
				'icon'        => 'dashicons-admin-media',
				'keywords'    => array( 'search', 'media', 'find', 'images', 'files' ),
				'capability'  => 'upload_files',
				'priority'    => 55,
				'placeholder' => __( 'Search media...', 'commandify' ),
				'min_chars'   => 2,
				'context'     => array( 'upload', 'attachment' ),
			)
		);
	},
	10
);

// Unified callback function for all post types.
function search_post_type_callback( $query, $context, $post_type_name ) {
	$post_type_obj = get_post_type_object( $post_type_name );
	if ( ! $post_type_obj ) {
		return array();
	}

	$args = array(
		's'              => sanitize_text_field( $query ),
		'post_type'      => $post_type_name,
		'post_status'    => 'any',
		'posts_per_page' => 10,
		'orderby'        => 'relevance',
	);

	$posts   = get_posts( $args );
	$results = array();

	// Get icon.
	$icon = 'dashicons-admin-post';
	if ( isset( $post_type_obj->menu_icon ) && ! empty( $post_type_obj->menu_icon ) ) {
		$icon = $post_type_obj->menu_icon;
	} elseif ( 'page' === $post_type_name ) {
		$icon = 'dashicons-admin-page';
	}

	foreach ( $posts as $post ) {
		$status_text = ucfirst( $post->post_status );
		$date_text   = get_the_date( 'M j, Y', $post );

		$description_parts = array( $status_text, $date_text );
		if ( 'post' === $post_type_name ) {
			$description_parts[] = get_the_author_meta( 'display_name', $post->post_author );
		}

		$actions = array(
			array(
				'id'       => 'edit-' . $post_type_name . '-' . $post->ID,
				'title'    => __( 'Edit', 'commandify' ),
				'type'     => 'navigation',
				'callback' => get_edit_post_link( $post->ID, 'raw' ),
				'icon'     => 'dashicons-edit',
				'target'   => '_self',
			),
		);

		// Add preview action (works for both published and draft posts).
		$preview_url = get_preview_post_link( $post->ID );
		if ( $preview_url ) {
			$actions[] = array(
				'id'       => 'preview-' . $post_type_name . '-' . $post->ID,
				'title'    => __( 'Preview', 'commandify' ),
				'type'     => 'navigation',
				'callback' => $preview_url,
				'icon'     => 'dashicons-visibility',
				'target'   => '_blank',
			);
		}

		// Add view action if post type is publicly viewable and post is published.
		if ( $post_type_obj->public && 'publish' === $post->post_status && get_permalink( $post->ID ) ) {
			$actions[] = array(
				'id'       => 'view-' . $post_type_name . '-' . $post->ID,
				'title'    => __( 'View', 'commandify' ),
				'type'     => 'navigation',
				'callback' => get_permalink( $post->ID ),
				'icon'     => 'dashicons-external',
				'target'   => '_blank',
			);
		}

		// Add trash/delete action
		$actions[] = array(
			'id'                   => 'trash-' . $post_type_name . '-' . $post->ID,
			'title'                => 'trash' === $post->post_status ? __( 'Delete Permanently', 'commandify' ) : __( 'Move to Trash', 'commandify' ),
			'type'                 => 'action',
			'icon'                 => 'dashicons-trash',
			'has_dynamic_callback' => true,
			'confirm'              => 'trash' === $post->post_status ? array(
				/* translators: %s: Post type singular label in lowercase */
				'message'     => sprintf( __( 'Permanently delete this %s?', 'commandify' ), strtolower( $post_type_obj->labels->singular_name ) ),
				'destructive' => true,
			) : false,
		);

		$results[] = array(
			'id'          => $post_type_name . '-' . $post->ID,
			'title'       => $post->post_title ?: __( '(No title)', 'commandify' ),
			'description' => implode( ' • ', $description_parts ),
			'type'        => 'submenu',
			'icon'        => $icon,
			'category'    => $post_type_name,
			'actions'     => $actions,
		);
	}//end foreach

	return $results;
}

function search_users_callback( $query ) {
	$args = array(
		'search'  => '*' . sanitize_text_field( $query ) . '*',
		'number'  => 10,
		'orderby' => 'display_name',
	);

	$users   = get_users( $args );
	$results = array();

	foreach ( $users as $user ) {
		$roles_text = ! empty( $user->roles ) ? ucfirst( $user->roles[0] ) : __( 'No role', 'commandify' );

		$results[] = array(
			'id'          => 'user-' . $user->ID,
			'title'       => $user->display_name,
			/* translators: 1: Email address or filename, 2: Role or file size */
			'description' => sprintf( __( '%1$s • %2$s', 'commandify' ), $user->user_email, $roles_text ),
			'type'        => 'submenu',
			'icon'        => 'dashicons-admin-users',
			'category'    => 'users',
			'actions'     => array(
				array(
					'id'       => 'edit-user-' . $user->ID,
					'title'    => __( 'Edit Profile', 'commandify' ),
					'type'     => 'navigation',
					'callback' => get_edit_user_link( $user->ID ),
					'icon'     => 'dashicons-edit',
					'target'   => '_self',
				),
				array(
					'id'       => 'view-user-posts-' . $user->ID,
					'title'    => __( 'View Posts', 'commandify' ),
					'type'     => 'navigation',
					'callback' => admin_url( 'edit.php?author=' . $user->ID ),
					'icon'     => 'dashicons-admin-post',
					'target'   => '_self',
				),
				array(
					'id'       => 'email-user-' . $user->ID,
					'title'    => __( 'Send Email', 'commandify' ),
					'type'     => 'navigation',
					'callback' => 'mailto:' . $user->user_email,
					'icon'     => 'dashicons-email',
					'target'   => '_blank',
				),
			),
		);
	}//end foreach

	return $results;
}

function search_media_callback( $query ) {
	$args = array(
		's'              => sanitize_text_field( $query ),
		'post_type'      => 'attachment',
		'post_status'    => 'any',
		'posts_per_page' => 10,
	);

	$attachments = get_posts( $args );
	$results     = array();

	foreach ( $attachments as $attachment ) {
		$file     = get_attached_file( $attachment->ID );
		$filename = basename( $file );
		$filesize = file_exists( $file ) ? size_format( filesize( $file ) ) : '';

		$results[] = array(
			'id'          => 'media-' . $attachment->ID,
			'title'       => $attachment->post_title ?: $filename,
			/* translators: 1: Email address or filename, 2: Role or file size */
			'description' => sprintf( __( '%1$s • %2$s', 'commandify' ), $filename, $filesize ),
			'type'        => 'submenu',
			'icon'        => 'dashicons-admin-media',
			'category'    => 'media',
			'actions'     => array(
				array(
					'id'       => 'edit-media-' . $attachment->ID,
					'title'    => __( 'Edit', 'commandify' ),
					'type'     => 'navigation',
					'callback' => admin_url( 'post.php?post=' . $attachment->ID . '&action=edit' ),
					'icon'     => 'dashicons-edit',
					'target'   => '_self',
				),
				array(
					'id'       => 'view-media-' . $attachment->ID,
					'title'    => __( 'View', 'commandify' ),
					'type'     => 'navigation',
					'callback' => wp_get_attachment_url( $attachment->ID ),
					'icon'     => 'dashicons-visibility',
					'target'   => '_blank',
				),
				array(
					'id'                   => 'delete-media-' . $attachment->ID,
					'title'                => __( 'Delete Permanently', 'commandify' ),
					'type'                 => 'action',
					'icon'                 => 'dashicons-trash',
					'has_dynamic_callback' => true,
					'confirm'              => array(
						'message'     => __( 'Permanently delete this media file?', 'commandify' ),
						'destructive' => true,
					),
				),
			),
		);
	}//end foreach

	return $results;
}
