<?php
/*********************************************************************************
 * The contents of this file are subject to the TimeTrex Public License Version
 * 1.1.0 ("License"); You may not use this file except in compliance with the
 * License. You may obtain a copy of the License at http://www.TimeTrex.com/TPL
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied.  See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * All copies of the Covered Code must include on each user interface screen:
 *    (i) the "Powered by TimeTrex" logo and
 *    (ii) the TimeTrex copyright notice
 * in the same form as they appear in the distribution.  See full license for
 * requirements.
 *
 * The Original Code is: TimeTrex Open Source
 * The Initial Developer of the Original Code is TimeTrex Payroll Services
 * Portions created by TimeTrex are Copyright (C) 2004-2007 TimeTrex Payroll Services;
 * All Rights Reserved.
 *
 ********************************************************************************/
/*
 * $Revision: 2158 $
 * $Id: HierarchyControlFactory.class.php 2158 2008-09-15 23:26:15Z ipso $
 * $Date: 2008-09-15 16:26:15 -0700 (Mon, 15 Sep 2008) $
 */

/**
 * @package Module_Hierarchy
 */
class HierarchyControlFactory extends Factory {
	protected $table = 'hierarchy_control';
	protected $pk_sequence_name = 'hierarchy_control_id_seq'; //PK Sequence name

	//Temporaray holding array.
	protected $object_type_ids = NULL;
	function getCompany() {
		return $this->data['company_id'];
	}
	function setCompany($id) {
		$id = trim($id);

		$clf = new CompanyListFactory();

		if ( $this->Validator->isResultSetWithRows(	'company',
													$clf->getByID($id),
													TTi18n::gettext('Invalid Company')
													) ) {

			$this->data['company_id'] = $id;

			return TRUE;
		}

		return FALSE;
	}

	function isUniqueName($name) {
		$ph = array(
					'company_id' => $this->getCompany(),
					'name' => $name,
					);

		$query = 'select id from '. $this->getTable() .' where company_id = ? AND name = ? AND deleted=0';
		$hierarchy_control_id = $this->db->GetOne($query, $ph);
		Debug::Arr($hierarchy_control_id,'Unique Hierarchy Control ID: '. $hierarchy_control_id, __FILE__, __LINE__, __METHOD__,10);

		if ( $hierarchy_control_id === FALSE ) {
			return TRUE;
		} else {
			if ($hierarchy_control_id == $this->getId() ) {
				return TRUE;
			}
		}

		return FALSE;
	}
	function getName() {
		return $this->data['name'];
	}
	function setName($name) {
		$name = trim($name);

		if (	$this->Validator->isLength(	'name',
											$name,
											TTi18n::gettext('Name is invalid'),
											2,50)
				AND	$this->Validator->isTrue(	'name',
												$this->isUniqueName($name),
												TTi18n::gettext('Name is already in use')
												)
						) {

			$this->data['name'] = $name;

			return TRUE;
		}

		return FALSE;
	}

	function getDescription() {
		return $this->data['description'];
	}
	function setDescription($description) {
		$description = trim($description);

		if (	$description == ''
				OR $this->Validator->isLength(	'description',
											$description,
											TTi18n::gettext('Description is invalid'),
											1,255) ) {

			$this->data['description'] = $description;

			return TRUE;
		}

		return FALSE;
	}

	//Return the temp IDs for validation.
	function getTmpObjectType() {
		if ( isset( $this->object_type_ids ) ) {
			return 	$this->object_type_ids;
		}

		return FALSE;
	}


	//Return IDs from the database,
	function getObjectType() {
		$hotlf = new HierarchyObjectTypeListFactory();
		$hotlf->getByHierarchyControlId( $this->getId() );

		foreach ($hotlf as $object_type) {
			$object_type_list[] = $object_type->getObjectType();
		}

		if ( isset($object_type_list) ) {
			return $object_type_list;
		}

		return FALSE;
	}

	function setObjectType($ids) {
		if ( is_array($ids) AND count($ids) > 0 ) {
			$this->object_type_ids = $ids;

			return TRUE;
		}

		$this->Validator->isTrue(		'object_type',
										FALSE,
										TTi18n::gettext('At least one object type must be selected'));
		return FALSE;
	}

	function setObjectTypeIds($ids) {
		if ( is_array($ids) ) {
			if ( !$this->isNew() ) {
				//If needed, delete mappings first.
				$lf_a = new HierarchyObjectTypeListFactory();
				$lf_a->getByHierarchyControlId( $this->getId() );

				$tmp_ids = array();
				foreach ($lf_a as $obj) {
					$id = $obj->getId();
					Debug::text('Hierarchy Object Type ID: '. $obj->getId() .' ID: '. $id, __FILE__, __LINE__, __METHOD__, 10);

					//Delete users that are not selected.
					if ( !in_array($id, $ids) ) {
						Debug::text('Deleting: '. $id, __FILE__, __LINE__, __METHOD__, 10);
						$obj->Delete();
					} else {
						//Save ID's that need to be updated.
						Debug::text('NOT Deleting : '. $id, __FILE__, __LINE__, __METHOD__, 10);
						$tmp_ids[] = $id;
					}
				}
				unset($id, $obj);
			}

			foreach ($ids as $id) {
				if ( isset($ids) AND !in_array($id, $tmp_ids) ) {
					$f = new HierarchyObjectTypeFactory();
					$f->setHierarchyControl( $this->getId() );
					$f->setObjectType( $id );

					if ($this->Validator->isTrue(		'object_type',
														$f->Validator->isValid(),
														TTi18n::gettext('Object type is already assigned to another hierarchy'))) {
						$f->save();
					}
				}
			}

			return TRUE;
		}

		return FALSE;
	}

	function Validate() {
		$hotlf = new HierarchyObjectTypeListFactory();
		$hotlf->getByCompanyId( $this->getCompany() );
		foreach ( $hotlf as $object_type_obj) {
			if ( $object_type_obj->getHierarchyControl() != $this->getId() ) {
				$current_object_type_ids[] = $object_type_obj->getObjectType();
			}
		}

		if ( ( is_array( $this->getTmpObjectType() ) AND count( $this->getTmpObjectType() ) > 0 )
				AND ( isset($current_object_type_ids) AND count($current_object_type_ids) > 0 ) ) {
			Debug::text('Other object types are assigned, checking for duplicates: '. count( $this->getTmpObjectType() ), __FILE__, __LINE__, __METHOD__, 10);

            //Debug::Arr($current_object_type_ids, 'Already assigned Ids: ', __FILE__, __LINE__, __METHOD__, 10);
			//Debug::Arr($this->getTmpObjectType(), 'Tmp Ids: ', __FILE__, __LINE__, __METHOD__, 10);

			foreach( $current_object_type_ids as $current_object_type_id) {
				if ( in_array( $current_object_type_id, $this->getTmpObjectType() ) ) {
					Debug::text('Duplicate object type IDs found!: ', __FILE__, __LINE__, __METHOD__, 10);
					$this->Validator->isTrue(		'object_type',
													FALSE,
													TTi18n::gettext('Object type is already assigned to another hierarchy'));

					break;
				}

			}
		}

		return TRUE;
	}

	function postSave() {
		//Save objectype IDs

		$this->setObjectTypeIds( $this->getTmpObjectType() );

		return TRUE;
	}

	function addLog( $log_action ) {
		return TTLog::addEntry( $this->getId(), $log_action, TTi18n::getText('Hierarchy'), NULL, $this->getTable() );
	}
}
?>
