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

/**
 * propertyFeatures Class
 *
 * Class to manage property features e.g. has swimming pool.
 *
 * @package clearFusionCMS\module\property
 */
class propertyFeatures extends flDbNestedSet {
	/**
	 * Construct the object.
	 *
	 * @param flDb $db The database object.
	 */
	function __construct($db) {
		parent::__construct($db, 'cf_property_features_' . clearFusionCMS::getSite(), 'featureid');
	}

	/**
	 * Get/create an instance of the features class.
	 *
	 * @return propertyFeatures The features class.
	 */
	static function getInstance() {
		static $instance = null;

		if(!$instance) {
			$instance = new propertyFeatures(clearFusionCMS::getDb());
		}

		return $instance;
	}

	/**
	 * Get the features available for a property.
	 *
	 * @param int $id The ID of the property to get the feature set for.
	 * @return array The array of feature categories and the features available in each.
	 * @throws flDbException
	 */
	function getFeatures($id) {
		$features = array();

		// Get the feature cats
		$results = self::getChildren(0, array('featureid', 'title'));
		foreach($results as $r) {
			$features[$r['featureid']] = array(
				'title' => $r['title'],
				'features' => array()
			);
		}

		// Get the features in each cat
		$results = $this->db->query('SELECT f.parentid, f.featureid, f.title FROM cf_property_features_map_' . clearFusionCMS::getSite() . ' AS fm, cf_property_features_' . clearFusionCMS::getSite() . ' AS  f WHERE propertyid=? && fm.featureid=f.featureid && !disabled ORDER BY lft', $id);
		while($row = $results->fetch()) {
			$features[$row['parentid']]['features'][$row['featureid']] = $row['title'];
		}

		return $features;
	}
}