<?php
/*
 * Copyright (C) 2007, M2X
 *
 * Authors: Jean-Paul Saman
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

$perms =& $AppUI->acl();

// Create new timesheet or edit an existing one.
$timesheet_id = intval( dPgetParam( $_GET, "timesheet_id", 0 ) );

// check permissions for this record
$canEdit = !getDenyEdit( $m, $timesheet_id );
if (!$canEdit) {
	$AppUI->redirect( "m=public&a=access_denied" );
}
$canDelete = $perms->checkModule( $m, 'delete' );

// use the object oriented design of dP for loading the timesheet that should be edited
// therefore create a new instance of the Timesheet Class
$obj = new CTimesheet();

// load the record data in case of that this script is used to edit the timesheet qith timesheet_id (transmitted via GET)
if (!$obj->load( $timesheet_id, false ) && ($timesheet_id > 0) ) {
	// show some error messages using the dPFramework if loadOperation failed
	// these error messages are nicely integrated with the frontend of dP
	// use detailed error messages as often as possible
	$AppUI->setMsg( 'Timesheet' );
	$AppUI->setMsg( "invalidID", UI_MSG_ERROR, true );
	$AppUI->redirect();					// go back to the calling location
}

// setup the title block
// Fill the title block either with 'Edit' or with 'New' depending on 
// if timesheet_id has been transmitted via GET or is empty
$ttl = ( $timesheet_id > 0 ) ? "Edit Timesheet" : "New Timesheet";
$titleBlock = new CTitleBlock( $ttl, 'timesheet.png', $m, "$m.$a" );
$titleBlock->addCrumb( "?m=timesheet", "view all timesheets" );
if ($canDelete && ($timesheet_id > 0) ) {
	$titleBlock->addCrumbDelete( 'delete timesheet', $canDelete, $msg );
}
$titleBlock->show();

// some javaScript code to submit the form and set the delete object flag for the form processing
?>
<script language="javascript">

	function delIt(id) {
		if (confirm( "<?php echo $AppUI->_('Really delete this timesheet ?');?>" )) {
			var f = document.editFrm;
			f.del.value='1';
			f.submit();
		}
	}

	function changeIt() {
        	var f=document.editFrm;
		f.stat.value='1';
	        f.submit();
	}

	function periodChange() {
		var f=document.editFrm;
		f.period.value='1';
		f.submit();
	}

	function workedHoursChange(val) {
		var f=document.editFrm;
		f.timesheet_worked.value=val;
	}

</script>
<?php
// use the css-style 'std' of the UI style theme to format the table
// create a form providing to add/edit a timesheet

//Pull all users
$q = new DBQuery;
$q->addQuery('user_id, contact_first_name, contact_last_name');
$q->addTable('users');
$q->addTable('contacts');
$q->addWhere('user_contact = contact_id');
$q->addOrder('contact_last_name, contact_first_name');
$q->exec();
$users = array();
while ( $row = $q->fetchRow()) {
  $users[$row['user_id']] = $row['contact_last_name'] . ', ' . $row['contact_first_name'];
}
// Get current submitter name
if ("$obj->timesheet_creator" == "") {
	$submitter = $users[$AppUI->user_id];
	$obj->timesheet_creator = $AppUI->user_id;
}
else
	$submitter = $users[$obj->timesheet_creator];

$q->Clear();

// Get the current timesheet period
if (intval($obj->timesheet_period)) {
	$period = new CDate();
	$period->setMonth($obj->timesheet_period);
}
else
	$period = new CDate();

// Get the current timesheet status
if (intval($obj->timesheet_status))
	$status = $obj->timesheet_status;
else
	$status = 0;

// Get the current timesheet creation date
if (intval($obj->timesheet_date)) {
	$creation_date = new CDate();
	$creation_date->setDate($obj->timesheet_date,DATE_FORMAT_UNIXTIME);
}
else {
	$creation_date = new CDate();
	$obj->timesheet_date = $creation_date->getTime();
}

if (intval($obj->timesheet_worked)) {
	$timesheet_worked = $obj->timesheet_worked;
}
else {
	$obj->timesheet_worked = 0;
}
?>
<table cellspacing="0" cellpadding="4" border="0" width="100%" class="std">
<form name="editFrm" action="./index.php?m=timesheet" method="post">
	<?php
	// if set, the value of dosql is automatically executed by the dP core application
	// do_timesheet_aed.php will be the target of this form
	// it will execute all database relevant commands
	?>
	<input type="hidden" name="dosql" value="do_timesheet_aed" />
	<?php
	// the del variable contains a bool flag deciding whether to run a delete operation on the given object with timesheet_id
	// the value of del will be zero by default (do not delete)
	// or in case of mouse click on the delete icon it will set to '1' by javaScript (delete object with given timesheet_id)
	?>
	<input type="hidden" name="del" value="0" />
	<input type="hidden" name="stat" value="0" />
	<input type="hidden" name="period" value="0" />

	<?php
	// the value of timesheet_id will be the id of the timesheet to edit
	// or in case of addition of a new timesheet it will contain '0' as value
	?>
	<input type="hidden" name="timesheet_id" value="<?php echo $timesheet_id;?>" />
	<input type="hidden" name="timesheet_date" value="<?php echo $obj->timesheet_date;?>" />
	<input type="hidden" name="timesheet_creator" value="<?php echo $obj->timesheet_creator;?>" />
	<input type="hidden" name="timesheet_worked" value="<?php echo $obj->timesheet_worked;?>" />

	<?php
	// please notice that html tags that have no </closing tag> should be closed
	// like you find it here (<tag />) for xhtml compliance
	?>

<tr>
	<td width="50%" valign="top">
		<table cellspacing="0" cellpadding="2" border="0">
		<tr>
			<td align="right" nowrap="nowarp"><?php echo $AppUI->_('Submitter'); ?>:&nbsp;</td>
			<td width="100%">
				<?php echo $submitter; ?>
			</td>
			<td align="right" nowrap="nowarp"><?php echo $AppUI->_('Period'); ?>:&nbsp;</td>
			<td width="100%">
				<?php
					if ( ($canEdit) && ($status < 1) ) {
				?>
				<select name="timesheet_period" size="1' class="text" onChange="periodChange();">
				<option <?php if ($period->getMonth() == 1) echo "selected"; ?> value="1"><? echo dPformSafe('January'); ?></option>
				<option <?php if ($period->getMonth() == 2) echo "selected"; ?> value="2"><? echo dPformSafe('February'); ?></option>
				<option <?php if ($period->getMonth() == 3) echo "selected"; ?> value="3"><? echo dPformSafe('March'); ?></option>
				<option <?php if ($period->getMonth() == 4) echo "selected"; ?> value="4"><? echo dPformSafe('April'); ?></option>
				<option <?php if ($period->getMonth() == 5) echo "selected"; ?> value="5"><? echo dPformSafe('May'); ?></option>
				<option <?php if ($period->getMonth() == 6) echo "selected"; ?> value="6"><? echo dPformSafe('June'); ?></option>
				<option <?php if ($period->getMonth() == 7) echo "selected"; ?> value="7"><? echo dPformSafe('July'); ?></option>
				<option <?php if ($period->getMonth() == 8) echo "selected"; ?> value="8"><? echo dPformSafe('August'); ?></option>
				<option <?php if ($period->getMonth() == 9) echo "selected"; ?> value="9"><? echo dPformSafe('September'); ?></option>
				<option <?php if ($period->getMonth() == 10) echo "selected"; ?> value="10"><? echo dPformSafe('October'); ?></option>
				<option <?php if ($period->getMonth() == 11) echo "selected"; ?> value="11"><? echo dPformSafe('November'); ?></option>
				<option <?php if ($period->getMonth() == 12) echo "selected"; ?> value="12"><? echo dPformSafe('December'); ?></option>
				</select>
				<?php
					}
					else {
						if ($period->getMonth() == 1) echo dPformSafe('January');
						else if ($period->getMonth() == 2) echo dPformSafe('February');
						else if ($period->getMonth() == 3) echo dPformSafe('March');
						else if ($period->getMonth() == 4) echo dPformSafe('April');
						else if ($period->getMonth() == 5) echo dPformSafe('May');
						else if ($period->getMonth() == 6) echo dPformSafe('June');
						else if ($period->getMonth() == 7) echo dPformSafe('July');
						else if ($period->getMonth() == 8) echo dPformSafe('August');
						else if ($period->getMonth() == 9) echo dPformSafe('September');
						else if ($period->getMonth() == 10) echo dPformSafe('October');
						else if ($period->getMonth() == 11) echo dPformSafe('November');
						else if ($period->getMonth() == 12) echo dPformSafe('December');
					}
				?>
			</td>
		</tr>
		<tr>
			<td align="right" nowrap="nowrap"><?php echo $AppUI->_('Creation date'); ?>:&nbsp;</td>
			<td width="100%">
				<?php
					// echo $creation_date ? $creation_date->format( FMT_TIMESTAMP_DATE ) : "" ;
					echo $creation_date->getYear() . "-" . $creation_date->getMonth() . "-" .
					     $creation_date->getDay();
				 ?>	
			</td>
			<td align="right" nowrap="nowarp"><?php echo $AppUI->_('Status'); ?>:&nbsp;</td>
			<td width="100%" align="right"">
				<?php
					if ( ($canEdit) && ($status == 0) ) {
				?>
				<select name="timesheet_status" size="1" class="text" onChange="changeIt()">
				<option <?php if ($status == 0) echo "selected"; ?> value="0"><? echo dPformSafe('Open for Editing');?></option>
				<option <?php if ($status == 1) echo "selected"; ?> value="1"><? echo dPformSafe('Submitted');?></option>
				<option <?php if ($status == 2) echo "selected"; ?> value="2"><? echo dPformSafe('Approved');?></option>
				</select>
				<?php
					}
					else {
						if ($status == 1)
							echo dPformSafe('Submitted');
						else if ($status == 1)
							echo dPformSafe('Approved');
					}
				?>
			</td>
		</tr>
		</table>
	</td>
</tr>
<tr>
	<td>
	<?php 
	// If $status is not "Open for Editing" then don't allow to change the status.
	// There is one exception to this rule the 'administrator' can always change the status.
	      if ($status == 0) 
	      {
	?>
		<input class="button" type="button" name="cancel" value="<?php echo $AppUI->_('cancel');?>" onClick="javascript:if(confirm('Are you sure you want to cancel.')){location.href = './index.php?m=timesheet';}" />
	</td>
	<td align="right">
		<input class="button" type="submit" name="btnFuseAction" value="<?php echo $AppUI->_('submit');?>"/>
	<?php }
	      else {
		echo '&nbsp;</td><td align="right">&nbsp;';
	      }
        ?>
	</td>
</tr>
</form>
</table>

<?php
// Get Project Status information.
$project_types = dPgetSysVal("ProjectStatus");

// Find all tasks in this timesheet period and account them to the project.
function showproject()
{
	global $AppUI, $period, $obj, $project_types;

	$q = new DBQuery();
	$q->addQuery('project_id');
	$q->addQuery('project_name');
	$q->addQuery('project_status');
	$q->addTable('projects');
	$q->addOrder('project_name ASC');
	$projects = $q->LoadList();
	$timesheet_worked = 0;
	foreach ($projects as $row) {
		$project_id = $row["project_id"];
		$t = new DBQuery;
		$t->addQuery('task_id');
		$t->addQuery('task_name');
		$t->addQuery('task_owner');
		$t->addQuery('task_start_date');
		$t->addQuery('task_hours_worked');
		$t->addTable('tasks');
		$t->addWhere('task_project = '. $project_id);
		$t->addOrder('task_start_date DESC');
		$tasks = $t->LoadList();
		$t->Clear();

		$amount = 0;
		foreach ($tasks as $item) {
        	        // Query the task_log table for actual start dates.
			$t->addQuery('task_log_id');
			$t->addQuery('task_log_name');
			$t->addQuery('task_log_creator');
			$t->addQuery('task_log_date');
			$t->addQuery('task_log_hours');
			$t->addTable('task_log');
			$t->addWhere('task_log_task = '. $item["task_id"]);
			// What if this is different then current user?
			$t->addWhere('task_log_creator = ' . $AppUI->user_id);
			$t->addOrder('task_log_date DESC');
			// TODO: select on user and date
			$log = $t->LoadList();
			foreach ($log as $logitem) {
				if (intval($logitem['task_log_date'])) 
				{
					$taskDate = new CDate($logitem['task_log_date']);
					if ($period->GetMonth() == $taskDate->GetMonth()) {
	     					$amount = $amount + $logitem['task_log_hours'];
					}
					// else do not account the worked hours to the project for this month
				}
			}
		}
        $timesheet_worked = $timesheet_worked + $amount;
        if( $amount > 0 )
        {
            echo '<tr>';
            echo '<td>&nbsp;</td>';
            echo '<td><a href="?m=projects&a=view&project_id=' . $row["project_id"] . '">' . $row["project_name"] . '</a>';
            echo '</td>';
            echo '<td>';
		    echo $amount;
		    echo '</td>';
		    echo '<td>' . $project_types[$row['project_status']] . '</td>';
		    echo '</tr>';
        }
	}
	$obj->timesheet_worked = $timesheet_worked;
} // end of function showproject()

function showtimesheetproject()
{
	global $timesheet_id, $project_types;

	$q = new DBQuery();
	$q->addQuery('timesheet_id');
	$q->addQuery('timesheet_project');
	$q->addQuery('timesheet_project_amount');
	$q->addTable('timesheet_project');
	$q->addWhere('timesheet_id = ' . $timesheet_id);
	$q->addOrder('timesheet_project ASC');
	$timesheet = $q->LoadList();
	foreach ($timesheet as $row) {

		$p = new DBQuery();
		$p->addQuery('project_id');
		$p->addQuery('project_name');
		$p->addQuery('project_status');
		$p->addTable('projects');
		$p->addWhere('project_id = ' . $row["timesheet_project"]);
		$p->addOrder('project_name ASC');
		$projects = $p->LoadList();
		foreach ($projects as $project) {
            if( intval( $row['timesheet_project_amount'] ) > 0 )
            {
			    echo '<tr>';
			    echo '<td>&nbsp;</td>';
                echo '<td><a href="?m=projects&a=view&project_id=' . $project["project_id"] . '">' . $project["project_name"] . '</a>';
//			    echo '<td><a href="?m=projects&a=view&project_id=' . $row["timesheet_project"] . '">' . $project["project_name"] . '</a>';
			    echo '</td>';
			    echo '<td>' . $row['timesheet_project_amount'] . '</td>';
			    echo '<td>' . $project_types[$project['project_status']] . '</td>';
			    echo '</tr>';
            }
		}
	}
} // end of function showtimesheetproject()
?>

<table width="100%" border="0" cellpadding="2" cellspacing="1" class="tbl">
<tr>
	<th nowrap="nowrap">&nbsp;</th>
	<th nowrap="nowrap"><?php echo $AppUI->_( 'Project' );?></th>
	<th nowrap="nowrap"><?php echo $AppUI->_( 'Worked hours' );?></th>
	<th nowrap="nowrap"><?php echo $AppUI->_( 'Project status' );?></th>
</tr>
<form name="projectFrm" action="./index.php?m=timesheet" method="post">
	<input type="hidden" name="dosql" value="do_timesheet_aed" />
	<input type="hidden" name="projects" value="0" />

	<input type="hidden" name="timesheet_id" value="<?php echo $timesheet_id;?>" />
	<input type="hidden" name="timesheet_date" value="<?php echo $obj->timesheet_date;?>" />
	<input type="hidden" name="timesheet_creator" value="<?php echo $obj->timesheet_creator;?>" />
	<input type="hidden" name="timesheet_worked" value="<?php echo $obj->timesheet_worked;?>" />
<?php
	if ($status == 0)
		showproject();
	else
		showtimesheetproject();
?>
<script language="javascript">
	 workedHoursChange(<?php echo $obj->timesheet_worked; ?>);
</script>
</form>
</table>