<?php
/**
 * ANCP Core - people search helper.
 *
 * Member search by name within a tree, used by AP Family Trees' search
 * widget/block/shortcode. Exposed as a static method on the core data layer
 * (the suite convention - no global functions in the shared library).
 *
 * @package AncestorPress\Core
 * @since   2.0.0
 */

namespace AncestorPress\Core;

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

/**
 * People search (static core API).
 *
 * @since 0.16.2
 */
class People_Table_Search {

	/**
	 * Search members by name within a tree.
	 *
	 * @param  string $gedcom          Tree identifier.
	 * @param  string $query           Search string (partial name).
	 * @param  bool   $include_living  Whether to include living persons.
	 * @param  int    $limit           Max results to return.
	 * @return array
	 */
	public static function search( $gedcom, $query, $include_living = false, $limit = 30 ) {
		global $wpdb;

		$query = trim( $query );
		if ( '' === $query || '' === $gedcom ) {
			return array();
		}

		$table = Tables::people();
		$like  = '%' . $wpdb->esc_like( $query ) . '%';

		if ( $include_living ) {
			// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- own table; identifier bound via %i.
			return $wpdb->get_results(
				$wpdb->prepare(
					"SELECT id, personID, firstname, lastname, birthdate, deathdate, living, private
					 FROM %i
					 WHERE gedcom = %s
					   AND private = 0
					   AND ( firstname LIKE %s OR lastname LIKE %s
					         OR CONCAT( COALESCE(firstname,''), ' ', COALESCE(lastname,'') ) LIKE %s )
					 ORDER BY lastname ASC, firstname ASC
					 LIMIT %d",
					$table,
					$gedcom,
					$like,
					$like,
					$like,
					$limit
				)
			);
			// phpcs:enable
		}

		// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- own table; identifier bound via %i.
		return $wpdb->get_results(
			$wpdb->prepare(
				"SELECT id, personID, firstname, lastname, birthdate, deathdate, living, private
				 FROM %i
				 WHERE gedcom = %s
				   AND private = 0
				   AND living  = 0
				   AND ( firstname LIKE %s OR lastname LIKE %s
				         OR CONCAT( COALESCE(firstname,''), ' ', COALESCE(lastname,'') ) LIKE %s )
				 ORDER BY lastname ASC, firstname ASC
				 LIMIT %d",
				$table,
				$gedcom,
				$like,
				$like,
				$like,
				$limit
			)
		);
		// phpcs:enable
	}
}

// Note: there is deliberately no global apft_search_members() wrapper in this
// library. AP Family Trees 1.2+ calls this static method directly; older
// Trees releases bundle their own core copy and never load this file beside
// a plugin that requires it (version negotiation plus the ONS sibling guard).
