<?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: ViewTimeSheetVerification.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('punch','enabled')
		OR !( $permission->Check('punch','edit')
				OR $permission->Check('punch','edit_own')
				OR $permission->Check('punch','edit_child')) ) {
	$permission->Redirect( FALSE ); //Redirect
}

$smarty->assign('title', TTi18n::gettext($title = 'View TimeSheet Verification')); // See index.php

/*
 * Get FORM variables
 */
extract	(FormVariables::GetVariables(
										array	(
												'action',
												'id',
												'timesheet_id',
												'timesheet_queue_ids',
												'selected_level'
												) ) );

if ( isset($timesheet_queue_ids) ) {
	$timesheet_queue_ids = unserialize( base64_decode( urldecode($timesheet_queue_ids) ) );
	Debug::Arr($timesheet_queue_ids, ' Input TimeSheet Queue IDs '. $action, __FILE__, __LINE__, __METHOD__,10);
}
if ( isset($data) ) {
	$data['date_stamp'] = TTDate::parseDateTime($data['date_stamp']);
}

$pptsvf = new PayPeriodTimeSheetVerifyFactory();

$action = Misc::findSubmitButton();
switch ($action) {
	case 'pass':
		if ( count($timesheet_queue_ids) > 1 ) {
			//Remove the authorized/declined timesheet from the stack.
			array_shift($timesheet_queue_ids);
			Redirect::Page( URLBuilder::getURL( array('id' => $timesheet_queue_ids[0], 'selected_level' => $selected_level, 'timesheet_queue_ids' => base64_encode( serialize($timesheet_queue_ids) ) ), 'ViewTimeSheetVerification.php') );
		} else {
			Redirect::Page( URLBuilder::getURL( array('refresh' => TRUE ), '../CloseWindow.php') );
		}
	case 'decline':
	case 'authorize':
		//Debug::setVerbosity(11);
		Debug::text(' Authorizing TimeSheet: Action: '. $action, __FILE__, __LINE__, __METHOD__,10);
		if ( !empty($timesheet_id) ) {
			Debug::text(' Authorizing TimeSheet ID: '. $timesheet_id, __FILE__, __LINE__, __METHOD__,10);

			$af = new AuthorizationFactory();
			$af->setObjectType('timesheet');
			$af->setObject( $timesheet_id );

			if ( $action == 'authorize' ) {
				Debug::text(' Approving Authorization: ', __FILE__, __LINE__, __METHOD__,10);
				$af->setAuthorized(TRUE);
			} else {
				Debug::text(' Declining Authorization: ', __FILE__, __LINE__, __METHOD__,10);
				$af->setAuthorized(FALSE);
			}

			if ( $af->isValid() ) {
				$af->Save();

				if ( count($timesheet_queue_ids) > 1 ) {
					//Remove the authorized/declined timesheet from the stack.
					array_shift($timesheet_queue_ids);
					Redirect::Page( URLBuilder::getURL( array('id' => $timesheet_queue_ids[0], 'selected_level' => $selected_level, 'timesheet_queue_ids' => base64_encode( serialize($timesheet_queue_ids) ) ), 'ViewTimeSheetVerification.php') );
				} else {
					Redirect::Page( URLBuilder::getURL( array('refresh' => TRUE ), '../CloseWindow.php') );
				}

				break;
			}
		}
	default:
		if ( (int)$id > 0 ) {
			Debug::Text(' ID was passed: '. $id, __FILE__, __LINE__, __METHOD__,10);

			$pptsvlf = new PayPeriodTimeSheetVerifyListFactory();
			$pptsvlf->getByIDAndCompanyID( $id, $current_company->getId() );

			$status_options = $pptsvlf->getOptions('type');
			foreach ($pptsvlf as $pptsv_obj) {
				//Debug::Arr($station,'Department', __FILE__, __LINE__, __METHOD__,10);

				$data = array(
									'id' => $pptsv_obj->getId(),
									'pay_period_id' => $pptsv_obj->getPayPeriod(),
									'user_id' => $pptsv_obj->getUser(),
									'user_full_name' => $pptsv_obj->getUserObject()->getFullName(),
									'pay_period_start_date' => $pptsv_obj->getPayPeriodObject()->getStartDate(),
									'pay_period_end_date' => $pptsv_obj->getPayPeriodObject()->getEndDate(),
									'status_id' => $pptsv_obj->getStatus(),
									'status' => $status_options[$pptsv_obj->getStatus()],
									'created_date' => $pptsv_obj->getCreatedDate(),
									'created_by' => $pptsv_obj->getCreatedBy(),
									'updated_date' => $pptsv_obj->getUpdatedDate(),
									'updated_by' => $pptsv_obj->getUpdatedBy(),
									'deleted_date' => $pptsv_obj->getDeletedDate(),
									'deleted_by' => $pptsv_obj->getDeletedBy()
								);
			}

			//Get Next TimeSheet to authorize:
			if ( $permission->Check('punch','authorize')
					AND $selected_level != NULL
					AND count($timesheet_queue_ids) <= 1 ) {

				Debug::Text('Get TimeSheet Queue: ', __FILE__, __LINE__, __METHOD__,10);

				$ulf = new UserListFactory();
				$hlf = new HierarchyListFactory();
				$hotlf = new HierarchyObjectTypeListFactory();

				//Get Hierarchy Control ID
				$timesheet_hierarchy_id = $hotlf->getByCompanyIdAndObjectTypeId( $current_company->getId(), 90 )->getCurrent()->getHierarchyControl();
				Debug::Text('TimeSheet Hierarchy ID: '. $timesheet_hierarchy_id, __FILE__, __LINE__, __METHOD__,10);

				//Get all levels below us.
				$timesheet_levels = $hlf->getLevelsByHierarchyControlIdAndUserId( $timesheet_hierarchy_id,  $current_user->getId() );
				Debug::Arr( $timesheet_levels, 'TimeSheet Levels', __FILE__, __LINE__, __METHOD__,10);

				if ( isset($selected_level) AND in_array( $selected_level, array_keys($timesheet_levels) ) ) {
					$timesheet_user_id = $timesheet_levels[$selected_level];
					Debug::Text(' Switching Levels... Using UserID: '. $timesheet_user_id, __FILE__, __LINE__, __METHOD__,10);
				} else {
					$timesheet_user_id = $current_user->getId();
				}

				$timesheet_node_data = $hlf->getByHierarchyControlIdAndUserId( $timesheet_hierarchy_id, $timesheet_user_id );

				//Get current level IDs
				$timesheet_current_level_user_ids = $hlf->getCurrentLevelIdArrayByHierarchyControlIdAndUserId($timesheet_hierarchy_id, $timesheet_user_id );
				Debug::Arr( $timesheet_current_level_user_ids, 'TimeSheet Current Level Ids', __FILE__, __LINE__, __METHOD__,10);

				//Get Parents
				$timesheet_parent_level_user_ids = $hlf->getParentLevelIdArrayByHierarchyControlIdAndUserId($timesheet_hierarchy_id, $timesheet_user_id );
				Debug::Arr( $timesheet_parent_level_user_ids, 'TimeSheet Parent Level Ids', __FILE__, __LINE__, __METHOD__,10);

				//Get Children
				$timesheet_child_level_user_ids = $hlf->getChildLevelIdArrayByHierarchyControlIdAndUserId($timesheet_hierarchy_id, $timesheet_user_id );
				Debug::Arr( $timesheet_child_level_user_ids, 'TimeSheet Child Level Ids', __FILE__, __LINE__, __METHOD__,10);

				if ( !( $timesheet_current_level_user_ids === FALSE
						AND $timesheet_parent_level_user_ids === FALSE
						AND $timesheet_child_level_user_ids === FALSE ) ) {

					$pptsvlf = new PayPeriodTimeSheetVerifyListFactory();
					$pptsvlf->getByUserIdListAndStatusAndNotAuthorized($timesheet_child_level_user_ids, 30, $timesheet_parent_level_user_ids, $timesheet_current_level_user_ids );

					//Get all IDs that need authorizing.
					//Only do 25 at a time, then grab more.
					$i=0;
					$start=FALSE;
					foreach( $pptsvlf as $pptsv_obj) {
						if ( $id == $pptsv_obj->getId() ) {
							$start = TRUE;
						}

						if ( $start == TRUE ) {
							$timesheet_queue_ids[] = $pptsv_obj->getId();
						}

						if ( $i > 25 ) {
							break;
						}
						$i++;
					}

					if ( isset($timesheet_queue_ids) ) {
						$timesheet_queue_ids = array_unique($timesheet_queue_ids);
					}
				}
			}
		}

		//Select box options;
		$data['status_options'] = $pptsvf->getOptions('status');

		if ( isset($timesheet_queue_ids) ) {
			Debug::Arr($timesheet_queue_ids, ' Output TimeSheet Queue IDs '. $action, __FILE__, __LINE__, __METHOD__,10);
			$smarty->assign_by_ref('timesheet_queue_ids', urlencode( base64_encode( serialize($timesheet_queue_ids) ) ) );
		}

		$smarty->assign_by_ref('selected_level', $selected_level);
		$smarty->assign_by_ref('data', $data);

		break;
}

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

$smarty->display('timesheet/ViewTimeSheetVerification.tpl');
?>