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

/**
 * propertyInstall Class
 *
 * Class for managing the property module installation.
 *
 * @package clearFusionCMS\module\property
 */
class propertyInstall implements cfInstallInterface {
	/**
	 * The last error message.
	 *
	 * @var string
	 */
	protected $lastError = '';

	/**
	 * Return the last error.
	 *
	 * @return string The last error string.
	 */
	function getLastError() {
		return $this->lastError;
	}

	/**
	 * Create the tables for the site.
	 *
	 * @param flDb $db The database object.
	 * @param string $site The site name.
	 */
	function createTables($db, $site) {

		// Create the database tables
		$db->query("CREATE  TABLE IF NOT EXISTS `cf_property_{$site}` (
  `propertyid` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
  `regionid` INT UNSIGNED NOT NULL ,
  `addedat` DATETIME NOT NULL ,
  `published` TINYINT NOT NULL DEFAULT 0,
  `category` ENUM('buy', 'rent') NOT NULL DEFAULT 'buy',
  `tenure` ENUM('freehold', 'leasehold', 'sharedfreehold', 'rental') NOT NULL DEFAULT 'freehold',
  `price_period` ENUM('buy', 'per_week', 'per_month') NOT NULL DEFAULT 'buy',
  `typeid` INT UNSIGNED NOT NULL DEFAULT 0,
  `price` decimal(13,4) NOT NULL,
  `deposit` decimal(13,4) NOT NULL,
  `lat` DECIMAL(10, 8) NOT NULL DEFAULT 0,
  `lng` DECIMAL(11, 8) NOT NULL DEFAULT 0,
  `bedrooms` tinyint(4) NOT NULL,
  `bathrooms` tinyint(4) NOT NULL DEFAULT '0',
  `ensuite` tinyint(4) NOT NULL DEFAULT '0',
  `parking` tinyint(4) NOT NULL DEFAULT '0',
  `reception` tinyint(4) NOT NULL DEFAULT '0',
  `featured` tinyint(1) NOT NULL DEFAULT '0',
  `sold` tinyint(1) NOT NULL DEFAULT '0',
  `countrycode` CHAR(2) NOT NULL DEFAULT '',
  `slug` VARCHAR(255) NOT NULL ,
  `title` VARCHAR(255) NOT NULL ,
  `reference` VARCHAR(255) NOT NULL DEFAULT '',
  `street1` varchar(200) NOT NULL DEFAULT '',
  `street2` varchar(200) NOT NULL DEFAULT '',
  `city` varchar(50) NOT NULL DEFAULT '',
  `state` varchar(50) NOT NULL DEFAULT '',
  `postcode` varchar(20) NOT NULL DEFAULT '',
  `fileext` VARCHAR(4) NOT NULL ,
  `ogtitle` VARCHAR(255) NOT NULL DEFAULT '',
  `ogdesc` VARCHAR(255) NOT NULL DEFAULT '',
  `twittertitle` VARCHAR(255) NOT NULL DEFAULT '',
  `twitterdesc` VARCHAR(255) NOT NULL DEFAULT '',
  `meta_title` VARCHAR(255) NOT NULL DEFAULT '',
  `meta_description` VARCHAR(255) NOT NULL DEFAULT '',
  `meta_keywords` VARCHAR(255) NOT NULL DEFAULT '',
  `content1` MEDIUMTEXT NOT NULL ,
  PRIMARY KEY (`propertyid`),
  UNIQUE INDEX `slug` (`slug` ASC, `regionid` ASC) ,
  INDEX `regionid` (`regionid` ASC) ,
  INDEX `category` (`category` ASC) ,
  INDEX `typeid` (`typeid` ASC) ,
  INDEX `featured` (`featured` ASC) ,
  INDEX `published` (`published` ASC) )
ENGINE = MyISAM
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci
");

		$db->query("CREATE  TABLE IF NOT EXISTS `cf_property_region_{$site}` (
  `regionid` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
  `parentid` INT UNSIGNED NOT NULL ,
  `lft` INT UNSIGNED NOT NULL ,
  `rgt` INT UNSIGNED NOT NULL ,
  `lftrgtset` linestring NOT NULL,
  `title` VARCHAR(255) NOT NULL ,
  PRIMARY KEY (`regionid`) ,
  INDEX `parentid` (`parentid` ASC) ,
  INDEX `lft` (`lft` ASC) ,
  INDEX `rgt` (`rgt` ASC) ,
  SPATIAL INDEX `lftrgtset` (`lftrgtset` ASC) )
ENGINE = MyISAM
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci
");

		$db->query("CREATE  TABLE IF NOT EXISTS `cf_property_type_{$site}` (
  `typeid` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
  `parentid` INT UNSIGNED NOT NULL ,
  `lft` INT UNSIGNED NOT NULL ,
  `rgt` INT UNSIGNED NOT NULL ,
  `lftrgtset` linestring NOT NULL,
  `title` VARCHAR(255) NOT NULL ,
  PRIMARY KEY (`typeid`),
  INDEX `parentid` (`parentid` ASC) ,
  INDEX `lft` (`lft` ASC) ,
  INDEX `rgt` (`rgt` ASC) ,
  SPATIAL INDEX `lftrgtset` (`lftrgtset` ASC) )
ENGINE = MyISAM
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci
");

		$db->query("CREATE TABLE IF NOT EXISTS `cf_property_features_{$site}` (
  `featureid` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `parentid` INT UNSIGNED NOT NULL,
  `lft` INT UNSIGNED NOT NULL ,
  `rgt` INT UNSIGNED NOT NULL ,
  `lftrgtset` linestring NOT NULL,
  `disabled` tinyint(4) NOT NULL,
  `title` VARCHAR(255) NOT NULL,
  PRIMARY KEY (`featureid`),
  INDEX `parentid` (`parentid` ASC) ,
  INDEX `lft` (`lft` ASC) ,
  INDEX `rgt` (`rgt` ASC) ,
  SPATIAL INDEX `lftrgtset` (`lftrgtset` ASC) )
ENGINE=MyISAM
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci");

		$db->query("CREATE TABLE `cf_property_features_map_{$site}` (
  `propertyid` INT UNSIGNED NOT NULL,
  `featureid` INT UNSIGNED NOT NULL,
  PRIMARY KEY (`propertyid`,`featureid`) )
ENGINE=MyISAM
DEFAULT CHARACTER SET=utf8
COLLATE = utf8_general_ci
");

		$db->query("CREATE  TABLE IF NOT EXISTS `cf_property_flds_{$site}` (
  `fldid` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
  `disporder` INT NOT NULL ,
  `fldtype` TINYINT UNSIGNED NOT NULL ,
  `fieldname` VARCHAR(255) NOT NULL ,
  `editor` VARCHAR(64) NOT NULL DEFAULT '' ,
  `snippet` VARCHAR(64) NOT NULL DEFAULT '' ,
  PRIMARY KEY (`fldid`) )
ENGINE = MyISAM
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci
");
		$db->insert("cf_property_flds_{$site}", array('disporder' => 0, 'fieldname' => 'Description', 'fldtype' => 1));

		$db->query("CREATE  TABLE IF NOT EXISTS `cf_property_rgnflds_{$site}` (
  `rgnfldid` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
  `disporder` INT NOT NULL ,
  `fldtype` TINYINT UNSIGNED NOT NULL ,
  `fieldname` VARCHAR(255) NOT NULL ,
  PRIMARY KEY (`rgnfldid`) )
ENGINE = MyISAM
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci
");

		$db->query("CREATE  TABLE IF NOT EXISTS `cf_property_gal_{$site}` (
  `galid` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
  `propertyid` INT UNSIGNED NOT NULL ,
  `disporder` INT NOT NULL ,
  `imgtype` ENUM('normal', 'floorplan', 'epc') NOT NULL DEFAULT 'normal' ,
  `fileext` VARCHAR(4) NOT NULL ,
  `title` VARCHAR(255) NOT NULL ,
  PRIMARY KEY (`galid`) ,
  INDEX `propertyid` (`propertyid` ASC) ,
  INDEX `floorplan` (`floorplan` ASC) )
ENGINE = MyISAM
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci
");
	}

	/**
	 * Delete the tables.
	 *
	 * @param flDb $db The database object.
	 * @param string $site The name of the site to delete the table.
	 */
	function deleteTables($db, $site) {
		$db->query("DROP TABLE IF EXISTS cf_property_{$site}");
		$db->query("DROP TABLE IF EXISTS cf_property_region_{$site}");
		$db->query("DROP TABLE IF EXISTS cf_property_type_{$site}");
		$db->query("DROP TABLE IF EXISTS cf_property_features_{$site}");
		$db->query("DROP TABLE IF EXISTS cf_property_features_map_{$site}");
		$db->query("DROP TABLE IF EXISTS cf_property_flds_{$site}");
		$db->query("DROP TABLE IF EXISTS cf_property_rgnflds_{$site}");
		$db->query("DROP TABLE IF EXISTS cf_property_gal_{$site}");
	}

	/**
	 * Install the module.
	 *
	 * @param flDb The database object to use.
	 * @return bool true if installed; else false.
	 */
	function install($db) {
		// Add to all sites
		$siteMgr = new cfSiteManager($db);
		$sites = $siteMgr->listSites();
		foreach($sites as $site => $n) {
			$this->createSite($db, $site);
		}

		// Create permissions
		$ac = new flAcMgr($db);
		$ac->createPermissionGroup('cfProperty', __noop('Property'), 'propertyBackend'); // 5000
		$ac->createPermission('cfProperty.regions', __noop('Can manage property regions.'), 5010, 'propertyBackend');
		$ac->createPermission('cfProperty.properties', __noop('Can manage properties.'), 5020, 'propertyBackend');
		$ac->createPermission('cfProperty.types', __noop('Can manage property types.'), 5030, 'propertyBackend');
		$ac->createPermission('cfProperty.features', __noop('Can manage property features.'), 5040, 'propertyBackend');
		$ac->createPermission('cfProperty.settings', __noop('Can manage property module settings.'), 5050, 'propertyBackend');
		$ac->createPermission('cfProperty.fields', __noop('Can edit property fields.'), 5060, 'propertyBackend');

		// Create dashboard icon groups
		$dmgr = new cfDashboardMgr($db);
		$dmgr->addGroup('cfProperty', 2400, __noop('Property'), 'propertyBackend');
		$dmgr->setGroupFAIcon('cfProperty', 'fa-home');
		$dmgr->setGroupMDIcon('cfProperty', 'domain');

		// Add property icons
		$dmgr->addIcon('cfProperty', 'cfProperty.properties', 'cfProperty.properties', __noop('Properties'), __noop('Manage properties.'), 'system/modules/property/images/property.svg', 'property', 'properties', 'propertyBackend');
		$dmgr->addIcon('cfProperty', 'cfProperty.types', 'cfProperty.types', __noop('Types'), __noop('Manage property types.'), 'system/modules/property/images/type.svg', 'property', 'type', 'propertyBackend');
		$dmgr->addIcon('cfProperty', 'cfProperty.features', 'cfProperty.features', __noop('Features'), __noop('Manage property features.'), 'system/modules/property/images/features.svg', 'property', 'feature', 'propertyBackend');
		$dmgr->addIcon('cfProperty', 'cfProperty.fields', 'cfProperty.fields',  __noop('Property Fields'),  __noop('Manage property fields.'), 'system/modules/property/images/propertyfields.svg', 'property', 'fields', 'propertyBackend');
		$dmgr->addIcon('cfProperty', 'cfProperty.rgnfields', 'cfProperty.fields',  __noop('Region Fields'),  __noop('Manage region fields.'), 'system/modules/property/images/propertyfields.svg', 'property', 'rgnfields', 'propertyBackend');
		$dmgr->addIcon('cfProperty', 'cfProperty.regions', 'cfProperty.regions', __noop('Regions'), __noop('Manage regions.'), 'system/modules/property/images/region.svg', 'property', 'region', 'propertyBackend');

		// Define additional strings that may not show else where
		__noop('Buy');
		__noop('Rent');
		__noop('Freehold');
		__noop('Leasehold');
		__noop('Shared Freehold');

		return true;
	}

	/**
	 * Uninstall the module.
	 *
	 * @param flDb The database object to use.
	 * @return bool true if uninstalled; else false.
	 */
	function uninstall($db) {

		// Remove from dashboard
		$dmgr = new cfDashboardMgr($db);
		$dmgr->delIcon('cfProperty.properties');
		$dmgr->delGroup('cfProperty');

		// Remove permissions
		$ac = new flAcMgr($db);
		$ac->deletePermissionGroup('cfProperty');

		// Delete the tables
		$siteMgr = new cfSiteManager($db);
		$sites = $siteMgr->listSites();
		foreach($sites as $site => $n) {
			$this->deleteSite($db, $site);
		}

		$cfg = clearFusionCMS::getSiteConfig('cfSystemFileStore');
		@rmdir($cfg->privateStorage . '/property/');
		@rmdir($cfg->publicStorage . '/property/');

		// Tell everyone this module has been removed
		clearFusionCMS::getEventManager()->notify(new flEvent('system.moduleRemoved', array(
			'module' => 'property'
		)));

		return true;
	}

	/**
	 * Upgrade the module.
	 *
	 * @param flDb The database object to use.
	 * @param string $installedVer The installed version.
	 * @return bool true if upgraded; else false.
	 */
	function upgrade($db, $installedVer) {

		return true;
	}

	/**
	 * Create a new site.
	 *
	 * @param flDb $db The database object.
	 * @param string $site The short name of the site.
	 * @return bool true if the site was created; else false.
	 */
	function createSite($db, $site) {
		$this->createTables($db, $site);

		$siteMgr = new cfSiteManager($db);
		$cfg = $siteMgr->getSiteCfg('cfProperty', $site);
		$cfg->tw = '64';
		$cfg->th = '64';
		$cfg->tcrop = '1';
		$cfg->sw = '150';
		$cfg->sh = '150';
		$cfg->scrop = '1';
		$cfg->mw = '320';
		$cfg->mh = '320';
		$cfg->mcrop = '1';
		$cfg->lw = '640';
		$cfg->lh = '480';
		$cfg->lcrop = '0';

		// Currency formatting
		$cfg->curleft = '$';
		$cfg->curright = '';
		$cfg->thoussep = ',';
		$cfg->decpoint = '.';
		$cfg->numdecimals = '2';

		return true;
	}

	/**
	 * Delete a site.
	 *
	 * @param flDb $db The database object.
	 * @param string $site The name of the site to delete.
	 * @return bool true if the site was deleted; else false.
	 */
	function deleteSite($db, $site) {
		$this->deleteTables($db, $site);

		// Delete the config data for the site
		$siteMgr = new cfSiteManager($db);
		$cfg = $siteMgr->getSiteCfg('cfProperty', $site);
		$cfg->deleteNamespace();

		// Delete thumbnails for site
		$cfg = clearFusionCMS::getSiteConfig('cfSystemFileStore');
		$path = $cfg->privateStorage . '/property/' . $site . '/';

		$top = glob($path . '*', GLOB_NOSORT | GLOB_ONLYDIR);
		foreach($top as $td) {
			$files = glob("$td/*.*", GLOB_NOSORT);
			foreach($files as $f) {
				@unlink($f);
			}
			@rmdir($td);
		}
		@rmdir($path);

		$path = $cfg->publicStorage . '/property/' . $site . '/';

		$top = glob($path . '*', GLOB_NOSORT | GLOB_ONLYDIR);
		foreach($top as $td) {
			$files = glob("$td/*.*", GLOB_NOSORT);
			foreach($files as $f) {
				@unlink($f);
			}
			@rmdir($td);
		}
		@rmdir($path);

		return true;
	}
}
