<?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: DepartmentFactory.class.php 2158 2008-09-15 23:26:15Z ipso $
 * $Date: 2008-09-15 16:26:15 -0700 (Mon, 15 Sep 2008) $
 */

/**
 * @package Module_Department
 */
class DepartmentFactory extends Factory {
	protected $table = 'department';
	protected $pk_sequence_name = 'department_id_seq'; //PK Sequence name


	function _getFactoryOptions( $name ) {

		$retval = NULL;
		switch( $name ) {
			case 'status':
				$retval = array(
										10 => TTi18n::gettext('ENABLED'),
										20 => TTi18n::gettext('DISABLED')
									);
				break;

		}

		return $retval;
	}


	function getCompany() {
		return $this->data['company_id'];
	}
	function setCompany($id) {
		$id = trim($id);

		$clf = new CompanyListFactory();

		if ( $id == 0
				OR $this->Validator->isResultSetWithRows(	'company',
															$clf->getByID($id),
															TTi18n::gettext('Company is invalid')
															) ) {
			$this->data['company_id'] = $id;

			return TRUE;
		}

		return FALSE;
	}

	function getStatus() {
		//Have to return the KEY because it should always be a drop down box.
		//return Option::getByKey($this->data['status_id'], $this->getOptions('status') );
		return $this->data['status_id'];
	}
	function setStatus($status) {
		$status = trim($status);

		$key = Option::getByValue($status, $this->getOptions('status') );
		if ($key !== FALSE) {
			$status = $key;
		}

		if ( $this->Validator->inArrayKey(	'status',
											$status,
											TTi18n::gettext('Incorrect Status'),
											$this->getOptions('status')) ) {

			$this->data['status_id'] = $status;

			return FALSE;
		}

		return FALSE;
	}

	function isUniqueManualID($id) {
		$ph = array(
					'manual_id' => $id,
					'company_id' =>  $this->getCompany(),
					);

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

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

		return FALSE;
	}
	static function getNextAvailableManualId( $company_id = NULL ) {
		global $current_company;

		if ( $company_id == '' ANd is_object($current_company) ) {
			$company_id = $current_company->getId();
		} elseif ( $company_id == '' AND isset($this) AND is_object($this) ) {
			$company_id = $this->getCompany();
		}

		$dlf = new DepartmentListFactory();
		$dlf->getHighestManualIDByCompanyId( $company_id );
		if ( $dlf->getRecordCount() > 0 ) {
			$next_available_manual_id = $dlf->getCurrent()->getManualId()+1;
		} else {
			$next_available_manual_id = 1;
		}

		return $next_available_manual_id;
	}

	function getManualID() {
		if ( isset($this->data['manual_id']) ) {
			return $this->data['manual_id'];
		}

		return FALSE;
	}
	function setManualID($value) {
		$value = trim($value);

		if (	$this->Validator->isNumeric(	'manual_id',
												$value,
												TTi18n::gettext('Code is invalid'))
				AND
					$this->Validator->isTrue(		'manual_id',
													$this->isUniqueManualID($value),
													TTi18n::gettext('Code is already in use, please enter a different one'))
												) {

			$this->data['manual_id'] = $value;

			return TRUE;
		}

		return FALSE;
	}

	function isUniqueName($name) {
		if ( $name == '' ) {
			return FALSE;
		}

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

		$query = 'select id from '. $this->table .'
					where company_id = ?
						AND name = ?
						AND deleted = 0';
		$name_id = $this->db->GetOne($query, $ph);
		//Debug::Arr($name_id,'Unique Name: '. $name, __FILE__, __LINE__, __METHOD__,10);

		if ( $name_id === FALSE ) {
			return TRUE;
		} else {
			if ($name_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('Department name is too short or too long'),
												2,
												100)
					AND
						$this->Validator->isTrue(		'name',
														$this->isUniqueName($name),
														TTi18n::gettext('Department already exists'))

												) {

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

			return TRUE;
		}

		return FALSE;
	}

	function getBranch() {
		$dblf = new DepartmentBranchListFactory();
		$dblf->getByDepartmentId( $this->getId() );
		foreach ($dblf as $department_branch) {
			$branch_list[] = $department_branch->getBranch();
		}

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

		return FALSE;
	}
	function setBranch($ids) {
		if (is_array($ids) and count($ids) > 0) {
			//If needed, delete mappings first.
			$dblf = new DepartmentBranchListFactory();
			$dblf->getByDepartmentId( $this->getId() );

			$branch_ids = array();
			foreach ($dblf as $department_branch) {
				$branch_id = $department_branch->getBranch();
				Debug::text('Department ID: '. $department_branch->getDepartment() .' Branch: '. $branch_id, __FILE__, __LINE__, __METHOD__, 10);

				//Delete branches that are not selected.
				if ( !in_array($branch_id, $ids) ) {
					Debug::text('Deleting DepartmentBranch: '. $branch_id, __FILE__, __LINE__, __METHOD__, 10);
					$department_branch->Delete();
				} else {
					//Save branch ID's that need to be updated.
					Debug::text('NOT Deleting DepartmentBranch: '. $branch_id, __FILE__, __LINE__, __METHOD__, 10);
					$branch_ids[] = $branch_id;
				}
			}

			//Insert new mappings.
			$dbf = new DepartmentBranchFactory();
			foreach ($ids as $id) {
				if ( !in_array($id, $branch_ids) ) {
					$dbf->setDepartment( $this->getId() );
					$dbf->setBranch( $id );

					if ($this->Validator->isTrue(		'branch',
														$dbf->Validator->isValid(),
														TTi18n::gettext('Branch selection is invalid'))) {
						$dbf->save();
					}
				}
			}

			return TRUE;
		}

		return FALSE;
	}

	function postSave() {
		$this->removeCache( $this->getId() );

		if ( $this->getDeleted() == TRUE ) {
			Debug::Text('UnAssign Hours from Job: '. $this->getId(), __FILE__, __LINE__, __METHOD__,10);
			//Unassign hours from this job.
			$pcf = new PunchControlFactory();
			$udtf = new UserDateTotalFactory();
			$uf = new UserFactory();
			$sf = new StationFactory();
			$udf = new UserDefaultFactory();

			$query = 'update '. $pcf->getTable() .' set department_id = 0 where department_id = '. $this->getId();
			$this->db->Execute($query);

			$query = 'update '. $udtf->getTable() .' set department_id = 0 where department_id = '. $this->getId();
			$this->db->Execute($query);

			$query = 'update '. $uf->getTable() .' set default_department_id = 0 where company_id = '. $this->getCompany() .' AND default_department_id = '. $this->getId();
			$this->db->Execute($query);

			$query = 'update '. $udf->getTable() .' set default_department_id = 0 where company_id = '. $this->getCompany() .' AND default_department_id = '. $this->getId();
			$this->db->Execute($query);

			$query = 'update '. $sf->getTable() .' set department_id = 0 where company_id = '. $this->getCompany() .' AND department_id = '. $this->getId();
			$this->db->Execute($query);
		}

		return TRUE;
	}

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