<?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 - 2017 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

/**
 * propertySettings Class
 *
 * Class to implement settings for the property module.
 *
 * @package clearFusionCMS\module\property
 */
class propertySettings implements cfModuleSettingsInterface {

	/**
	 * Get a list of settings groups.
	 *
	 * @return array Array of setting groups, name => func name
	 */
	function getSettingsGroups() {
		if(!clearFusionCMS::getUser()->hasPermission('cfProperty.settings'))
			return array();

		return array(
			__('Price Formatting', 'propertyBackend') => 'price',
			__('Images Sizes', 'propertyBackend') => 'images',
			__('Region', 'propertyBackedn') => 'region'
		);
	}

	/**
	 * Implement image size settings.
	 *
	 * @param flForm $form The form object to use.
	 * @param flDb $db The database object.
	 * @return bool true if the settings were updated, false if failed to update or null if no change.
	 */
	function imagesSetting($form, $db) {
		if(!clearFusionCMS::getUser()->hasPermission('cfProperty.settings'))
			return null;

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

		// tiny
		$tw = new flFormElementInteger($form, 'tw', 10, null, $cfg->tw);
		$tw->setLabel(__('Image Width', 'propertyBackend'))
			->setRequired()
			->addValidator(new flFormValidatorRequired());

		$th = new flFormElementInteger($form, 'th', 10, null, $cfg->th);
		$th->setLabel(__('Image Height', 'propertyBackend'))
			->setRequired()
			->addValidator(new flFormValidatorRequired());

		$tcrop = new flFormElementCheckbox($form, 'tcrop', $cfg->tcrop);
		$tcrop->setLabel(__('Crop Image to Size', 'propertyBackend'))
			->setDescription(__('If checked then the image will be scaled and cropped to the exact width and height; if not checked the image will be scaled to fit within the given dimensions.', 'propertyBackend'));

		// small
		$sw = new flFormElementInteger($form, 'sw', 10, null, $cfg->sw);
		$sw->setLabel(__('Image Width', 'propertyBackend'))
			->setRequired()
			->addValidator(new flFormValidatorRequired());

		$sh = new flFormElementInteger($form, 'sh', 10, null, $cfg->sh);
		$sh->setLabel(__('Image Height', 'propertyBackend'))
			->setRequired()
			->addValidator(new flFormValidatorRequired());

		$scrop = new flFormElementCheckbox($form, 'scrop', $cfg->scrop);
		$scrop->setLabel(__('Crop Image to Size', 'propertyBackend'))
			->setDescription(__('If checked then the image will be scaled and cropped to the exact width and height; if not checked the image will be scaled to fit within the given dimensions.', 'propertyBackend'));

		// medium
		$mw = new flFormElementInteger($form, 'mw', 10, null, $cfg->mw);
		$mw->setLabel(__('Image Width', 'propertyBackend'))
			->setRequired()
			->addValidator(new flFormValidatorRequired());

		$mh = new flFormElementInteger($form, 'mh', 10, null, $cfg->mh);
		$mh->setLabel(__('Image Height', 'propertyBackend'))
			->setRequired()
			->addValidator(new flFormValidatorRequired());

		$mcrop = new flFormElementCheckbox($form, 'mcrop', $cfg->mcrop);
		$mcrop->setLabel(__('Crop Image to Size', 'propertyBackend'))
			->setDescription(__('If checked then the image will be scaled and cropped to the exact width and height; if not checked the image will be scaled to fit within the given dimensions.', 'propertyBackend'));

		// large
		$lw = new flFormElementInteger($form, 'lw', 10, null, $cfg->lw);
		$lw->setLabel(__('Image Width', 'propertyBackend'))
			->setRequired()
			->addValidator(new flFormValidatorRequired());

		$lh = new flFormElementInteger($form, 'lh', 10, null, $cfg->lh);
		$lh->setLabel(__('Image Height', 'propertyBackend'))
			->setRequired()
			->addValidator(new flFormValidatorRequired());

		$lcrop = new flFormElementCheckbox($form, 'lcrop', $cfg->lcrop);
		$lcrop->setLabel(__('Crop Image to Size', 'propertyBackend'))
			->setDescription(__('If checked then the image will be scaled and cropped to the exact width and height; if not checked the image will be scaled to fit within the given dimensions.', 'propertyBackend'));



		$submit = new flFormElementSubmit($form, 'update');
		$submit->setCaption(__('Update Settings', 'propertyBackend'))->setCSS('primary');

		$form->groupElements('tiny', array($tw, $th, $tcrop))
			->addTab(__('Tiny', 'propertyBackend'), 'tiny')
			->groupElements('small', array($sw, $sh, $scrop))
			->addTab(__('Small', 'propertyBackend'), 'small')
			->groupElements('medium', array($mw, $mh, $mcrop))
			->addTab(__('Medium', 'propertyBackend'), 'medium')
			->groupElements('large', array($lw, $lh, $lcrop))
			->addTab(__('Large', 'propertyBackend'), 'large')
			->groupElements('submit', array($submit), new flFormDecoratorList(new flFormDecoratorDl()))
			->focusElement($tw);

		if($form->isSubmitted() && $form->isValid()) {
			cfSettingsAudit::update(
				__('Property', 'propertyBackend'),
				__('Images Sizes', 'propertyBackend'),
				[
					'tw' => $cfg->get('tw'),
					'th' => $cfg->get('th'),
					'tcrop' => $cfg->get('tcrop'),
					'sw' => $cfg->get('sw'),
					'sh' => $cfg->get('sh'),
					'scrop' => $cfg->get('scrop'),
					'mw' => $cfg->get('mw'),
					'mh' => $cfg->get('mh'),
					'mcrop' => $cfg->get('mcrop'),
					'lw' => $cfg->get('lw'),
					'lh' => $cfg->get('lh'),
					'lcrop' => $cfg->get('lcrop')
				]
			);

			$cfg->tw = $tw->getValue();
			$cfg->th = $th->getValue();
			$cfg->tcrop = $tcrop->getValue();

			$cfg->sw = $sw->getValue();
			$cfg->sh = $sh->getValue();
			$cfg->scrop = $scrop->getValue();

			$cfg->mw = $mw->getValue();
			$cfg->mh = $mh->getValue();
			$cfg->mcrop = $mcrop->getValue();

			$cfg->lw = $lw->getValue();
			$cfg->lh = $lh->getValue();
			$cfg->lcrop = $lcrop->getValue();

			$this->deleteCachedImages();

			return true;
		}

		return null;
	}

	/**
	 * Delete all cached/scaled images.
	 */
	function deleteCachedImages() {

		// Find and delete all scaled/cached images.
		$fileCfg = clearFusionCMS::getSiteConfig('cfSystemFileStore');
		$top = glob($fileCfg->privateStorage . '/property/' . clearFusionCMS::getSite() . '/*', GLOB_ONLYDIR);
		foreach($top as $td) {
			$inner = glob("$td/*", GLOB_NOSORT | GLOB_ONLYDIR);
			foreach($inner as $id) {
				$files = glob("$id/*_*.*", GLOB_NOSORT);
				foreach($files as $f) {
					@unlink($f);
				}
			}
		}

		// Flush the cache to force complete rebuild
		clearFusionCMS::getCache()->flush();
	}

	/**
	 * Implement price formatting settings.
	 *
	 * @param flForm $form The form object to use.
	 * @param flDb $db The database object.
	 * @return bool true if the settings were updated, false if failed to update or null if no change.
	 */
	function priceSetting($form, $db) {
		if(!clearFusionCMS::getUser()->hasPermission('cfProperty.settings'))
			return null;

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

		$curleft = new flFormElementText($form, 'curleft', $cfg->get('curleft', '$'));
		$curleft->setLabel(__('Left Currency Symbol', 'propertyBackend'))
			->addValidator(new flFormValidatorMaxLength(4));

		$curright = new flFormElementText($form, 'curright', $cfg->get('curright', ''));
		$curright->setLabel(__('Right Currency Symbol', 'propertyBackend'))
			->addValidator(new flFormValidatorMaxLength(4));

		$thoussep = new flFormElementText($form, 'thoussep', $cfg->get('thoussep', ','));
		$thoussep->setLabel(__('Thousands Separator', 'propertyBackend'))
			->addValidator(new flFormValidatorMaxLength(1));

		$decpoint = new flFormElementText($form, 'decpoint', $cfg->get('decpoint', '.'));
		$decpoint->setLabel(__('Decimals Separator', 'propertyBackend'))
			->addValidator(new flFormValidatorMaxLength(1));

		$numdecimals = new flFormElementText($form, 'numdecimals', $cfg->get('numdecimals', 2));
		$numdecimals->setLabel(__('Number of Decimals Points', 'propertyBackend'))
			->setRequired()
			->addValidator(new flFormValidatorRequired());

		$submit = new flFormElementSubmit($form, 'update');
		$submit->setCaption(__('Update Settings', 'propertyBackend'))->setCSS('primary');

		$form->groupElements('submit', array($submit), new flFormDecoratorList(new flFormDecoratorDl()));
		$form->focusElement($curleft);

		if($form->isSubmitted() && $form->isValid()) {
			cfSettingsAudit::update(
				__('Property', 'propertyBackend'),
				__('Price Formatting', 'propertyBackend'),
				[
					'curleft' => $cfg->get('curleft'),
					'curright' => $cfg->get('curright'),
					'thoussep' => $cfg->get('thoussep'),
					'decpoint' => $cfg->get('decpoint'),
					'numdecimals' => $cfg->get('numdecimals')
				]
			);

			$cfg->curleft = $curleft->getValue();
			$cfg->curright = $curright->getValue();
			$cfg->thoussep = $thoussep->getValue();
			$cfg->decpoint = $decpoint->getValue();
			$cfg->numdecimals = $numdecimals->getValue();
			
			clearFusionCMS::getCache()->flush();

			return true;
		}

		return null;
	}

	/**
	 * Implement regional settings.
	 *
	 * @param flForm $form The form object to use.
	 * @param flDb $db The database object.
	 * @return bool true if the settings were updated, false if failed to update or null if no change.
	 */
	function regionSetting($form, $db) {
		if(!clearFusionCMS::getUser()->hasPermission('cfProperty.settings'))
			return null;

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

		$country = new flFormElementSelect($form, 'countrycode', $cfg->get('default_country', 'US'), cfCountries::getList());
		$country->setLabel(__('Country', 'propertyBackend'))
			->setRequired();

		$submit = new flFormElementSubmit($form, 'update');
		$submit->setCaption(__('Update Settings', 'propertyBackend'))->setCSS('primary');

		$form->groupElements('submit', array($submit), new flFormDecoratorList(new flFormDecoratorDl()));
		$form->focusElement($country);

		if($form->isSubmitted() && $form->isValid()) {
			cfSettingsAudit::update(
				__('Property', 'propertyBackend'),
				__('Region', 'propertyBackend'),
				[
					'default_country' => $cfg->get('default_country')
				]
			);
			$cfg->default_country = $country->getValue();

			return true;
		}

		return null;
	}
}
