<?php
/*****************************************************************************
 * ProvideAutoSuggest.php
 * Contains the autosuggest provider.
 *
 * Kabuki CMS (C) 2013-2015, Aaron van Geffen
 *****************************************************************************/

class ProvideAutoSuggest extends JSONController
{
	public function __construct()
	{
		// Ensure we're logged in at this point.
		if (!Registry::get('user')->isLoggedIn())
			throw new NotAllowedException();

		if (!isset($_GET['type']))
			throw new UnexpectedValueException('Unsupported autosuggest request.');

		if ($_GET['type'] === 'tags' && isset($_GET['data']))
		{
			$data = array_unique(explode(' ', urldecode($_GET['data'])));
			$data = array_filter($data, function($item) {
				return strlen($item) >= 3;
			});

			$this->payload = ['items' => []];

			// Nothing to look for?
			if (count($data) === 0)
				return;

			$results = Tag::match($data);
			foreach ($results as $id_tag => $tag)
				$this->payload['items'][] = [
					'label' => $tag,
					'id_tag' => $id_tag,
				];
		}
	}
}