<?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: 2004 $
 * $Id: EditPunch.php 2004 2008-07-18 21:19:47Z ipso $
 * $Date: 2008-07-18 14:19:47 -0700 (Fri, 18 Jul 2008) $
 */
require_once('../../includes/global.inc.php');

//Debug::setVerbosity(11);

$skip_message_check = TRUE;
require_once(Environment::getBasePath() .'includes/Interface.inc.php');

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 = 'Edit Punch')); // See index.php

/*
 * Get FORM variables
 */
extract	(FormVariables::GetVariables(
										array	(
												'action',
												'id',
												'punch_control_id',
												'user_id',
												'date_stamp',
												'status_id',
												'pc_data'
												) ) );

$punch_full_time_stamp = NULL;
if ( isset($pc_data) ) {
	if ( $pc_data['date_stamp'] != '' AND $pc_data['time_stamp'] != '') {
		$punch_full_time_stamp = TTDate::parseDateTime($pc_data['date_stamp'].' '.$pc_data['time_stamp']);
		$pc_data['punch_full_time_stamp'] = $punch_full_time_stamp;
		$pc_data['time_stamp'] = $punch_full_time_stamp;
	} else {
		$pc_data['punch_full_time_stamp'] = NULL;
	}

	if ( $pc_data['date_stamp'] != '') {
		$pc_data['date_stamp'] = TTDate::parseDateTime($pc_data['date_stamp']);
	}
}

$pcf = new PunchControlFactory();
$pf = new PunchFactory();
$ulf = new UserListFactory();

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

		$plf = new PunchListFactory();
		$plf->getById( $pc_data['punch_id'] );
		if ( $plf->getRecordCount() > 0 ) {
			foreach($plf as $p_obj) {
				$p_obj->setDeleted(TRUE);
				$p_obj->setEnableCalcTotalTime( TRUE );
				$p_obj->setEnableCalcSystemTotalTime( TRUE );
				$p_obj->setEnableCalcWeeklySystemTotalTime( TRUE );
				$p_obj->setEnableCalcUserDateTotal( TRUE );
				$p_obj->setEnableCalcException( TRUE );
				$p_obj->Save();
			}
		}

		Redirect::Page( URLBuilder::getURL( array('refresh' => TRUE ), '../CloseWindow.php') );

		break;
	case 'submit':
		//Debug::setVerbosity(11);
		Debug::Text('Submit!', __FILE__, __LINE__, __METHOD__,10);

		$fail_transaction=FALSE;

		$pf->StartTransaction();

		//Limit it to 14 days.
		if ( $pc_data['repeat'] > 14 ) {
			$pc_data['repeat'] = 14;
		}
		Debug::Text('Repeating Punch For: '. $pc_data['repeat'] .' Days', __FILE__, __LINE__, __METHOD__,10);

		for($i=0; $i <= (int)$pc_data['repeat']; $i++ ) {
			$pcf = new PunchControlFactory();
			$pf = new PunchFactory();

			Debug::Text('Punch Repeat: '. $i, __FILE__, __LINE__, __METHOD__,10);
			if ( $i == 0 ) {
				$time_stamp = $punch_full_time_stamp;
			} else {
				$time_stamp = $punch_full_time_stamp + (86400 * $i);
			}

			Debug::Text('Punch Full Time Stamp: '. date('r', $time_stamp) .'('.$time_stamp.')', __FILE__, __LINE__, __METHOD__,10);

			$pcf->findUserDate( $pc_data['user_id'], $time_stamp, $pc_data['status_id'], $pc_data['punch_id'] );

			if ( $i == 0 ) {
				$pcf->setId( $pc_data['id'] );
			} else {
				//Try to find a punch_control_id we can attach to safely.
				$pclf = new PunchControlListFactory();
				$tmp_punch_control_id = $pclf->getInCompletePunchControlIdByUserDateIdAndEpoch( $pcf->getUserDateId(), $time_stamp, $pc_data['status_id'] );
				if ( $tmp_punch_control_id !== FALSE ) {
					$pcf->setId( $tmp_punch_control_id );
				}
			}

			if ( $i == 0 AND $pc_data['user_date_id'] != '' AND $pc_data['user_date_id'] != $pcf->getUserDateId() ) {
				Debug::Text(' User Date ID has changed!!: Old: '. $pc_data['user_date_id']  .' New: '. $pcf->getUserDateId(), __FILE__, __LINE__, __METHOD__,10);
				$pcf->setOldUserDateId( $pc_data['user_date_id'] );
			}

			if ( isset($pc_data['branch_id']) ) {
				$pcf->setBranch( $pc_data['branch_id'] );
			}
			if ( isset($pc_data['department_id']) ) {
				$pcf->setDepartment( $pc_data['department_id'] );
			}
			if ( isset($pc_data['job_id']) ) {
				$pcf->setJob( $pc_data['job_id'] );
			}
			if ( isset($pc_data['job_item_id']) ) {
				$pcf->setJobItem( $pc_data['job_item_id'] );
			}
			if ( isset($pc_data['quantity']) ) {
				$pcf->setQuantity( $pc_data['quantity'] );
			}
			if ( isset($pc_data['bad_quantity']) ) {
				$pcf->setBadQuantity( $pc_data['bad_quantity'] );
			}
			if ( isset($pc_data['note']) ) {
				$pcf->setNote( $pc_data['note'] );
			}

			if ( isset($pc_data['other_id1']) ) {
				$pcf->setOtherID1( $pc_data['other_id1'] );
			}
			if ( isset($pc_data['other_id2']) ) {
				$pcf->setOtherID2( $pc_data['other_id2'] );
			}
			if ( isset($pc_data['other_id3']) ) {
				$pcf->setOtherID3( $pc_data['other_id3'] );
			}
			if ( isset($pc_data['other_id4']) ) {
				$pcf->setOtherID4( $pc_data['other_id4'] );
			}
			if ( isset($pc_data['other_id5']) ) {
				$pcf->setOtherID5( $pc_data['other_id5'] );
			}

			$pcf->setEnableStrictJobValidation( TRUE );
			if ( $pcf->isValid() == TRUE ) {
				$punch_control_id = $pcf->Save();

				//If its an update, not a new insert
				if ( $i == 0 AND $punch_control_id === TRUE ) {
					Debug::Text(' Updating Punch Control Object, not using New ID: '. $pc_data['id'], __FILE__, __LINE__, __METHOD__,10);
					$punch_control_id = $pc_data['id'];
				} elseif ( $i > 0 AND $punch_control_id === TRUE ) {
					$punch_control_id = $tmp_punch_control_id;
				}
				Debug::Text(' Punch Control ID: '. $punch_control_id, __FILE__, __LINE__, __METHOD__,10);

				if ( $i == 0 ) {
					$pf->setId( $pc_data['punch_id'] );
				}
				if ( isset($data['transfer']) ) {
					$pf->setTransfer( TRUE );
				}
				$pf->setPunchControlID( $punch_control_id );
				$pf->setType( $pc_data['type_id'] );
				$pf->setStatus( $pc_data['status_id'] );
				if ( isset($pc_data['disable_rounding']) ) {
					$enable_rounding = FALSE;
				} else {
					$enable_rounding = TRUE;
				}
				$pf->setTimeStamp( $time_stamp, $enable_rounding );

				if ( $pf->isNew() ) {
					$pf->setActualTimeStamp( $time_stamp );
					$pf->setOriginalTimeStamp( $pf->getTimeStamp() );
				}

				if ( $pf->isValid() ) {
					$pf->setEnableCalcTotalTime( TRUE );
					$pf->setEnableCalcSystemTotalTime( TRUE );
					$pf->setEnableCalcWeeklySystemTotalTime( TRUE );
					$pf->setEnableCalcUserDateTotal( TRUE );
					$pf->setEnableCalcException( TRUE );

					if ( $pf->Save() != TRUE ) {
						Debug::Text(' aFail Transaction: ', __FILE__, __LINE__, __METHOD__,10);
						$fail_transaction = TRUE;
						break;
					}
				} else {
					Debug::Text(' bFail Transaction: ', __FILE__, __LINE__, __METHOD__,10);
					$fail_transaction = TRUE;
					break;
				}
			} else {
				Debug::Text(' cFail Transaction: ', __FILE__, __LINE__, __METHOD__,10);
				$fail_transaction = TRUE;
				break;
			}
		}

		if ( $fail_transaction == FALSE ) {
			//$pf->FailTransaction();
			$pf->CommitTransaction();

			Redirect::Page( URLBuilder::getURL( array('refresh' => TRUE ), '../CloseWindow.php') );
			break;
		} else {
			$pf->FailTransaction();
		}
	default:
		if ( $id != '' AND $action != 'submit' ) {
			Debug::Text(' ID was passed: '. $id, __FILE__, __LINE__, __METHOD__,10);

			$pclf = new PunchControlListFactory();
			$pclf->getByPunchId( $id );

			foreach ($pclf as $pc_obj) {
				//Debug::Arr($station,'Department', __FILE__, __LINE__, __METHOD__,10);

				//Get punches
				$plf = new PunchListFactory();
				//$plf->getByPunchControlId( $pc_obj->getId() );
				$plf->getById( $id );
				if ( $plf->getRecordCount() > 0 ) {
					$p_obj = $plf->getCurrent();
				} else {
					$punch_data = NULL;
				}

				//Get Station data.
				$station_data = FALSE;
				$slf = new StationListFactory();
				if ( $p_obj->getStation() != FALSE ) {
					$slf->getById( $p_obj->getStation() );
					if ( $slf->getRecordCount() > 0 ) {
						$s_obj = $slf->getCurrent();

						$station_data = array(
											'id' => $s_obj->getId(),
											'type_id' => $s_obj->getType(),
											'type' => Option::getByKey($s_obj->getType(), $s_obj->getOptions('type') ),
											'station_id' => $s_obj->getStation(),
											'source' => $s_obj->getSource(),
											'description' => Misc::TruncateString( $s_obj->getDescription(), 20 )
											);
					}
				}

				$pc_data = array(
									'id' => $pc_obj->getId(),
									'user_date_id' => $pc_obj->getUserDateId(),
									'user_id' => $pc_obj->getUserDateObject()->getUser(),
									'user_full_name' => $pc_obj->getUserDateObject()->getUserObject()->getFullName(),
									'pay_period_id' => $pc_obj->getUserDateObject()->getPayPeriod(),
									//This causes punches that span 24hrs to not be edited correct
									//the date being the date of the first punch, not the last if we're
									//editing the last.
									//'date_stamp' => $pc_obj->getUserDateObject()->getDateStamp(),
									'branch_id' => $pc_obj->getBranch(),
									'department_id' => $pc_obj->getDepartment(),
									'job_id' => $pc_obj->getJob(),
									'job_item_id' => $pc_obj->getJobItem(),
									'quantity' => (float)$pc_obj->getQuantity(),
									'bad_quantity' => (float)$pc_obj->getBadQuantity(),
									'note' => $pc_obj->getNote(),

									'other_id1' => $pc_obj->getOtherID1(),
									'other_id2' => $pc_obj->getOtherID2(),
									'other_id3' => $pc_obj->getOtherID3(),
									'other_id4' => $pc_obj->getOtherID4(),
									'other_id5' => $pc_obj->getOtherID5(),

									//Punch Data
									'punch_id' => $p_obj->getId(),
									'status_id' => $p_obj->getStatus(),
									'type_id' => $p_obj->getType(),
									'station_id' => $p_obj->getStation(),
									'station_data' => $station_data,
									'time_stamp' => $p_obj->getTimeStamp(),
									//Use this so the date is always insync with the time.
									'date_stamp' => $p_obj->getTimeStamp(),
									'original_time_stamp' => $p_obj->getOriginalTimeStamp(),
									'actual_time_stamp' => $p_obj->getActualTimeStamp(),

									'created_date' => $p_obj->getCreatedDate(),
									'created_by' => $p_obj->getCreatedBy(),
									'created_by_name' => (string)$ulf->getFullNameById( $p_obj->getCreatedBy() ),
									'updated_date' => $p_obj->getUpdatedDate(),
									'updated_by' => $p_obj->getUpdatedBy(),
									'updated_by_name' => (string)$ulf->getFullNameById( $p_obj->getUpdatedBy() ),
									'deleted_date' => $p_obj->getDeletedDate(),
									'deleted_by' => $p_obj->getDeletedBy()
								);
			}
		} elseif ( $action != 'submit' ) {
			Debug::Text(' ID was NOT passed: '. $id, __FILE__, __LINE__, __METHOD__,10);

			//UserID has to be set at minimum
			if ( $punch_control_id != '' ) {
				Debug::Text(' Punch Control ID was passed: '. $punch_control_id, __FILE__, __LINE__, __METHOD__,10);

				//Get previous punch, and default timestamp to that.
				$plf = new PunchListFactory();
				$plf->getPreviousPunchByPunchControlID( $punch_control_id );
				if ( $plf->getRecordCount() > 0 ) {
					$prev_punch_obj = $plf->getCurrent();
					$time_stamp = $prev_punch_obj->getTimeStamp()+3600;
					$date_stamp = $prev_punch_obj->getTimeStamp(); //Match date with previous punch as well, incase a new day hasnt been triggered yet.
				} else {
					$time_stamp = TTDate::getTime();
					$date_stamp = NULL;
				}

				$pclf = new PunchControlListFactory();
				$pclf->getById( $punch_control_id );
				if ( $pclf->getRecordCount() > 0 ) {
					$pc_obj = $pclf->getCurrent();

					if ( $date_stamp == NULL ) {
						$date_stamp = $pc_obj->getUserDateObject()->getDateStamp();
					}

					$pc_data = array(
									'id' => $pc_obj->getId(),
									'user_id' => $pc_obj->getUserDateObject()->getUser(),
									'user_full_name' => $pc_obj->getUserDateObject()->getUserObject()->getFullName(),
									'date_stamp' => $date_stamp,
									'user_date_id' => $pc_obj->getUserDateObject()->getId(),
									'time_stamp' => $time_stamp,
									'branch_id' => $pc_obj->getBranch(),
									'department_id' => $pc_obj->getDepartment(),
									'job_id' => $pc_obj->getJob(),
									'job_item_id' => $pc_obj->getJobItem(),
									'quantity' => (float)$pc_obj->getQuantity(),
									'bad_quantity' => (float)$pc_obj->getBadQuantity(),
									'note' => $pc_obj->getNote(),

									'other_id1' => $pc_obj->getOtherID1(),
									'other_id2' => $pc_obj->getOtherID2(),
									'other_id3' => $pc_obj->getOtherID3(),
									'other_id4' => $pc_obj->getOtherID4(),
									'other_id5' => $pc_obj->getOtherID5(),

									'status_id' => $status_id
									);
				}
			} elseif ( $user_id != '' ) {
				Debug::Text(' User ID was passed: '. $user_id .' Date Stamp: '. $date_stamp, __FILE__, __LINE__, __METHOD__,10);

				//Don't guess too much. If they click a day to add a punch. Make sure that punch is on that day.
				if ( isset($date_stamp) AND $date_stamp != '' ) {
					$time_stamp = $date_stamp + (3600*12); //Noon
				} else {
					$time_stamp = TTDate::getBeginDayEpoch( TTDate::getTime() ) + (3600*12); //Noon
				}

				/*
				if ( isset($date_stamp) AND $date_stamp != '' ) {
					$epoch = $date_stamp;
				} else {
					$epoch = TTDate::getTime();
				}
				//Get previous punch, and default timestamp to that.
				$plf = new PunchListFactory();
				$plf->getPreviousPunchByUserIDAndEpoch( $user_id, $epoch );
				if ( $plf->getRecordCount() > 0 ) {
					Debug::Text(' Found Previous punch: ', __FILE__, __LINE__, __METHOD__,10);
					$prev_punch_obj = $plf->getCurrent();
					$time_stamp = $prev_punch_obj->getTimeStamp()+3600;
				} else {
					$time_stamp = $date_stamp;
				}
				*/
				$ulf = new UserListFactory();
				$ulf->getByIdAndCompanyId( $user_id, $current_company->getId() );
				if ( $ulf->getRecordCount() > 0 ) {
					$user_obj = $ulf->getCurrent();

					$pc_data = array(
									'user_id' => $user_obj->getId(),
									'user_full_name' => $user_obj->getFullName(),
									'date_stamp' => $date_stamp,
									'time_stamp' => $time_stamp,
									'status_id' => $status_id,
									'branch_id' => $user_obj->getDefaultBranch(),
									'department_id' => $user_obj->getDefaultDepartment(),
									'quantity' => 0,
									'bad_quantity' => 0
									);
				}

				unset($time_stamp, $plf);
			}
		}


		$blf = new BranchListFactory();
		$branch_options = $blf->getByCompanyIdArray( $current_company->getId() );

		$dlf = new DepartmentListFactory();
		$department_options = $dlf->getByCompanyIdArray( $current_company->getId() );

		if ( $current_company->getProductEdition() == 20 ) {
			$jlf = new JobListFactory();
			$jlf->getByCompanyIdAndUserIdAndStatus( $current_company->getId(), $pc_data['user_id'], array(10,20,30,40) );
			$pc_data['job_options'] = $jlf->getArrayByListFactory( $jlf, TRUE, TRUE );
			$pc_data['job_manual_id_options'] = $jlf->getManualIDArrayByListFactory($jlf, TRUE);

			$jilf = new JobItemListFactory();
			$jilf->getByCompanyId( $current_company->getId() );
			$pc_data['job_item_options'] = $jilf->getArrayByListFactory( $jilf, TRUE, TRUE );
			$pc_data['job_item_manual_id_options'] = $jilf->getManualIdArrayByListFactory( $jilf, TRUE );
		}

		//Select box options;
		$pc_data['status_options'] = $pf->getOptions('status');
		$pc_data['type_options'] = $pf->getOptions('type');
		$pc_data['branch_options'] = $branch_options;
		$pc_data['department_options'] = $department_options;

		//Get other field names
		$oflf = new OtherFieldListFactory();
		$pc_data['other_field_names'] = $oflf->getByCompanyIdAndTypeIdArray( $current_company->getId(), 15 );

		//Debug::Text('pc_data[date_stamp]: '. TTDate::getDate('DATE+TIME', $pc_data['date_stamp']), __FILE__, __LINE__, __METHOD__,10);
		$smarty->assign_by_ref('pc_data', $pc_data);

		break;
}

$smarty->assign_by_ref('pcf', $pcf);
$smarty->assign_by_ref('pf', $pf);

$smarty->display('punch/EditPunch.tpl');
?>