<?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: 2073 $
 * $Id: EditMessage.php 2073 2008-08-22 18:41:21Z ipso $
 * $Date: 2008-08-22 11:41:21 -0700 (Fri, 22 Aug 2008) $
 */
require_once('../../includes/global.inc.php');
require_once(Environment::getBasePath() .'includes/Interface.inc.php');

//Debug::setVerbosity(11);

if ( !$permission->Check('message','enabled')
		OR !( $permission->Check('message','edit') OR $permission->Check('message','edit_own') ) ) {

	$permission->Redirect( FALSE ); //Redirect

}

$smarty->assign('title', TTi18n::gettext($title = 'New Message')); // See index.php
BreadCrumb::setCrumb($title);

/*
 * Get FORM variables
 */
extract	(FormVariables::GetVariables(
										array	(
												'action',
												'id',
												'filter_user_id',
												'data',
												) ) );

$mf = new MessageFactory();

$action = Misc::findSubmitButton();
switch ($action) {
	case 'submit_message':
		//Debug::setVerbosity(11);
		Debug::Text('Submit!', __FILE__, __LINE__, __METHOD__,10);

		$redirect = TRUE;
		//Make sure the only array entry isn't 0 => 0;
		if ( is_array($filter_user_id) AND count($filter_user_id) > 0 AND ( isset($filter_user_id[0]) AND $filter_user_id[0] != 0 ) ) {
			$mf->StartTransaction();
			foreach( $filter_user_id as $object_id ) {
				Debug::Text('Adding Message for: '. $object_id, __FILE__, __LINE__, __METHOD__,10);

				$mf = new MessageFactory();
				$mf->setObjectType( 5 );
				$mf->setObject( $object_id );
				$mf->setParent( 0 );
				$mf->setPriority();
				$mf->setStatus('UNREAD');
				$mf->setSubject( $data['subject'] );
				$mf->setBody( $data['body'] );

				if ( isset($data['require_ack']) ) {
					Debug::Text('Requires Ack!!', __FILE__, __LINE__, __METHOD__,10);
					$mf->setRequireAck( TRUE );
				} else {
					Debug::Text('DOES NOT Requires Ack!!', __FILE__, __LINE__, __METHOD__,10);
					$mf->setRequireAck( FALSE );
				}

				if ( $mf->isValid() ) {
					$mf->Save();
				} else {
					$redirect = FALSE;
				}
			}

			if ( $redirect == TRUE ) {
				$mf->CommitTransaction();
				Redirect::Page( URLBuilder::getURL( NULL, 'UserMessageList.php') );

				break;
			}
			$mf->FailTransaction();
		} else {
			$mf->Validator->isTrue(	'to',
									FALSE,
									TTi18n::gettext('Please select at least one recipient') );
		}
	default:
		if ( isset($id) AND $action != 'submit_message') {
			unset($data);

			Debug::Text('ID: '. $id, __FILE__, __LINE__, __METHOD__,10);
			$mlf = new MessageListFactory();
			$mlf->getById($id);
			if ( $mlf->getRecordCount() > 0 ) {
				foreach ($mlf as $m_obj) {
					$data = array(
										'id' => $m_obj->getId(),
										'status_id' => $m_obj->getStatus(),
										'status_date' => $c_obj->getStatusDate(),
										'object_type_id' => $m_obj->getObjectType(),
										'object_id' => $m_obj->getObject(),
										'priority' => $m_obj->getPriority(),

										'subject' => $m_obj->getSubject(),
										'body' => $m_obj->getBody(),

										'require_ack' => $m_obj->getRequireAck(),
										'ack_date' => $m_obj->getAckDate(),
										'ack_by' => $m_obj->getAckBy(),

										'created_date' => $c_obj->getCreatedDate(),
										'created_by' => $c_obj->getCreatedBy(),
										'created_by_full_name' => $ulf->getById( $message->getCreatedBy() )->getCurrent()->getFullName(),
										'updated_date' => $c_obj->getUpdatedDate(),
										'updated_by' => $c_obj->getUpdatedBy(),
										'deleted_date' => $c_obj->getDeletedDate(),
										'deleted_by' => $c_obj->getDeletedBy()
									);
				}
			}
		}

		$data['status_options'] = $mf->getOptions('status');
		$data['priority_options'] = $mf->getOptions('priority');

		if ( $permission->Check('message','send_to_any') ) {
			$user_options = UserListFactory::getByCompanyIdArray( $current_company->getId(), FALSE, TRUE);
			$data['user_options'] = Misc::arrayDiffByKey( (array)$filter_user_id, $user_options );
			$filter_user_options = Misc::arrayIntersectByKey( (array)$filter_user_id, $user_options );
		} else {
			//Only allow sending to supervisors OR children.
			$hlf = new HierarchyListFactory();
			$hotlf = new HierarchyObjectTypeListFactory();

			$request_hierarchy_id = $hotlf->getByCompanyIdAndObjectTypeId( $current_user->getCompany(), 50 )->getCurrent()->getHierarchyControl();
			Debug::Text('Request Hierarchy ID: '. $request_hierarchy_id, __FILE__, __LINE__, __METHOD__,10);

			$request_current_level_user_ids = (array)$hlf->getCurrentLevelIdArrayByHierarchyControlIdAndUserId($request_hierarchy_id, $current_user->getId() );
			Debug::Arr( $request_current_level_user_ids, 'Request Current Level Ids', __FILE__, __LINE__, __METHOD__,10);
			foreach( $request_current_level_user_ids as $key => $current_level_user_id ) {
				if ( $current_level_user_id == $current_user->getId() ) {
					unset($request_current_level_user_ids[$key]);
				}
			}
			unset($key, $current_level_user_id);

			//Get Parents
			$request_parent_level_user_ids = $hlf->getParentLevelIdArrayByHierarchyControlIdAndUserId($request_hierarchy_id, $current_user->getId() );
			//Debug::Arr( $request_parent_level_user_ids, 'Request Parent Level Ids', __FILE__, __LINE__, __METHOD__,10);

			//Get Children
			$request_child_level_user_ids = $hlf->getChildLevelIdArrayByHierarchyControlIdAndUserId($request_hierarchy_id, $current_user->getId() );
			//Debug::Arr( $request_child_level_user_ids, 'Request Child Level Ids', __FILE__, __LINE__, __METHOD__,10);

			$request_user_ids = array_merge( (array)$request_current_level_user_ids, (array)$request_parent_level_user_ids, (array)$request_child_level_user_ids );

			$ulf = new UserListFactory();
			$ulf->getByIdAndCompanyId( $request_user_ids, $current_user->getCompany() );
			$user_options = UserListFactory::getArrayByListFactory( $ulf, TRUE, FALSE);

			//$data['user_options'] = Misc::arrayDiffByKey( (array)$filter_user_id, $user_options );
			$data['user_options'] = $user_options;
			$filter_user_options = Misc::arrayIntersectByKey( (array)$filter_user_id, $user_options );
		}

		$smarty->assign_by_ref('data', $data);
		$smarty->assign_by_ref('filter_user_options', $filter_user_options);
		$smarty->assign_by_ref('filter_user_id', $filter_user_id);

		break;
}

$smarty->assign_by_ref('mf', $mf);

$smarty->display('message/EditMessage.tpl');
?>