<?php
/* Copyright (C) 2013-2020	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	   	htdocs/myschedule/tabs/massdelete.php
 *	\ingroup		myschedule
 *	\brief	  	Page of fichinter myschedule
 */

// on charge la liste des évènements
print " events: [\n";
$return=array();
$sql = 'SELECT f.ref, f.description as descinter, ft.rowid, ft.description, ft.fk_fichinter, ft.duree, ft.rang,';
$sql.= ' ft.date as date_intervention, s.nom';
$sql.= ' FROM '.MAIN_DB_PREFIX.'fichinterdet as ft, '.MAIN_DB_PREFIX.'fichinter as f';
$sql.= ' , '.MAIN_DB_PREFIX.'societe as s';
if ($perioduser > 0) {
	$sql.= ' , '.MAIN_DB_PREFIX.'element_contact as ec  , '.MAIN_DB_PREFIX.'c_type_contact as ctc';
	$sql.= ' , '.MAIN_DB_PREFIX.'user as u ';
}
$sql.= ' WHERE date_format(ft.date, "%Y-%m-%d") >= "'.$fullcalendarfirstday.'"';
$sql.= ' AND date_format(ft.date, "%Y-%m-%d") <= "'.$fullcalendarlastday.'"';
$sql.= ' AND ft.fk_fichinter = f.rowid';
$sql.= ' AND f.fk_soc= s.rowid';

if ($dolstatut > 0) 
	$sql.= ' AND f.fk_statut = '.$dolstatut;

if ($perioduser > 0) {
	$sql.= ' AND f.rowid = ec.element_id AND ec.fk_c_type_contact = ctc.rowid';
	$sql.= ' AND ctc.element="fichinter" and source="internal"';
	$sql.= ' AND ec.fk_socpeople = u.rowid';
	// pour récupérer les subalterne quand on est le boss
	$sql.= ' AND (u.rowid='.$perioduser.' OR u.fk_user='.$perioduser.')';
}

if ($periodsoc > 0) {
	$sql.= ' AND (f.fk_soc = '.$periodsoc;
	$sql.= ' OR s.parent = '.$periodsoc.")";
}

$sql.= ' ORDER BY ft.rang ASC, ft.date ASC, ft.rowid';

// pour rendre opérationnel customTooltip
if (!is_object($hookmanager)) $hookmanager = new HookManager($db);
	
$resql = $db->query($sql);
if ($resql) {
	$num = $db->num_rows($resql);
	$j = 0;
	
	$object = new Fichinter($db);
	$fichinterdet_schedule = new fichinterdet_schedule($db);
	$userstatic=new User($db);
	while ($j < $num) {
		$objp = $db->fetch_object($resql);
		$object->fetch($objp->fk_fichinter);
		$object->fetch_thirdparty();
		$tab = $object->liste_contact(-1, 'internal');
		//$ret = $fichinterdet_schedule->fetch(0, 0, $objp->rowid);
		$headEvent = "<table border=0 style='background-color:#E0E0E0;'>";
		$dureeinterdet = convertSecondToTime($objp->duree, "allhourmin", 86400);

		// on ajoute un popup pour une saisie plus fine
		$headEvent.= "<tr><td>".img_picto($objp->descinter, 'object_intervention' )." ".$objp->ref;

		if ($editPlanned || $editMade) {
			$libstatus = $object->getLibStatut(2);
			$headEvent.= "</td><td align=right>".$libstatus;
			$headEvent.= "&nbsp;".img_picto("Zoomin", 'detail', "class='openDialog' data-rowname='".$objp->rowid."'" )."</td></tr>";
		} else
			$headEvent.= "</td><td align=right>".$object->getLibStatut(2)."</td>";
		$nomTiers = $object->thirdparty->getNomUrl(3, "", 0, 1);
		$title=$nomTiers;
		//La ligne de description est toujours présente
		$title.="<br>".dol_trunc($objp->description, 30);

		$nbUser = count($tab);
		if ($nbUser > 0) {
			$title.="<hr>";
			$totalPlanned= 0;
			$totalMade= 0;
			$userArray=array();

			// champs contenant les ids des inter et contact ainsi que le temps associé

			foreach($tab as $userinter) {
				$ret = $userstatic->fetch($userinter['id']);
				$title.="<div  style='float:left;width:99%;'><div style='display: inline-block;'>".$userstatic->getnomUrl(1, "", 0, 1)."</div>";
				 //.' ('.$userinter['libelle'].')'."<br>";

				// on récupère ce qui a été saisie pour cet user/inter
				//$ret = $fichinterdet_schedule->fetch(0, $userinter['id'], $objp->rowid);
				$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 = 0;
				$default = "";
				$made = 0;
				if ($reusersql) {
					$objuser = $db->fetch_object($reusersql);
					$planned = $objuser->duration_planned;
					$made = ($objuser->duration_made!=0?$objuser->duration_made:0);

					$madehour = round($made/3600, 0, PHP_ROUND_HALF_DOWN);
					$plannedhour = round($planned/3600, 0, PHP_ROUND_HALF_DOWN);
					$mademin = ($made - ($madehour*3600)) / 60;
					$plannedmin = ($planned - ($plannedhour*3600)) / 60;
	
					if ($editPlanned) {
						if ($made == 0) {
							$title.= "<div style='display: inline-block;width:32px;text-align:center;'> ";
							$title.= img_picto(
								"Fill ".$dureeinterdet, 'rightarrow', 
								"class='AutoFillTime' data-rowname='".$objp->rowid."-".$userinter['id']."' data-duree='".$objp->duree."' data-value='".$dureeinterdet."'"
							);
							$title.=" </div>";
						}

						$title.="<div style='float:right;display: inline-block;text-align:right;' name='".$objp->rowid."-".$userinter['id']."'>";
						if ($planned >0)
							$title.=convertSecondToTime($planned, "allhourmin", 86400);
						else
							$title.="00:00";

						if ($made != 0) {
							// on affiche ce qui a déjà été réalisé, pas possible de changé ce qui a déja été planifié alors
							$title.="&nbsp;/&nbsp;<div style='float:right;display: inline-block;background-color:#".$conf->global->MYSCHEDULE_colormade."'>";
							$title.=convertSecondToTime($made, "allhourmin", 86400);
							$title.="</div>";
						}
						$title.="</div>";
					} elseif ($editMade) {
						//$title.= "<br>"; // on passe à la ligne la gestion des heures
						$title.= "<div style='display: inline-block;width:17px;text-align:center;'> ";
						$title.=" </div>";

						
						$title.="<div style='display: inline-block;text-align:right;'";
						$title.=" name='".$objp->rowid."-".$userinter['id']."'>";
						if ($planned >0)
							$title.=convertSecondToTime($planned, "allhourmin", 86400);
						else
							$title.="00:00";
						$title.="</div>";

						$title.= "<div style='display: inline-block;width:16px;text-align:center;'>";
						//si il y a un temps de prévue on l'affecte
						if ($planned> 0)
							$title.= img_picto(
								"Fill ".convertSecondToTime($planned, "allhourmin", 86400), 'rightarrow', 
								"class='AutoFillTimeMade' data-rowname='".$objp->rowid."-".$userinter['id']."' data-duree='".$objp->planned."' data-value='".convertSecondToTime($planned, "allhourmin", 86400)."'"
							);
						else // si pas de temps prévue on affecte celui de l'intervention
							$title.= img_picto(
								"Fill ".$dureeinterdet, 'rightarrow@myschedule', 
								"class='AutoFillTimeMade' data-rowname='".$objp->rowid."-".$userinter['id']."' data-duree='".$objp->duree."' data-value='".$dureeinterdet."'"
							);

						$title.= "</div>";

						// on affiche ce qui a déjà été réalisé, pas possible de changé ce qui a déja été planifié alors
						$title.="<div style='float:right;display: inline-block;background-color:#".$conf->global->MYSCHEDULE_colormade."'";
						$title.=" name='made-".$objp->rowid."-".$userinter['id']."'>";

						if ($made > 0)
							$title.=convertSecondToTime($made, "allhourmin", 86400);
						else
							$title.="00:00";
						$title.="</div>";

					} else {
						$title.=" (".convertSecondToTime($planned, "allhourmin", 86400);
						if ($made)
							$title.='/'.convertSecondToTime($made, "allhourmin", 86400);
						$title.=')';
					}
					$totalPlanned+= $planned;
					$totalMade+= $made;
				}
				// reformatage heure et minute
				$userArray[$userinter['id']] = array(
					"name" => $userinter['nom'],
					"made" => ($madehour<10?"0":"").$madehour.":".($mademin<10?"0":"").$mademin,
					"madehour" => $madehour,
					"mademin" => $mademin,
					"planned" => ($plannedhour<10?"0":"").$plannedhour.":".($plannedmin<10?"0":"").$plannedmin,
					"plannedhour" => $plannedhour,
					"plannedmin" => $plannedmin,
				);
				$title.="</div><br>";
			}
		}


		$bshowelement=false;
		$textColor="black";
		// si pas de collaborateur
		if (count($tab) == 0){
			$bgcolor="#".$conf->global->MYSCHEDULE_colornouser;
			if(in_array('nouser', $filterbystatut))
				$bshowelement=true;
		} elseif ($totalPlanned < $objp->duree || $ret == 0) {
			$bgcolor="#".$conf->global->MYSCHEDULE_colornotplanned;
			if(in_array('notplanned', $filterbystatut))
				$bshowelement=true;
		} elseif($totalPlanned >= $objp->duree && $made == 0){
				$bgcolor="#".$conf->global->MYSCHEDULE_colornotmade;
			if(in_array('notmade', $filterbystatut))
				$bshowelement=true;
		} elseif($made > 0){
			$bgcolor="#".$conf->global->MYSCHEDULE_colormade;
			if(in_array('made', $filterbystatut))
				$bshowelement=true;
		} else {
			$bgcolor="#C0C0C0";
			if(in_array('made', $filterbystatut))
				$bshowelement=true;
		}

		if ($bshowelement) {
			$event =array();
			$event['id'] = $objp->rowid;
			$event['title'] = '';

			$event['start'] =$objp->date_intervention;
			$datedebevent =$db->jdate($objp->date_intervention);

			$event['datestart'] = date("d", $datedebevent)."/".date("m", $datedebevent)."/".date("Y", $datedebevent);
			// on décompose la durée pour l'affichage (plus simple en php qu'en js)
			$event['duree'] = $objp->duree;
			$dureehour = round($objp->duree/3600, 0, PHP_ROUND_HALF_DOWN);
			$dureemin =  ($objp->duree - ($dureehour*3600)) / 60;
			if ($dureemin < 10) 
				$dureemin = "0".$dureemin;
			$event['dureehourmin'] = $dureehour.":".$dureemin;

			$dateendevent= dol_time_plus_duree($datedebevent, ($objp->duree/3600),"h");
			$event['end'] = substr(date("c", $dateendevent), 0, -6);

			$headEvent.= "<tr><td >".date("H", $datedebevent).":".date("i", $datedebevent);
			$headEvent.= "-".date("H", $dateendevent).":".date("i", $dateendevent);
			$headEvent.="</td><td align=right >".$dureehour.":".$dureemin."&nbsp;</td></tr></table>";
			$event['htmltitle'] = $headEvent.$title;

			$event['color'] = $bgcolor;
			$event['borderColor'] = $textColor;
			$event['textColor'] = $textColor;
			$event['allDay'] = false;
			// infos additionnelle
			$event['ref'] = $object->ref;
			$event['fk_soc'] = $object->socid;
			$event['lib_soc'] = $nomTiers;
			
			$event['fk_statut'] = $object->statut;
			$event['lib_statut'] = $libstatus;

			$event['fi_description'] = $object->description;
			$event['note_private'] = $object->note_private;
			$event['note_public'] = $object->note_public;
			
			$event['fk_projet'] = $object->fk_projet;
			$event['fk_contrat'] = $object->fk_contrat;
			$event['fk_fichinter'] = $objp->fk_fichinter;

			$event['lib_projet'] = "";
			if ($object->fk_projet) {
				$projet_static->fetch($object->fk_projet);
				$event['lib_projet'] = $projet_static->getNomUrl();
			}

			$event['lib_contrat'] ="";
			if ($object->fk_contrat) {
				$contrat_static->fetch($object->fk_contrat);
				$event['lib_contrat'] = $contrat_static->getNomUrl();
			}

			$event['description'] = html_entity_decode(str_replace("<br>", "\n", $objp->description));
			$event['selected'] = false;
			$event['userArray'] = $userArray;

			//array_push($return, $event);
			print json_encode($event);
			print ",\n";
		}
		$j++;
	}
}
print "],\n";