<?php

/**
 * Snippet to draw the paginated testimonial archive.
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package clearFusionCMS\module\testimonials
 * @copyright Copyright (c) 2017 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

/* @var $tplEngine cfTemplateEngine */
$controller = $tplEngine->controller;
$content = $controller->content;
$db = clearFusionCMS::getDb();

$limit = isset($limit) ? $limit : 10;
$size = isset($size) ? $size : 's';

$archiveRoute = $content->getContainerRoute($controller->pageData['id'], ':marker/:page', ['marker' => 'page', 'page' => '0'], ['marker' => 'page', 'page' => '\d+']);

$segs = $controller->getRequest()->getSegments();
if($params = $archiveRoute->match($segs)) {
	$results = $db->query('SELECT SQL_CALC_FOUND_ROWS id,dateoftestimonial,gender,age,fileext,author,location,occupation,website,company,testimonial FROM cf_testimonials_' . clearFusionCMS::getSite() . ' WHERE published ORDER BY dateoftestimonial DESC LIMIT ' . ($params['page'] * $limit) . ",$limit");
	$totalTestimonials = $db->fetchOne('SELECT FOUND_ROWS()');
	if($results->numRows()) {
		$testimonialRoute = $content->getContainerRoute($controller->pageData['id'], 'testimonial/:id', array(), array('id' => '\d+'));

		// Create pagination widget
		$pagination = new flWidgetPagination($params['page'], $totalTestimonials, $limit);
		$pagination->setRoute($archiveRoute, [], 'page', [], 'page');

		// If outside page bounds
		if($pagination->getPage() > $pagination->getNumPages() || $pagination->getPage() < 0)
			$controller->getResponse()->redirectTo($archiveRoute->assemble(array(), true));

		// Sort out image size
		$cfg = clearFusionCMS::getSiteConfig('cfTestimonials');
		$w = $cfg->get($size . 'w');
		$h = $cfg->get($size . 'h');
		if($cfg->get($size . 'crop'))
			$imgSize = "width=\"$w\" height=\"$h\"";
		else
			$imgSize = '';

		$imgRouteCache = [];

		// Draw the testimonials
		$html = '';
		while($row = $results->fetch()) {

			if(empty($row['fileext']))
				$src = '';
			else {
				if(!isset($imgRouteCache[$row['fileext']])) {
					$imgRouteCache[$row['fileext']] = $content->getContainerRoute($controller->pageData['id'], 'images/:size/:id', array(), array('size' => '[tsml]', 'id' => '\d+'), $row['fileext']);
				}
				$src = $imgRouteCache[$row['fileext']]->assemble(array('size' => $size, 'id' => $row['id']));
			}

			$pub = new flDate($row['dateoftestimonial'] . ' UTC', clearFusionCMS::getSysTimezone());
			$html .= $tplEngine->parseChunk('testimonials.archiveItem', array(
				'dategiven' => $pub->toString(flDate::DATE),
				'gender' => $row['gender'] == 'm' ? 'Male' : 'Female',
				'age' => $row['age'],
				'author' => $row['author'],
				'location' => $row['location'],
				'occupation' => $row['occupation'],
				'company' => $row['company'],
				'website' => $row['website'],
				'testimonial' => flTextSplitWords::split(cfContentFilter::apply($cfg->get('filter', ''), $row['testimonial']), isset($params['words']) ? $params['words'] : 100),
				'testimonialURI' => $testimonialRoute->assemble(array('id' => $row['id'])),
				'image' => $src,
				'image_size' => $imgSize,
				'continueReading' => __('continue reading', 'testimonials')
			));
		}

		echo $tplEngine->parseChunk('testimonials.archiveWrapper', [
			'testimonials' => $html,
			'pagination' => $pagination->render()
		]);
	}
	else
		throw new flExceptionNotFound();
}
else if(count($segs))
	throw new flExceptionNotFound();
