<?php

class PeepSoHashtagsAjax extends PeepSoAjaxCallback
{
	const SUGGESTION_LIMIT = 8;

	/**
	 * Return hashtag suggestions for the given query. Used by the postbox hashtag dropdown.
	 */
	public function get_hashtags(PeepSoAjaxResponse $resp)
	{
		global $wpdb;

		$query = trim((string) $this->_input->value('query', '', FALSE));

		// Strip leading '#' if the client included it.
		if ('' !== $query && '#' === $query[0]) {
			$query = substr($query, 1);
		}

		$limit = (int) apply_filters('peepso_hashtag_suggestions_limit', self::SUGGESTION_LIMIT);
		$limit = max(1, min(50, $limit));

		$hashtags = array();

		if ('' === $query) {
			// No query yet — return the most-used hashtags.
			$sql = $wpdb->prepare(
				"SELECT ht_name, ht_count FROM {$wpdb->prefix}peepso_hashtags ORDER BY ht_count DESC, ht_name ASC LIMIT %d",
				$limit
			);
		} else {
			$like = $wpdb->esc_like($query) . '%';
			$sql = $wpdb->prepare(
				"SELECT ht_name, ht_count FROM {$wpdb->prefix}peepso_hashtags WHERE ht_name LIKE %s ORDER BY ht_count DESC, ht_name ASC LIMIT %d",
				$like,
				$limit
			);
		}

		$rows = $wpdb->get_results($sql);
		if (is_array($rows)) {
			foreach ($rows as $row) {
				$hashtags[] = array(
					'name' => $row->ht_name,
					'count' => (int) $row->ht_count,
				);
			}
		}

		$hashtags = apply_filters('peepso_hashtag_suggestions', $hashtags, $query);

		$resp->success(TRUE);
		$resp->set('hashtags', $hashtags);
	}
}

// EOF
