<?php

/**
 * Snippet to draw a single property image.
 *
 * 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\property
 * @copyright Copyright (c) 2016 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

if(isset($id)) {
	/* @var $tplEngine cfTemplateEngine */
	$controller = $tplEngine->controller;

	$size = isset($size) && preg_match('/^[tsmlo]$/', $size) ? $size : 'm';

	$db = clearFusionCMS::getDb();
	if(($item = $db->fetchRow("SELECT propertyid,title,street1,street2,city,state,postcode,fileext,slug,regionid,addedat,category FROM cf_property_" . clearFusionCMS::getSite() . ' WHERE propertyid=? && published', $id)) &&
		($container = $controller->content->getContainer('property.' . $item['category'] . '.' . $item['regionid']))) {
		$route = $controller->content->getContainerRoute($container, 'images/:size/:slug', array(), array(), $item['fileext']);

		if(isset($linkOnly) && $linkOnly) {
			echo $route->assemble(array('size' => $size, 'slug' => $item['slug']), isset($abs) && $abs ? true : false);
		}
		else {

			$imageTpl = isset($imageTpl) ? $tplEngine->getChunk($imageTpl) : '[[if &subject=`[[+link]]` &operator=`!empty` &then=`<a href="[[+link]]"><img src="[[+src]]" alt="[[+title]]" /></a>` &else=`<img src="[[+src]]" alt="[[+title]]" />`]]';

			$addr = array();
			if(!empty($item['street1']))
				$addr[] = $item['street1'];
			if(!empty($item['street2']))
				$addr[] = $item['street2'];
			if(!empty($item['city']))
				$addr[] = $item['city'];
			if(!empty($item['state']))
				$addr[] = $item['state'];
			if(!empty($item['postcode']))
				$addr[] = $item['postcode'];
			$addr = join(', ', $addr);

			$d = array(
				'id'      => $id,
				'src'     => $route->assemble(array('size' => $size, 'slug' => $item['slug']), isset($abs) && $abs ? true : false),
				'title'   => $item['title'],
				'address' => $addr,
				'added'   => new flDate($item['addedat'] . ' UTC', clearFusionCMS::getSysTimezone())
			);

			echo $tplEngine->parseString($imageTpl, $d);
		}
	}
}
