<?php
/**
 * Global Search handler.
 *
 * @package automation-web-platform
 */

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

/**
 * Class WAWP_Global_Search
 * Handles global search functionality across the plugin.
 */
class WAWP_Global_Search {
	/**
	 * Singleton instance.
	 *
	 * @var WAWP_Global_Search|null
	 */
	private static $instance = null;

	/**
	 * Get instance.
	 *
	 * @return WAWP_Global_Search
	 */
	public static function get_instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Register REST routes.
	 */
	public function register_routes() {
		register_rest_route(
			'wawp/v1',
			'/global-search',
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'handle_search' ),
				'permission_callback' => array( $this, 'check_permission' ),
				'args'                => array(
					'q'       => array(
						'required'          => true,
						'sanitize_callback' => 'sanitize_text_field',
					),
					'sources' => array(
						'required'          => false,
						'sanitize_callback' => 'sanitize_text_field',
						'default'           => 'plugin,users',
					),
				),
			)
		);
	}

	/**
	 * Check if user has permission to search.
	 *
	 * @return bool
	 */
	public function check_permission() {
		return current_user_can( WAWP_CAPABILITY );
	}

	/**
	 * Handle search request.
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response
	 */
	public function handle_search( $request ) {
		$query   = mb_strtolower( trim( $request->get_param( 'q' ) ) );
		$sources = explode( ',', $request->get_param( 'sources' ) );

		if ( mb_strlen( $query ) < 2 ) {
			return rest_ensure_response( array( 'results' => array() ) );
		}

		$results = array();

		// 1. Search Plugin Sections (Handled client-side in React for 0ms speed).

		// 2. Search WordPress Users.
		if ( in_array( 'users', $sources, true ) ) {
			$user_args = array(
				'search'         => '*' . $query . '*',
				'search_columns' => array( 'user_login', 'user_email', 'user_nicename', 'display_name' ),
				'number'         => 10,
			);

			// Also search in meta values (phone numbers).
			global $wpdb;
			$phone_like    = '%' . $wpdb->esc_like( $query ) . '%';
			$meta_user_ids = WAWP()->db->get_col_cached(
				$wpdb->prepare( "SELECT user_id FROM %i WHERE meta_key IN ('billing_phone', '_wawp_phone', 'phone') AND meta_value LIKE %s LIMIT 10", $wpdb->usermeta, $phone_like ),
				'search_users_meta_' . md5( $query ),
				'wawp_search',
				300
			);

			$user_query_search = new WP_User_Query( $user_args );
			$users_from_search = $user_query_search->get_results();

			$users_from_meta = array();
			if ( ! empty( $meta_user_ids ) ) {
				foreach ( $meta_user_ids as $muid ) {
					$u = get_userdata( $muid );
					if ( $u ) {
						$users_from_meta[] = $u;
					}
				}
			}

			$users = array_unique( array_merge( $users_from_search, $users_from_meta ), SORT_REGULAR );

			foreach ( $users as $user ) {
				$first_name = get_user_meta( $user->ID, 'first_name', true );
				$last_name  = get_user_meta( $user->ID, 'last_name', true );
				$phone      = WAWP()->user_manager->get_user_phone( $user->ID );
				$full_name  = trim( $first_name . ' ' . $last_name );
				if ( ! $full_name ) {
					$full_name = $user->display_name;
				}

				$results[] = array(
					'title'         => $full_name,
					'description'   => $user->user_email . ( $phone ? ' • ' . $phone : '' ),
					'section'       => 'user_profile',
					'icon'          => 'Users',
					'link'          => get_edit_user_link( $user->ID ),
					'source'        => 'users',
					'user_id'       => $user->ID,
					'thumbnail_url' => get_avatar_url( $user->ID, array( 'size' => 96 ) ),
				);
			}
		}

		// 3. Search WooCommerce Orders & Subscriptions.
		if ( ( in_array( 'orders', $sources, true ) || in_array( 'subscriptions', $sources, true ) ) && class_exists( 'WooCommerce' ) ) {
			$post_types = array( 'shop_order' );
			if ( post_type_exists( 'shop_subscription' ) ) {
				$post_types[] = 'shop_subscription';
			}

			// Search by ID.
			$order_by_id = null;
			if ( is_numeric( $query ) ) {
				$order_by_id = get_post( (int) $query );
				if ( $order_by_id && in_array( $order_by_id->post_type, $post_types, true ) ) {
					$this->add_order_to_results( $order_by_id, $results );
				}
			}

			// Search by Meta (Email / Phone).
			global $wpdb;
			$query_like     = '%' . $wpdb->esc_like( $query ) . '%';
			$meta_order_ids = WAWP()->db->get_col_cached(
				$wpdb->prepare( "SELECT post_id FROM %i WHERE meta_key IN ('_billing_email', '_billing_phone') AND meta_value LIKE %s LIMIT 10", $wpdb->postmeta, $query_like ),
				'search_orders_meta_' . md5( $query ),
				'wawp_search',
				300
			);

			$order_posts = array();
			if ( ! empty( $meta_order_ids ) ) {
				$order_query = new WP_Query(
					array(
						'post_type'      => $post_types,
						'post_status'    => 'any',
						'post__in'       => $meta_order_ids,
						'posts_per_page' => 10,
					)
				);
				$order_posts = $order_query->posts;
			}

			foreach ( $order_posts as $order_post ) {
				if ( $order_by_id && $order_post->ID === $order_by_id->ID ) {
					continue;
				}
				$this->add_order_to_results( $order_post, $results );
			}
		}

		// 4. Search WooCommerce Products.
		if ( in_array( 'products', $sources, true ) && class_exists( 'WooCommerce' ) ) {
			$product_query = new WP_Query(
				array(
					'post_type'      => 'product',
					'post_status'    => 'publish',
					's'              => $query,
					'posts_per_page' => 10,
				)
			);

			foreach ( $product_query->posts as $product_post ) {
				$product       = wc_get_product( $product_post->ID );
				$p_thumb_id    = get_post_thumbnail_id( $product_post->ID );
				$p_thumb       = $p_thumb_id ? wp_get_attachment_image_src( $p_thumb_id, 'thumbnail' ) : false;
				$thumbnail_url = $p_thumb ? $p_thumb[0] : '';
				$results[]     = array(
					'title'         => $product->get_name(),
					'description'   => $product->get_sku() ? 'SKU: ' . $product->get_sku() : 'Price: ' . $product->get_price(),
					'section'       => 'product',
					'icon'          => 'Package',
					'link'          => admin_url( 'post.php?post=' . $product_post->ID . '&action=edit' ),
					'source'        => 'products',
					'thumbnail_url' => $thumbnail_url,
				);
			}
		}

		// 5. Search WooCommerce Coupons.
		if ( in_array( 'coupons', $sources, true ) && class_exists( 'WooCommerce' ) ) {
			$coupon_query = new WP_Query(
				array(
					'post_type'      => 'shop_coupon',
					'post_status'    => 'publish',
					's'              => $query,
					'posts_per_page' => 10,
				)
			);

			foreach ( $coupon_query->posts as $coupon_post ) {
				$coupon    = new WC_Coupon( $coupon_post->post_title );
				$results[] = array(
					'title'       => strtoupper( $coupon_post->post_title ),
					'description' => 'Discount Type: ' . $coupon->get_discount_type() . ' • Amount: ' . $coupon->get_amount(),
					'section'     => 'coupons',
					'icon'        => 'Crown',
					'link'        => admin_url( 'post.php?post=' . $coupon_post->ID . '&action=edit' ),
					'source'      => 'coupons',
				);
			}
		}

		// 6. Search Wawp Broadcast Campaigns.
		if ( in_array( 'campaign_broadcasts', $sources, true ) ) {
			global $wpdb;
			$camp_table = $wpdb->prefix . 'wawp_campaigns';
			$camp_like  = '%' . $wpdb->esc_like( $query ) . '%';
			$camps      = WAWP()->db->get_results_cached(
				$wpdb->prepare( 'SELECT id, name, status, total_count, processed_count FROM %i WHERE name LIKE %s LIMIT 10', $camp_table, $camp_like ),
				'search_campaigns_' . md5( $query ),
				'wawp_search',
				300
			);

			if ( ! empty( $camps ) ) {
				foreach ( $camps as $camp ) {
					$results[] = array(
						'title'       => $camp['name'],
						'description' => 'Status: ' . ucfirst( $camp['status'] ) . ' • Total Recipients: ' . $camp['total_count'] . ' • Sent: ' . $camp['processed_count'],
						'section'     => 'campaigns',
						'icon'        => 'Target',
						'link'        => admin_url( 'admin.php?page=wawp&wawp_section=campaigns' ),
						'source'      => 'campaign_broadcasts',
					);
				}
			}
		}

		// 7. Search Wawp Notification Rules.
		if ( in_array( 'notification_rules', $sources, true ) ) {
			global $wpdb;
			$flows_table = $wpdb->prefix . 'wawp_flows';
			$flow_like   = '%' . $wpdb->esc_like( $query ) . '%';
			$flows       = WAWP()->db->get_results_cached(
				$wpdb->prepare( 'SELECT id, name, trigger_key, status FROM %i WHERE name LIKE %s LIMIT 10', $flows_table, $flow_like ),
				'search_flows_' . md5( $query ),
				'wawp_search',
				300
			);

			if ( ! empty( $flows ) ) {
				foreach ( $flows as $flow ) {
					$results[] = array(
						'title'       => str_replace( 'Migrated: ', '', $flow['name'] ),
						'description' => 'Trigger: ' . ucfirst( str_replace( '_', ' ', $flow['trigger_key'] ) ) . ' • Status: ' . ucfirst( $flow['status'] ),
						'section'     => 'notifications',
						'icon'        => 'Zap',
						'link'        => admin_url( 'admin.php?page=wawp&wawp_section=notifications' ),
						'source'      => 'notification_rules',
					);
				}
			}
		}

		// 8. Search WordPress Posts.
		if ( in_array( 'posts', $sources, true ) ) {
			$posts_query = new WP_Query(
				array(
					'post_type'      => 'post',
					'post_status'    => 'publish',
					's'              => $query,
					'posts_per_page' => 10,
				)
			);

			foreach ( $posts_query->posts as $p_post ) {
				$p_thumb_id    = get_post_thumbnail_id( $p_post->ID );
				$p_thumb       = $p_thumb_id ? wp_get_attachment_image_src( $p_thumb_id, 'thumbnail' ) : false;
				$thumbnail_url = $p_thumb ? $p_thumb[0] : '';
				$results[]     = array(
					'title'         => $p_post->post_title,
					'description'   => 'WordPress Post • Status: ' . ucfirst( $p_post->post_status ),
					'section'       => 'post',
					'icon'          => 'FileText',
					'link'          => admin_url( 'post.php?post=' . $p_post->ID . '&action=edit' ),
					'source'        => 'posts',
					'thumbnail_url' => $thumbnail_url,
				);
			}
		}

		// 9. Search WordPress Pages.
		if ( in_array( 'pages', $sources, true ) ) {
			$pages_query = new WP_Query(
				array(
					'post_type'      => 'page',
					'post_status'    => 'publish',
					's'              => $query,
					'posts_per_page' => 10,
				)
			);

			foreach ( $pages_query->posts as $page_post ) {
				$p_thumb_id    = get_post_thumbnail_id( $page_post->ID );
				$p_thumb       = $p_thumb_id ? wp_get_attachment_image_src( $p_thumb_id, 'thumbnail' ) : false;
				$thumbnail_url = $p_thumb ? $p_thumb[0] : '';
				$results[]     = array(
					'title'         => $page_post->post_title,
					'description'   => 'WordPress Page • Status: ' . ucfirst( $page_post->post_status ),
					'section'       => 'page',
					'icon'          => 'FileText',
					'link'          => admin_url( 'post.php?post=' . $page_post->ID . '&action=edit' ),
					'source'        => 'pages',
					'thumbnail_url' => $thumbnail_url,
				);
			}
		}

		// 10. Search WordPress Media Library.
		if ( in_array( 'media', $sources, true ) ) {
			$media_query = new WP_Query(
				array(
					'post_type'      => 'attachment',
					'post_status'    => 'inherit',
					's'              => $query,
					'posts_per_page' => 10,
				)
			);

			foreach ( $media_query->posts as $media_post ) {
				$thumbnail_url = '';
				if ( strpos( $media_post->post_mime_type, 'image/' ) === 0 ) {
					$img_src = wp_get_attachment_image_src( $media_post->ID, 'thumbnail' );
					if ( $img_src ) {
						$thumbnail_url = $img_src[0];
					}
				}
				$results[] = array(
					'title'         => $media_post->post_title ? $media_post->post_title : basename( $media_post->guid ),
					'description'   => 'Media File • Type: ' . $media_post->post_mime_type,
					'section'       => 'media',
					'icon'          => 'Image',
					'link'          => admin_url( 'post.php?post=' . $media_post->ID . '&action=edit' ),
					'source'        => 'media',
					'thumbnail_url' => $thumbnail_url,
				);
			}
		}

		// 11. Search WooCommerce & WordPress Categories & Tags.
		if ( in_array( 'categories', $sources, true ) ) {
			$taxonomies = array( 'product_cat', 'category', 'product_tag', 'post_tag' );
			$terms      = get_terms(
				array(
					'taxonomy'   => $taxonomies,
					'search'     => $query,
					'hide_empty' => false,
					'number'     => 10,
				)
			);

			if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
				foreach ( $terms as $term ) {
					$results[] = array(
						'title'       => $term->name,
						'description' => 'Taxonomy: ' . ucfirst( str_replace( '_', ' ', $term->taxonomy ) ) . ' • Count: ' . $term->count,
						'section'     => 'category',
						'icon'        => 'Folder',
						'link'        => admin_url( 'term.php?taxonomy=' . $term->taxonomy . '&tag_ID=' . $term->term_id ),
						'source'      => 'categories',
					);
				}
			}
		}

		// 12. Add Direct Activity Hub Search Entry.
		$results[] = array(
			'title'       => 'Search Activity Hub: "' . esc_html( $query ) . '"',
			'description' => 'Deep search logs by email, phone, or other criteria.',
			'section'     => 'activity_hub',
			'icon'        => 'History',
			'link'        => admin_url( 'admin.php?page=wawp&wawp_section=activity_hub&search=' . rawurlencode( $query ) ),
			'source'      => 'plugin',
		);

		return rest_ensure_response(
			array(
				'success' => true,
				'query'   => $query,
				'results' => $results,
			)
		);
	}

	/**
	 * Add order to results.
	 *
	 * @param WP_Post $order_post Post object.
	 * @param array   $results Results array.
	 */
	private function add_order_to_results( $order_post, &$results ) {
		$order = wc_get_order( $order_post->ID );
		if ( ! $order ) {
			return;
		}

		$is_sub = 'shop_subscription' === $order_post->post_type;
		$title  = ( $is_sub ? 'Sub #' : 'Order #' ) . $order->get_order_number();

		// Robust edit link building.
		$link = admin_url( 'post.php?post=' . $order_post->ID . '&action=edit' );
		if ( class_exists( '\Automattic\WooCommerce\Utilities\OrderUtil' ) && method_exists( '\Automattic\WooCommerce\Utilities\OrderUtil', 'custom_orders_table_usage_is_enabled' ) ) {
			if ( \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled() ) {
				$link = admin_url( 'admin.php?page=wc-orders&action=edit&id=' . $order_post->ID );
			}
		}

		$results[] = array(
			'title'       => $title,
			'description' => $order->get_billing_first_name() . ' ' . $order->get_billing_last_name() . ' • ' . $order->get_billing_email(),
			'section'     => $is_sub ? 'subscription' : 'order',
			'icon'        => $is_sub ? 'RefreshCw' : 'ShoppingCart',
			'link'        => $link,
			'source'      => $is_sub ? 'subscriptions' : 'orders',
		);
	}
}
