<?php
/*****************************************************************************
 * ViewPeople.php
 * Contains the people index controller
 *
 * Kabuki CMS (C) 2013-2015, Aaron van Geffen
 *****************************************************************************/

class ViewPeople extends HTMLController
{
	const PER_PAGE = 24;

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

		$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
		$start = ($page - 1) * self::PER_PAGE;
		$total_count = Tag::getCount(1, 'Person');

		// Fetch subalbums.
		$subalbums = Tag::getPeople(0, $start, self::PER_PAGE);

		// What assets are we using?
		$id_assets = array_map(function($album) {
			return (int) $album['id_asset_thumb'];
		}, $subalbums);

		// Fetch assets for thumbnails.
		$assets = Asset::fromIds($id_assets, 'object');

		// Build album list.
		$albums = [];
		foreach ($subalbums as $album)
		{
			$albums[$album['id_tag']] = [
				'id_tag' => $album['id_tag'],
				'caption' => $album['tag'],
				'link' => BASEURL . '/' . $album['slug'] . '/',
				'thumbnail' => !empty($album['id_asset_thumb']) ? $assets[$album['id_asset_thumb']]->getImage() : null,
			];
		}

		parent::__construct('People - ' . SITE_TITLE);
		$this->page->adopt(new AlbumIndex($albums));

		$pagination = new PageIndex([
			'recordCount' => $total_count,
			'items_per_page' => self::PER_PAGE,
			'start' => $start,
			'base_url' => BASEURL . '/people/',
			'page_slug' => 'page/%PAGE%/',
		]);
		$this->page->adopt(new Pagination($pagination));

		$this->page->setCanonicalUrl(BASEURL . '/people/' . ($page > 1 ? 'page/' . $page . '/' : ''));
	}
}