<?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($_REQUEST['type']))
			throw new UnexpectedValueException('Unsupported autosuggest request.');

		if ($_REQUEST['type'] === 'tags' && isset($_REQUEST['data']))
			return $this->handleTagSearch();

		if ($_REQUEST['type'] === 'createtag' && isset($_REQUEST['tag']))
			return $this->handleTagCreation();
	}

	private function handleTagSearch()
	{
		{
			$data = array_unique(explode(' ', urldecode($_REQUEST['data'])));
			$data = array_filter($data, function($item) {
				return strlen($item) >= 2;
			});

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

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

			$results = Tag::matchPeople($data);
			foreach ($results as $id_tag => $tag)
				$this->payload['items'][] = [
					'label' => $tag['tag'],
					'id_tag' => $id_tag,
					'url' => BASEURL . '/' . $tag['slug'] . '/',
				];
		}
	}

	private function handleTagCreation()
	{
		// It better not already exist!
		if (Tag::exactMatch($_REQUEST['tag']))
		{
			$this->payload = ['error' => true, 'msg' => 'Tag already exists!'];
			return;
		}

		$label = htmlentities(trim($_REQUEST['tag']));
		$slug = strtr($label, [' ' => '-']);
		$tag = Tag::createNew([
			'tag' => $label,
			'kind' => 'Person',
			'slug' => $slug,
		]);

		// Did we succeed?
		if (!$tag)
		{
			$this->payload = ['error' => true, 'msg' => 'Could not create tag.'];
			return;
		}

		$this->payload = [
			'success' => true,
			'label' => $tag->tag,
			'id_tag' => $tag->id_tag,
		];
	}
}