<?php

/**
 * Snippet to draw a featured property.
 *
 * 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
 */

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

if(($item = $db->fetchRow("SELECT propertyid,sold,title,street1,street2,city,state,postcode,price,shortdesc,fileext,slug,regionid,addedat,category FROM cf_property_" . clearFusionCMS::getSite() . ' WHERE featured && published && propertyid >= FLOOR(RAND() * (SELECT MAX(propertyid) FROM cf_property_' . clearFusionCMS::getSite() . ' WHERE featured && published)) LIMIT 1')) &&
	($container = $controller->content->getContainer('property.' . $item['category'] . '.' . $item['regionid']))) {
	$route = $controller->content->getContainerRoute($container, ':slug');
	$imgRoute = $controller->content->getContainerRoute($container, 'images/:size/:slug', array(), array(), $item['fileext']);

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

	$cfg = clearFusionCMS::getSiteConfig('cfProperty');

	$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);

	$period = '';
	if($item['category'] == 'rent') {
		if($item['price_period'] == 'per_week')
			$period = __(' p/w', 'property');
		else if($item['price_period'] == 'per_month')
			$period = __(' p/m', 'property');
	}

	$d = array(
		'id'        => $item['propertyid'],
		'imgsrc'    => $imgRoute->assemble(array('size' => $size, 'slug' => $item['slug'])),
		'title'     => $item['title'],
		'address'   => $addr,
		'added'     => new flDate($item['addedat'] . ' UTC', clearFusionCMS::getSysTimezone()),
		'link'      => $route->assemble(array('slug' => $item['slug'])),
		'shortdesc' => $item['shortdesc'],
		'price'     => $cfg->curleft . number_format($item['price'], $cfg->numdecimals, $cfg->decpoint, $cfg->thoussep) . $cfg->curright . $period,
		'sold'      => $item['sold'],
		'soldLabel' => $item['category'] == 'buy' ? __('Sold', 'cfProperty') : __('Rented', 'cfProperty')
	);

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