<?php

/**
 * 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
 */

/**
 * propertySearchHelper Class
 *
 * Class to provide support for search to gain access to properties.
 *
 * @package clearFusionCMS\module\property
 */
class propertySearchHelper extends cfSearchHelper {

	/**
	 * The table name.
	 *
	 * @var string
	 */
	protected $table;

	/**
	 * Create the helper object.
	 *
	 * @param flDb $db The database object.
	 */
	function __construct($db) {
		parent::__construct($db);
		$this->table = 'cf_property_' . clearFusionCMS::getSite();
	}

	/**
	 * Get the number of content items.
	 */
	function getContentCount() {
		return $this->db->fetchOne("SELECT COUNT(*) FROM $this->table");
	}

	/**
	 * Reindex the block of items.
	 *
	 * @param int $start The index to start working from.
	 * @param int $items The number of items to index.
	 */
	function reindex($start, $items) {
		$regions = new propertyRegions($this->db);

		// Grab the next block of images and send to search
		$result = $this->db->query("SELECT propertyid,regionid,street1,street2,city,state,postcode,price,addedat,category,bedrooms,bathrooms,parking,title FROM $this->table LIMIT $start, $items");
		while($row = $result->fetch()) {
			$res = $regions->getPath($row['regionid'], array('regionid'));
			$segs = array('property');
			foreach($res as $r)
				$segs[] = $r['regionid'];
			$segs[] = $row['propertyid'];

			// Send to search
			clearFusionCMS::getEventManager()->notify(new flEvent('system.searchIndex', array(
				'path' => $segs,
				'accessPerm' => '',
				'publishedAt' => $row['addedat'],
				'fields' => array(
					'property.title' => $row['title'],
					'property.address' => $row['street1'] . ' ' . $row['street2'] . ' ' . $row['city'] . ' ' . $row['state'] . ' ' . $row['postcode'],
					'property.price' => $row['price'],
					'property.category' => $row['category'] == 'buy' ? 1 : 0,
					'property.bedrooms' => $row['bedrooms'],
					'property.bathrooms' => $row['bathrooms'],
					'property.parking' => $row['parking']
				))));
		}
	}

	/**
	 * Get the search summary for the given search path.
	 *
	 * @param string $id The ID of the element to get a summary of.
	 * @param string $order The order to use data to generate the summary or null for the default.
	 * @param int $words The number of words to return in the summary.
	 * @return array The summary data.
	 */
	function getSearchSummary($id, $order = null, $words = 30) {
		if(!($row = $this->db->fetchRow("SELECT title,sold,street1,street2,city,state,postcode,price,regionid,slug,fileext,category,shortdesc,price_period FROM $this->table WHERE propertyid=?", $id)))
			return false;

		$uri = $img = '';
		$content = new cfContent($this->db, clearFusionCMS::getSite());
		if($container = $content->getContainer('property.' . $row['category'] . '.' . $row['regionid'])) {
			$route = $content->getContainerRoute($container, ':slug');
			$uri = $route->assemble(array('slug' => $row['slug']));

			$imgRoute = $content->getContainerRoute($container, 'images/:size/:slug', array(), array(), $row['fileext']);
			$img = empty($row['fileext']) ? '' : $imgRoute->assemble(array('size' => 's', 'slug' => $row['slug']));
		}

		$title = $row['street1'];
		if(!empty($row['street2']))
			$title .= ', ' . $row['street2'];
		if(!empty($row['city']))
			$title .= ', ' . $row['city'];
		if(!empty($row['state']))
			$title .= ', ' . $row['state'];
		if(!empty($row['postcode']))
			$title .= ', ' . $row['postcode'];


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

		$cfg = clearFusionCMS::getSiteConfig('cfProperty');
		return array(
			'title' => $row['title'],
			'address' => $title,
			'summary' => str_replace(array('[', ']'), array('&#91;', '&#93;'), flTextSplitWords::split($row['shortdesc'], $words)),
			'uri' => $uri,
			'img' => $img,
			'price' => $cfg->curleft . number_format($row['price'], $cfg->numdecimals, $cfg->decpoint, $cfg->thoussep) . $cfg->curright . $period,
			'property' => 1,
			'sold' => $row['sold'],
			'soldLabel' => $row['category'] == 'buy' ? __('Sold', 'cfProperty') : __('Rented', 'cfProperty')
		);
	}

	/**
	 * Get the URI of the page holding the content.
	 *
	 * @param string $id The ID of the element to get the page URI of.
	 * @param bool $absolute true if an absolute URI should be returned; else false for a relative URI.
	 * @return string The URI of the page or false if not found.
	 */
	function getURI($id, $absolute = false) {
		if($row = $this->db->fetchRow("SELECT regionid,slug,category FROM $this->table WHERE propertyid=?", $id)) {
			$content = new cfContent($this->db, clearFusionCMS::getSite());
			if($container = $content->getContainer('property.' . $row['category'] . '.' . $row['regionid'])) {
				$route = $content->getContainerRoute($container, ':slug');
				return $route->assemble(array('slug' => $row['slug']), $absolute);
			}
		}

		return false;
	}
}
