<?php
/* Copyright (C) 2005		Rodolphe Quiedeville 	<rodolphe@quiedeville.org>
 * Copyright (C) 2004-2013	Laurent Destailleur  	<eldy@users.sourceforge.net>
 * Copyright (C) 2005-2010	Regis Houssin			<regis.houssin@capnetworks.com>
 * Copyright (C) 2010	 	François Legastelois 	<flegastelois@teclib.com>
 * Copyright (C) 2014-2018	charlene BENKE			<charlie@patas-monkey.com>
 *
 * 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 3 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, see <http://www.gnu.org/licenses/>.
 */

/**
 *	\file	   /myschedule/projet/listtime.php
 *	\ingroup	projet
 *	\brief	  List activities of tasks
 */

$res=0;
if (! $res && file_exists("../../main.inc.php"))
	$res=@include("../../main.inc.php");		// For root directory
if (! $res && file_exists("../../../main.inc.php"))
	$res=@include("../../../main.inc.php");	// For "custom" directory

require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';

require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';

dol_include_once('/myschedule/class/taskschedule.class.php');
dol_include_once('/myschedule/core/lib/myschedule.lib.php');

$langs->load('myschedule@myschedule');

$action=GETPOST('action');
$mode=GETPOST("mode");
$id=GETPOST('id', 'int');

$periodyear=GETPOST('periodyear', 'int');
if (!$periodyear)
	$periodyear=date('Y');

$periodmonth=GETPOST('periodmonth', 'int');
if (!$periodmonth)
	$periodmonth=date('m');

$perioduser=GETPOST('perioduser', 'int');
if (!$perioduser)
	$perioduser=$user->id;

$filter= "";
$seeallproject=GETPOST('seeallproject', 'int');
if ($seeallproject == 1) {
	$seeallproject=" checked ";
} else
	$filter.= " AND p.fk_statut=1";



$refprojectfilter=GETPOST('refprojectfilter');
if ($refprojectfilter ) {
	$filter.= " AND p.ref like '%".$refprojectfilter."%'";
}

// récupération du nombre de jour dans le mois
$time = mktime(0, 0, 0, $periodmonth+1, 1, $periodyear); // premier jour du mois suivant
$time--; // Recule d'une seconde
$nbdaymonth=date('d', $time); // on récupère le dernier jour

$projectid='';
$projectid=isset($_GET["id"])?$_GET["id"]:$_POST["projectid"];

// Security check
$socid=0;
if ($user->societe_id > 0) $socid=$user->societe_id;
$result = restrictedArea($user, 'projet', $projectid);

$form=new Form($db);
$formother = new FormOther($db);
$projectstatic=new Project($db);
$project = new Project($db);
$taskstatic = new Taskschedule($db);

if (GETPOST("perioduser") > 0) {
	$userstatic = new User($db);
	$userstatic->fetch(GETPOST("perioduser"));
} else
	$userstatic= $user;

// Return all project i have permission on.
// I want my tasks and some of my task may be on a public projet that is not my project
//$projectsListId = $projectstatic->getProjectsAuthorizedForUser($userstatic, 0, 1, $filter);
$projectsListId = _getProjectsAuthorizedForUser($userstatic, 0, 1, 0, $filter);
//print $projectsListId ;
	// We want to see all task of project i am allowed to see, not only mine. Later only mine will be editable later.
$tasksarray=$taskstatic->getTasksArray($userstatic, 0, $projectsListId, $socid, 0, $refprojectfilter);
$projectsrole=$taskstatic->getUserRolesForProjectsOrTasks($userstatic, 0, $projectsListId, 0);
$tasksrole=$taskstatic->getUserRolesForProjectsOrTasks(0, $userstatic, $projectsListId, 0);

/*
 * Actions
 */
// on ne controle que la partie lecture
if ($action == 'addtime' && $user->rights->projet->lire) {

	// no limit for the time
	set_time_limit(0);
	// on boucle sur les lignes de taches
	setsheetLines($j, 0, $tasksarray, $level, $projectsrole, $tasksrole, $perioduser);

	setEventMessage($langs->trans("RecordSaved"));

	$action ="";
	// Redirect to avoid submit twice on back
	$location='Location: '.$_SERVER["PHP_SELF"].'?id='.$projectid;
	$location.=($perioduser?'&perioduser='.$perioduser:"");
	$location.=($mode?'&mode='.$mode:"");

	$location.=($periodmonth?'&periodmonth='.$periodmonth:"");
	$location.=($periodyear?'&periodyear='.$periodyear:"");
	//header($location);
	//exit;
}

/*
 * View
 */


$title=$langs->trans("TimePlannedPeriod");

llxHeader("", $title, "");

//$projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, $mine,1);
//var_dump($tasksarray);
//var_dump($projectsrole);
//var_dump($taskrole);

print_barre_liste($title, $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, "", $num);
dol_htmloutput_mesg($mesg);

//

print '<form name="selectperiod" method="POST" action="'.$_SERVER["PHP_SELF"].'?id='.$project->id.'">';
print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
print '<input type="hidden" name="action" value="selectperiod">';

print '<table  >';
print '<tr >';
print '<td width=180px>'.$langs->trans("PeriodAAAAMM").'</td>';
print '<td width=100px>'.$formother->selectyear($periodyear, 'periodyear');
print $formother->select_month($periodmonth, 'periodmonth').'</td>';
print '<td width=200px><div id="lblBlurWeekEnd">';
print img_picto("ShowHideWeekendColumns", "edit_add").$langs->trans("ShowHideWeekend").'</div></td>';
print "</tr>\n";
print '<tr >';
print '<td>'.$langs->trans("UserToDisplay").'</td>';
$showempty=0;
// attention le dernier paramétre n'est dispo que sur la 3.7 et le patch fournis
$filteruser="";
if ($user->admin == 0)
	$filteruser=" AND (u.rowid = ".$user->id." OR fk_user=".$user->id.")";

print '<td >'.$form->select_dolusers(
				$perioduser, 'perioduser', $showempty,
				'', 0, '', '', 0, 0, 0, $filteruser
).'</td>';
print '<td ><input type=submit name="select" value="'.$langs->trans("Select").'"></td>';
print "</tr>\n";

print '<tr >';
print '<td width=170px>'.$langs->trans("RefProjectFilter").'</td>';
print '<td ><input type="text" name="refprojectfilter" value="'.$refprojectfilter.'"</td>';
print '<td ><input type="checkbox" name="seeallproject" value=1 '.$seeallproject.'>';
print '&nbsp;'.$langs->trans("SeeAllProject").'</td>';
print "</tr>\n";

print "</table>";
print '</form>';


print '<form name="addtime" method="POST" action="'.$_SERVER["PHP_SELF"].'?id='.$project->id.'">';
print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
print '<input type="hidden" name="action" value="addtime">';
print '<input type="hidden" name="mode" value="'.$mode.'">';

print '<input type="hidden" name="periodyear" value="'.$periodyear.'">';
print '<input type="hidden" name="periodmonth" value="'.$periodmonth.'">';
print '<input type="hidden" name="perioduser" value="'.$perioduser.'">';

print '<input type="hidden" name="onlyopenproject" value="'.$onlyopenproject.'">';
print '<input type="hidden" name="refprojectfilter" value="'.$refprojectfilter.'">';

print '<table class="noborder" width="100%">';
print '<tr class="liste_titre">';
print '<td>'.$langs->trans("Project").' / '.$langs->trans("RefTask").'</td>';
print '<td align="right">'.$langs->trans("Status").'</td>';
print '<td colspan="31" align="right">'.$langs->trans("TimePlanned").'&nbsp;<input type=submit name=save></td>';
print "</tr>\n";

timesheetLines($j, 0, $tasksarray, $level, $projectsrole, $tasksrole, $mine, $perioduser);

print "</table>";
print '</form>';
// pour activer ou non le week-end
print '<script language="javascript">';
print '$(document).ready(function() {';
print '$(".weekendtohide").toggle();';
print '	$("#lblBlurWeekEnd").click(function() {';
print '		$(".weekendtohide").toggle();';
print '		$(".weekendtoshow").toggle();';
print '	});';
print '});';
print '</script>';

llxFooter();

$db->close();


/**
 * Output a task line
 *
 * @param	string	   	&$inc			?
 * @param   string		$parent			?
 * @param   Object		$lines			?
 * @param   int			&$level			?
 * @param   string		&$projectsrole	?
 * @param   string		&$tasksrole		?
 * @param   int			$mytask			0 or 1 to enable only if task is a task i am affected to
 * @return  $inc
 */
function timesheetLines(&$inc, $parent, $lines, &$level, &$projectsrole, &$tasksrole, $mytask=0, $perioduser='')
{
	global $bc, $langs, $conf, $db; // $user,
	global $formother, $projectstatic, $taskstatic; //$form,
	global $periodyear, $periodmonth, $nbdaymonth ;

	// détermination du mode de saisie
	$nbhoursonquarterday=$conf->global->MANAGEMENT_NBHOURS_ON_QUARTER_DAY;


	$lastprojectid=0;

	$var=true;

	//$numlines=count($lines);
	//for ($i = 0 ; $i < $numlines ; $i++)
	foreach ($lines as $taskline) {
//		var_dump($lines);
		if ($parent == 0) $level = 0;

		if ($taskline->fk_parent == $parent) {
			// Break on a new project
			if ($parent == 0 && $taskline->fk_project != $lastprojectid) {
				$var = !$var;
				$lastprojectid=$taskline->fk_project;
				print "<tr ".$bc[$var].">\n";

				print '<td>';
				// Project
				$projectstatic->id=$taskline->fk_project;
				$projectstatic->ref=$taskline->projectref;
				$projectstatic->public=$taskline->public;
				$projectstatic->label=$langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$taskline->fk_project];
				print $projectstatic->getNomUrl(1);
				print '</td>';
				print '<td>';

				if ($taskline->thirdparty_id > 0) {
					$socstatic = new Societe($db);
					$socstatic->fetch($taskline->thirdparty_id);
					print $socstatic->getNomUrl(1);
				}
				print '</td>';

				for ($day=1; $day <= $nbdaymonth ; $day++) {
					$curday=mktime(0, 0, 0, $periodmonth, $day, $periodyear);
					$bgcolor="";
					if (date('N', $curday) == 6 || date('N', $curday) == 7) {
						print '<td width=1px class=weekendtoshow bgcolor=grey ></td>';
						$bgcolor=" class=weekendtohide bgcolor=grey ";
					}
					print '<td '.$bgcolor.' align=center>';
					print substr($langs->trans(date('l', $curday)), 0, 1)." ".$day.'</td>';
				}
				print "</tr>\n";
			}

			print "<tr ".$bc[$var].">\n";

			// Ref
			print "<td><a href=# onclick=\"$('.detailligne".$i."').toggle();\" >";
			print img_picto("", "edit_add")."</a>&nbsp;";
			$taskstatic->id=$taskline->id;

			if ($conf->global->MANAGEMENT_DISPLAY_TASKLABEL_INSTEAD_TASKREF == 1) {
				$tasklabel =$taskline->ref." (".dol_print_date($taskline->date_start, 'day');
				$tasklabel.=" - ".dol_print_date($taskline->date_end, 'day').')';
				$taskstatic->label=$tasklabel;
				$taskstatic->ref=$taskline->label;
			} else {
				$tasklabel =$taskline->label." (".dol_print_date($taskline->date_start, 'day');
				$tasklabel.=" - ".dol_print_date($taskline->date_end, 'day').')';
				$taskstatic->ref=$taskline->ref;
				$taskstatic->label=$tasklabel;
			}

			print $taskstatic->getNomUrl(1, ($showproject?'':'withproject'));
			print '</td>';

			// Progress
			print '<td align="right">';
//			$progressvalue=(GETPOST('progress-'.$taskstatic->id)?GETPOST('progress-'.$taskstatic->id):$taskline->progress);
//			print $formother->select_percent($progressvalue, 'progress-'.$taskstatic->id);
			print '</td>';

			for ($day=1; $day <= $nbdaymonth;$day++) {
				$curday=mktime(0, 0, 0, $periodmonth, $day, $periodyear);
				$bgcolor="";
				if (date('N', $curday) == 6 || date('N', $curday) == 7) {
					print '<td width=1px class=weekendtoshow bgcolor=grey ></td>';
					$bgcolor=" class=weekendtohide bgcolor=grey ";
				}
				print '<td '.$bgcolor.' align=center>';
				$timespent=fetchSumTimePlanned($taskstatic->id, $curday, $perioduser);

				if ($nbhoursonquarterday > 0
					&& ($timespent == 0 ||
					 	(($timespent/3600) % $nbhoursonquarterday == 0))) {
					print '<select style="font-size:0.9em"  name="hrs-'.$taskstatic->id.'-'.$day.'">';
					print '<option value="0"></option>';

					for ($hrs=1;$hrs <= 4;$hrs++) {
						print '<option value="'.$hrs * $nbhoursonquarterday.'"';
						if (($timespent/3600) == $hrs * $nbhoursonquarterday ) {
							//$bselected = true;
							print ' selected ';
						}
						print '>';
						print $langs->trans("Quarterday".$hrs);
						print '</option>';
					}
					print '</select>';
				} else {
					// le nom du champs c'est à la fois le jour et l'id de la tache
					print '<input type=text id="inputday" name="hrs-'.$taskstatic->id.'-'.$day.'"';
					if ($timespent !=0)
						print ' value="'.round($timespent/3600, 2).'"';
					print ' size=1 style="font-size:0.7em">';
				}
				print '</td>';
			}

			print "</tr>\n";
			print "<tr style='display:none' class='detailligne".$i."'>";
			print '<td colspan=2>';
			if ($conf->global->MANAGEMENT_DISPLAY_TASKLABEL_INSTEAD_TASKREF == 1)
				print " ".$langs->trans("Ref")." : ".$taskline->ref;
			else
				print " ".$langs->trans("Label")." : ".$taskline->label;
			print "<br>".$langs->trans("TaskStart")." : ";
			print dol_print_date($taskline->date_start, 'day');
			print " - ".$langs->trans("TaskEnd")." : ".dol_print_date($taskline->date_end, 'day');
			print "<br>".$langs->trans("Planned")." : ";
			print convertSecondToTime($taskline->planned_workload, 'allhourmin');
			print " - ".$langs->trans("YetMade")." : ".convertSecondToTime($taskline->duration_effective, 'allhourmin');
			print '</td>';
			// popup pour détail saisie
			for ($day=1;$day <= $nbdaymonth;$day++) {
				$curday=mktime(0, 0, 0, $periodmonth, $day, $periodyear);
				$bgcolor="";
				if (date('N', $curday) == 6 || date('N', $curday) == 7) {
					print '<td width=1px class=weekendtoshow bgcolor=grey ></td>';
					$bgcolor=" class=weekendtohide bgcolor=grey ";
				}
				print '<td '.$bgcolor.' valign=top align=center>';
				$textInDay=fetchTextTimePlanned($taskstatic->id, $curday, $perioduser);
				print "<a href=# onclick=\"$('#txt-".$taskstatic->id."-".$day."').toggle();\" >";
				if ($textInDay != '')
					print "<font color=red><b>X</b></font>";// ..img_info();
				else
					print "X";// ..img_info();
				print '</a><br>';
				print '<textarea style="display:none"';
				print ' id="txt-'.$taskstatic->id.'-'.$day.'" name="txt-'.$taskstatic->id.'-'.$day.'">';
				if ($textInDay)
					print $textInDay;
				print ' </textarea>';
				print '</td>';
			}
			print "</tr>\n";
			$inc++;
			$level++;
			if ($taskline->id)
				timesheetLines($inc, $taskline->id, $lines, $level, $projectsrole, $tasksrole, $mytask, $perioduser);
			$level--;
		}
	}

	return $inc;
}


/**
 * Output a task line
 *
 * @param	string	   	&$inc			?
 * @param   string		$parent			?
 * @param   Object		$lines			?
 * @param   int			&$level			?
 * @param   string		&$projectsrole	?
 * @param   string		&$tasksrole		?
 * @param   int			$mytask			0 or 1 to enable only if task is a task i am affected to
 * @return  $inc
 */
function setsheetLines(&$inc, $parent, $lines, &$level, &$projectsrole, &$tasksrole, $perioduser)
{
	global $db, $user; //$bc, $langs;
	global $taskstatic; //$form, $projectstatic, ;
	global $periodyear, $periodmonth, $nbdaymonth ;


	$lastprojectid=0;

	//$numlines=count($lines);
	//for ($i = 0 ; $i < $numlines ; $i++)
	foreach ($lines as $taskline) {
		if ($parent == 0) $level = 0;

		if ($taskline->fk_parent == $parent) {
			// Break on a new project
			if ($parent == 0 && $taskline->fk_project != $lastprojectid)
				$lastprojectid=$taskline->fk_project;

			// on se positionne sur la tache associé à la ligne
			$taskstatic->fetch($taskline->id);
			$db->begin();

			for ($day=1; $day <= $nbdaymonth; $day++) {
				$durationsuppr=0;
				$curday=mktime(0, 0, 0, $periodmonth, $day, $periodyear);

				// on totalise les durées que l'on va supprimer
				$sql = "SELECT sum(task_duration) as totduration FROM ".MAIN_DB_PREFIX."projet_task_schedule";
				$sql.= " WHERE fk_task = ".$taskstatic->id;
				$sql.= " AND task_date ='".$db->idate($curday)."'";
				$sql.= " AND fk_user = ".$perioduser;

				$resql=$db->query($sql);
				if ($resql) {
					if ($db->num_rows($resql)) {
						$obj = $db->fetch_object($resql);
						$durationsuppr= ($obj->totduration ? $obj->totduration:0);
					}
					$db->free($resql);
				}
				if ($durationsuppr != 0) {
					// on supprime les lignes du mois
					$sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task_schedule";
					$sql.= " WHERE fk_task = ".$taskstatic->id;
					$sql.= " AND task_date ='".$db->idate($curday)."'";
					$sql.= " AND fk_user = ".$perioduser;
					dol_syslog("timesheet.php::setsheetLines sql=".$sql);
					$resql = $db->query($sql);

				}
				// si il y a des choses de saisie dans le champs
				if (GETPOST('hrs-'.$taskstatic->id.'-'.$day)) {
					//print $curday."=".GETPOST ('hrs-'.$taskstatic->id.'-'.$day).'<br>';
					// on alimente les infos pour la saisie
					$taskstatic->timeplanned_date=$curday;
					$taskstatic->timeplanned_datehour=$curday;
					$timespent=GETPOST('hrs-'.$taskstatic->id.'-'.$day);
					if ($timespent=='')
						$timespent=0;
					$taskstatic->timeplanned_duration=$timespent*3600;
					$taskstatic->timeplanned_fk_user=$perioduser;
					$taskstatic->timeplanned_note=GETPOST('txt-'.$taskstatic->id.'-'.$day);

					$taskstatic->addTimePlanned($user, $notrigger = 0);

				}
			}

			$db->commit();

			$inc++;
			$level++;
			if ($taskline->id)
				setsheetLines($inc, $taskline->id, $lines, $level, $projectsrole, $tasksrole, $perioduser);
			$level--;
		} else {
			//$level--;
		}
	}
	return $inc;
}

function _getProjectsAuthorizedForUser($user, $mode=0, $list=0, $socid=0, $filter="")
{
	$projects = array();
	$temp = array();
	global $db, $projectstatic;

	$sql = "SELECT ".(($mode == 0 || $mode == 1) ? "DISTINCT " : "")."p.rowid, p.ref";
	$sql.= " FROM " . MAIN_DB_PREFIX . "projet as p";
	if ($mode == 0 || $mode == 1)
		$sql.= ", " . MAIN_DB_PREFIX . "element_contact as ec";
	$sql.= " WHERE p.entity IN (".getEntity('project', 1).")";
	if ($socid > 0) $sql.= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = " . $socid . ")";

	// Get id of types of contacts for projects (This list never contains a lot of elements)
	$listofprojectcontacttype=array();
	$sql2 = "SELECT ctc.rowid, ctc.code FROM ".MAIN_DB_PREFIX."c_type_contact as ctc";
	$sql2.= " WHERE ctc.element = '" . $projectstatic->element . "'";
	$sql2.= " AND ctc.source = 'internal'";
	$resql = $db->query($sql2);
	if ($resql) {
		while ($obj = $db->fetch_object($resql))
			$listofprojectcontacttype[$obj->rowid]=$obj->code;
	}
	else dol_print_error($db);
	if (count($listofprojectcontacttype) == 0) $listofprojectcontacttype[0]='0';	// To avoid syntax error if not found

	if ($mode == 0) {
		$sql.= " AND ec.element_id = p.rowid";
		$sql.= " AND ( p.public = 1";
		$sql.= " OR ( ec.fk_c_type_contact IN (".join(',', array_keys($listofprojectcontacttype)).")";
		$sql.= " AND ec.fk_socpeople = ".$user->id.")";
		$sql.= " )";
	}
	if ($mode == 1) {
		$sql.= " AND ec.element_id = p.rowid";
		$sql.= " AND (";
		$sql.= "  ( ec.fk_c_type_contact IN (".join(',', array_keys($listofprojectcontacttype)).")";
		$sql.= " AND ec.fk_socpeople = ".$user->id.")";
		$sql.= " )";
	}
	if ($mode == 2) {
		// No filter. Use this if user has permission to see all project
	}

	$sql.= $filter;
	//print $sql;

	$resql = $db->query($sql);
	if ($resql) {
		$num = $db->num_rows($resql);
		$i = 0;
		while ($i < $num) {
			$row = $db->fetch_row($resql);
			$projects[$row[0]] = $row[1];
			$temp[] = $row[0];
			$i++;
		}

		$db->free($resql);

		if ($list) {
			if (empty($temp)) return '0';
			$result = implode(',', $temp);
			return $result;
		}
	} else {
		dol_print_error($this->db);
	}
	return $projects;
}
