<?php
/* Copyright (C) 2013-2021	Charlene BENKE	<charlene@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	   	htdocs/myschedule/tabs/intervention.php
 *	\ingroup		myschedule
 *	\brief	  	Page of fichinter myschedule
 */

$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.'/core/class/html.formother.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';

require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php';

require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/modules/fichinter/modules_fichinter.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/fichinter.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';

// voir si il est utile de rajouter les contrats
if (! empty($conf->projet->enabled)) {
	require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
	require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
}

if ($conf->contrat->enabled) {
	require_once DOL_DOCUMENT_ROOT."/core/class/html.formcontract.class.php";
	require_once DOL_DOCUMENT_ROOT."/contrat/class/contrat.class.php";
}

require_once DOL_DOCUMENT_ROOT."/holiday/class/holiday.class.php";

dol_include_once('/myschedule/class/myschedule.class.php');

$langs->load('companies');
$langs->load('interventions');
$langs->load('bills');
$langs->load('myschedule@myschedule');

//$langs->load(' ');
//$langs->load('compta');
//$langs->load('bills');
//$langs->load('orders');
$langs->load('products');
if (! empty($conf->margin->enabled))
	$langs->load('margins');

$error=0;

$id 	= GETPOST('id', 'int');
$ref 	= GETPOST('ref', 'alpha');
$socid	= GETPOST('socid', 'int');
$action	= GETPOST('action', 'alpha');

// Security check
if (! empty($user->societe_id))
	$socid=$user->societe_id;
$result = restrictedArea($user, 'ficheinter', $id, 'fichinter');

$object = new Fichinter($db);

// Load object
if ($id > 0 || ! empty($ref)) {
	if ($action != 'add') {
		$ret=$object->fetch($id, $ref);
		if ($ret == 0) {
			$langs->load("errors");
			setEventMessage($langs->trans('ErrorRecordNotFound'), 'errors');
			$error++;
		} else if ($ret < 0) {
			setEventMessage($object->error, 'errors');
			$error++;
		} else {
			$id = $object->id;
			$object->fetch_thirdparty();
		}
	}
} else {
	header('Location: '.DOL_URL_ROOT.'/fichinter/list.php');
	exit;
}



/*
 * Action
 */
if ($action == "update") {
	// récupération des jours d'interventions dans les lignes
	$sql= 'SELECT * FROM '.MAIN_DB_PREFIX.'fichinterdet as ft';
	$sql.= ' WHERE ft.fk_fichinter = '.$object->id;
	$sql.= ' ORDER BY ft.date ASC';

	$resql= $db->query($sql);
	if ($resql) {
		$num = $db->num_rows($resql);
		$i = 0;

		// on a en colonne les interventions
		if ($num) {
			$var=true;
			$tab = $object->liste_contact(-1, 'internal');

			$fichinterdet_schedule = new fichinterdet_schedule($db);

			while ($i < $num) {
				$obj = $db->fetch_object($resql);
				foreach($tab as $userinter) {
					$namef = $obj->rowid.'-'.$userinter['id'];
					$planned= GETPOST("planned-".$namef)?GETPOST("planned-".$namef, "int"):0;
					$made = GETPOST("made-".$namef)?GETPOST("made-".$namef,"int"):0;
					
					// on supprime l'ancien
					$fichinterdet_schedule->delete(0, $userinter['id'], $obj->rowid);
					
					// on ajoute à nouveau
					if ($planned !="" || $made!="" ) {
						$fichinterdet_schedule->fk_user = $userinter['id'];
						$fichinterdet_schedule->fk_fichinterdet = $obj->rowid;
						$fichinterdet_schedule->duration_planned = $planned * 3600;
						$fichinterdet_schedule->duration_made = $made * 3600;
						$fichinterdet_schedule->insert();
//						print $namef."==".$planned."+".$made."<br>";
					}
				}

				$i++;
			}
		}
	}
}



/*
 * View
 */
$title=$langs->trans("Intervention").' - '.$langs->trans("mySchedule");
$help_url='https://wiki.patas-monkey.com/index.php?title=MySchedule';

llxHeader('', $title, $help_url);

$form = new Form($db);
$formother = new FormOther($db);
$formfile = new FormFile($db);
$companystatic=new Societe($db);

$now=dol_now();

/*
 * Show object in view mode
 */

$soc = new Societe($db);
$soc->fetch($object->socid);

$object->fetch_thirdparty();

$head = fichinter_prepare_head($object);

dol_fiche_head($head, 'myschedule', $langs->trans("InterventionCard"), -1, 'intervention');


$linkback = '<a href="'.DOL_URL_ROOT.'/fichinter/list.php'.(! empty($socid)?'?socid='.$socid:'').'">';
$linkback.= $langs->trans("BackToList").'</a>';

$morehtmlref='<div class="refidno">';

// Thirdparty
$morehtmlref.=$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
// Project
if ($conf->contrat->enabled) {
	require_once DOL_DOCUMENT_ROOT."/core/class/html.formcontract.class.php";
	require_once DOL_DOCUMENT_ROOT."/contrat/class/contrat.class.php";
	$langs->load("contract");
	$morehtmlref.='<br>'.$langs->trans('Contract') . ' : ';
	if (! empty($object->fk_contrat)) {
		$contratstatic = new Contrat($db);
		$contratstatic->fetch($object->fk_contrat);
		$morehtmlref.=$contratstatic->getNomUrl(0, '', 1);
	}
}
$morehtmlref.='</div>';
dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
dol_fiche_end();
//print '<div class="underbanner clearboth"></div>';
print load_fiche_titre($title, "", 'myschedule@myschedule');


print '<form method="POST" action="useraffect.php?id='.$id.'">';
print '<input type="hidden" name="action" value="update">';
print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
print '<br>';
print '<table class="border" >';
// récupération des jours d'interventions dans les lignes
$sqldate = 'SELECT Distinct date(ft.date) as date_intervention';
$sqldate.= ' FROM '.MAIN_DB_PREFIX.'fichinterdet as ft';
$sqldate.= ' WHERE ft.fk_fichinter = '.$object->id;
$sqldate.= ' ORDER BY date_intervention ASC';

$resqldate = $db->query($sqldate);
if ($resqldate) {
	$num = $db->num_rows($resqldate);
	$i = 0;
	$tblsem=array();
	print '<tr class="title">';
	// on a en colonne les interventions
	if ($num) {
		$var=true;
		while ($i < $num) {
			$objdate = $db->fetch_object($resqldate);
			// on récupère les semaines de l'intervention
			if (!in_array(date("Y-W", $db->jdate($objdate->date_intervention)), $tblsem)) {
				$tblsem[]=date("Y-W", $db->jdate($objdate->date_intervention));
			}

			print '<th style="border: 1px solid #333333;">';
			print dol_print_date($db->jdate($objdate->date_intervention), 'day');
			print '</th>';
			$i++;
		}
	}
	print '</tr>';
	$resqldate = $db->query($sqldate);
	if ($resqldate) {
		$numdt = $db->num_rows($resqldate);
		$i = 0;
		print '<tr class="title">';
		if ($numdt) {
			$var=true;
			while ($i < $numdt) {
				$objdate = $db->fetch_object($resqldate);
				print '<td valign=top width=200px style="border: 1px solid #333333">';
				// on s�lectionne les �l�ments de la date
				// Intervention lines
				$sql = 'SELECT ft.rowid, ft.description, ft.fk_fichinter, ft.duree, ft.rang,';
				$sql.= ' ft.date as date_intervention';
				$sql.= ' FROM '.MAIN_DB_PREFIX.'fichinterdet as ft';
				$sql.= ' WHERE ft.fk_fichinter = '.$object->id;
				$sql.= ' AND date_format(ft.date, "%Y-%m-%d") = "'.substr($objdate->date_intervention, 0, 10).'"';
				$sql.= ' ORDER BY ft.rang ASC, ft.date ASC, ft.rowid';
				$resql = $db->query($sql);
				if ($resql) {
					$num = $db->num_rows($resql);
					$j = 0;

					// on regarde si il y a déjà de la saisie pour cette ligne d'inter
					$var=true;
					while ($j < $num) {
						$objp = $db->fetch_object($resql);
						$fichinterdet_schedule = new fichinterdet_schedule($db);
						$fichinterdet_schedule->fetch(0, 0, $objp->rowid);
						// si on a déjà une ligne de saisie
						if ($fichinterdet_schedule->duration_planned == 0) {
							$notyetplanned = true;
							$bgcolor="lightgreen";
						} else {
							$notyetplanned = false;
							if($fichinterdet_schedule->duration_made == 0)
								$bgcolor="lightpink";
							else
								$bgcolor="lightgray";
						}

						print '<table bgcolor='.$bgcolor.' width=100% height=100px cellspacing=0>';
						print '<tr >';
						print '<td colspan=3 >';
						//print '<a name="'.$objp->rowid.'"></a>'; // ancre pour retourner sur la ligne
						if (substr($objp->date_intervention, -8) !="00:00:00")
							print "<i>".substr($objp->date_intervention, -8, 5)."</i> - " ;
						else
							print "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" ;
						
						print dol_htmlentitiesbr($objp->description);
						// Duration
						print '</td>';
						print '</tr>';

						print "<tr >";
						print "<th align='center' width='50px' style='padding-top:0px;padding-bottom:0px;'>";
						print convertSecondToTime($objp->duree);
						print '</th>';
//						print '<th>'.$langs->trans("User").'</th>';
						print "<td style='padding-top:0px;padding-bottom:0px;text-align:right;'>".$langs->trans("TimePlanned").'</td>';
						print "<td style='padding-top:0px;padding-bottom:0px;text-align:right;'>".$langs->trans("TimeMade").'</td>';

						print '</tr>';


						$tab = $object->liste_contact(-1,'internal');
						$userstatic=new User($db);
						$userholidays=new Holiday($db);
						$holidaystatic=new Holiday($db);

						foreach($tab as $userinter) {
//							print '<tr><td style="padding-top:0px;padding-bottom:0px;" colspan=3><hr></td></tr>';

							print "<tr><td colspan=3 style='padding-top:0px;padding-bottom:0px;'> ";
							$ret = $userstatic->fetch($userinter['id']);
							print $userstatic->getnomUrl(1); //.' ('.$userinter['libelle'].')'."<br>";

							// on r�cup�re ce qui a �t� saisie pour cet user/inter
							$sql = 'SELECT rowid, fk_product, duration_planned, duration_made';
							$sql.= ' FROM '.MAIN_DB_PREFIX.'fichinterdet_schedule';
							$sql.= ' WHERE fk_fichinterdet = '.$objp->rowid;
							$sql.= ' AND fk_user = '.$userinter['id'];
							$reusersql = $db->query($sql);
							$planned = "";
							$default = "";
							$made = "";
							
							if ($reusersql) {
								$objuser = $db->fetch_object($reusersql);

								$planned = $objuser->duration_planned/3600;
								$made = ($objuser->duration_made!=0?$objuser->duration_made/3600:"");
							}

							print '</td></tr>';

							// si il y a un jour de cong�s...
							
							$dateinter= substr($objdate->date_intervention, 0, 10);
							$filterDate = " AND date_debut <= '".$dateinter."'";
							$filterDate.= " AND date_fin >= '".$dateinter."'";
							$ret = $userholidays->fetchByUser($userinter['id'], "", $filterDate);
							if ($ret == 1) {
								foreach($userholidays->holiday as $holiday) {
									$tdstyle="style='padding-top:0px;padding-bottom:0px;'";
	
									$holidaystatic->fetch($holiday['rowid']);
									if ($holidaystatic->statut  == 1)
											$trstyle="background-color:yellow;";
									elseif ($holidaystatic->statut  == 2)
											$trstyle="background-color:orange;";
									elseif ($holidaystatic->statut  == 3)
											$trstyle="background-color:red;";
									print "<tr style='".$trstyle."'> <td nowrap ".$tdstyle." align=right>";
									print $holidaystatic->getNomUrl(1)." ".$holidaystatic->getLibStatut(3);
									print '</td>';
								}
							} else {
								$tdstyle="style='padding-top:0px;padding-bottom:0px;'";
								print "<tr><td ".$tdstyle." ></td>";
							}
							print "<td ".$tdstyle." align=right>";
							// id fichinterdet et id user
							$namef=$objp->rowid.'-'.$userinter['id'];
							// si rien de plannifi� encore
							if ($planned == "") {
								if (count($tab)!=1) {
									// on ajoute l'icone d'affectation rapid
									if ($notyetplanned)
									print img_picto(
													$langs->trans("AutoFill"), 'rightarrow', 
													"class='AutoFillPlanned' data-intername='planned-".$objp->rowid."'  data-rowname='planned-".$namef."' data-value='".($objp->duree/3600)."'");
								} else {
									// si c'est une valeur pr�d�finie
									print img_picto($langs->trans("Predefined"), 'star');
									$default = $objp->duree/3600;
								}
							}
							print '<input type="text" size="1" class="planned-'.$objp->rowid.'" name="planned-'.$namef.'" value="'.($planned ? $planned : $default).'">';
							print "</td><td ".$tdstyle." align=right>";
							// si planifi� saisie et pas encore de r�alis�
							if ($planned != "" && $made =="") {
								if (count($tab)!=1) {
									// on ajoute l'icone d'affectation rapide
									print img_picto("Auto fill", '1rightarrow', "class='AutoFillMade' data-rowname='made-".$namef."' data-value='".$planned."'");
								} else {
									// si c'est une valeur pr�d�finie
									print img_picto($langs->trans("Predefined"), 'star');
									$made = $planned;
								}
							}
							// 
							print '<input type="text" size="1" class="amount" name="made-'.$namef.'" value="'.($made ).'">';
							print '</td></tr>';
						}
						print '</table>';
						print "<br>";
						$j++;
					}
				}
				print '</td>';
				$i++;
			}
		}
		print '</tr>';
	}
}

/*
 * Boutons Actions
 */

if ($object->statut < 2 ) {
	print "<tr><td align=center rowspan=2>";
	print '<div class="tabsAction">';
	// 0 = draft
	// 1 = Valided
	// 2 = Billed
	// 3 = Close
	// 4 = Partial Close
	print "<input class='button' type=submit value='".$langs->trans('Save')."'>";
	print '</div>';
	print "</td></tr>";
}
print '</table>';
print '</form>';

// on affiche les activit�s sur les semaines de l'interventions

foreach($tblsem as $semaine) {
	$infosemaine=explode("-", $semaine);
	$timeStampPremierJanvier = strtotime($infosemaine[0] . '-01-01');
	$jourPremierJanvier = date('w', $timeStampPremierJanvier);
	$numSemainePremierJanvier = date('W', $timeStampPremierJanvier);

	print '<table class="noborder" >';
	//-- nombre � ajouter en fonction du num�ro pr�c�dent ------------
	$decallage = ($numSemainePremierJanvier == 1) ? (int) ($infosemaine[1] ) - 1 : (int) $infosemaine[1];
	//-- timestamp du jour dans la semaine recherch�e ----------------
	$timeStampDate = strtotime('+' . $decallage . ' weeks', $timeStampPremierJanvier);
	//-- recherche du lundi de la semaine en fonction de la ligne pr�c�dente ---------
	$jour[0] = ($jourPremierJanvier == 1) ?  $timeStampDate : strtotime('last monday', $timeStampDate);
//var_dump($jour);
	// on affiche les entetes de colonnes de semaine
	print '<tr class="title">';
	print '<th>'.$langs->trans('Week')." ".$semaine.'</th>';
	print '<th>'.$langs->trans('NbHrsByWeek').'</th>';
	print '<th>'.$langs->trans('NbHrHoliday').'</th>';
	for ($i=0;$i<=6;$i++) {
		$jour[$i] = strtotime(date("Y-m-d", strtotime(date('d-m-Y', $jour[0])))." +".$i." day"); 
		print '<th align=right>'.date('d/m/Y', $jour[$i]).'</th>';
	}
	print '<th align=right>'.$langs->trans('Total').'</th>';
	print '<th align=right>'.$langs->trans('Ecart').'</th>';

	print '</tr>';
	// on boucle sur les salari�s
	foreach($tab as $userinter) {
		$var=!$var;
		print "<tr $bc[$var]>";
		print "<td valign=top> ";
		$ret = $userstatic->fetch($userinter['id']);
		print $userstatic->getnomUrl(1); //.' ('.$userinter['libelle'].')'."<br>";
		$planned = 0;
		$made = 0;

		print "</td>";
		// nombre d'heures d'activit� hebdo
		print "<td valign=top> ";
		print convertSecondToTime($userstatic->weeklyhours * 3600, 'allhourmin', 86400) ;
		print "</td>";
		// nombre d'heures de cong�s
		print "<td valign=top> ";
		$filterDate = ' AND date_format(fd.date_debut, "%Y-%m-%d") <= "'.date("Y-m-d", strtotime(date("Y-m-d", strtotime(date('d-m-Y', $jour[0])))))."'";
		$filterDate = ' AND date_format(fd.date_fin, "%Y-%m-%d") >= "'.date("Y-m-d", strtotime(date("Y-m-d", strtotime(date('d-m-Y', $jour[0])))." +6 day"))."'";
		
		$ret = $userholidays->fetchByUser($userinter['id'], "", $filterDate);
		if ($ret == 1) {
			foreach($userholidays->holiday as $holiday) {
				var_dump($holiday);
			}
		}
		print "</td>";

		for ($i=0;$i<=6;$i++) {
			$jour[$i] = strtotime(date("Y-m-d", strtotime(date('d-m-Y', $jour[0])))." +".$i." day"); 
			// on r�cup�re le nombre de d'heure travaill�
			$sql = 'SELECT sum(duration_planned) as planned, sum(duration_made) as made';
			$sql.= ' FROM '.MAIN_DB_PREFIX.'fichinterdet_schedule as fds';
			$sql.= ' , '.MAIN_DB_PREFIX.'fichinterdet as fd';
			$sql.= ' WHERE fds.fk_fichinterdet = fd.rowid ';
			$sql.= ' AND fds.fk_user = '.$userinter['id'];
			$sql.= ' AND date_format(fd.date, "%Y-%m-%d") = "'.date("Y-m-d", strtotime(date("Y-m-d", strtotime(date('d-m-Y', $jour[0])))." +".$i." day")).'"';
			$reusersql = $db->query($sql);

			if ($reusersql) {
				$objuser = $db->fetch_object($reusersql);
				print "<td align=right valign=top>";
				print ($objuser->planned?convertSecondToTime($objuser->planned):"")."<br>";
				print ($objuser->made?convertSecondToTime($objuser->made):"")."</td>";
				$planned+= $objuser->planned;
				$made+= $objuser->made;
			}
		}
		print "<td align=right valign=top >";
		print ($planned ? convertSecondToTime($planned):"")."<br>";
		print ($made ? convertSecondToTime($made):"")."</td>";
		
		print "<td align=right valign=top >";
		print convertSecondToTime(($userstatic->weeklyhours * 3600) - $planned, 'allhourmin', 86400)."<br>";
		print convertSecondToTime(($userstatic->weeklyhours * 3600) - $made, 'allhourmin', 86400)."</td>";
		print "</tr>";

	}
	print "</table>";
}


//Add js for AutoFill
print '	<script>'."\n";
print ' $(document).ready(function () {'."\n";
print ' 	$(".AutoFillPlanned").on(\'click touchstart\', function(){
				// on vide les lignes
				$("input[class="+$(this).data(\'intername\')+"]").val("").trigger("change");

				// on remplie
				$("input[name="+$(this).data(\'rowname\')+"]").val($(this).data("value")).trigger("change");
				
			});'."\n";
print ' 	$(".AutoFillMade").on(\'click touchstart\', function(){
				// on remplie
				$("input[name="+$(this).data(\'rowname\')+"]").val($(this).data("value")).trigger("change");
			});'."\n";
print '	});'."\n";
print '	</script>'."\n";

// End of page
llxFooter();
$db->close();