<?php
/* Copyright (C) 2012 		Regis Houssin		<regis.houssin@capnetworks.com>
 * Copyright (C) 2016 		Laurent Destailleur	<eldy@users.sourceforge.net>
 * Copyright (C) 2018-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       myschdule/ficheinter/ajax/events-feed.php
 *       \brief      File to load contacts combobox
 */

if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Disables token renewal
if (! defined('NOREQUIREMENU'))  define('NOREQUIREMENU','1');
//if (! defined('NOREQUIREHTML'))  define('NOREQUIREHTML','1');
if (! defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX','1');
//if (! defined('NOREQUIRESOC'))   define('NOREQUIRESOC','1');
//if (! defined('NOREQUIRETRAN'))  define('NOREQUIRETRAN','1');

$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

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

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

$choiceperiod=GETPOST('choiceperiod', 'alpha');
$datedeb = GETPOST('datedeb', 'alpha');
$datefin = GETPOST('datefin', 'alpha');
$perioduser = GETPOST('perioduser', 'int');
$periodsoc = GETPOST('periodsoc', 'int');
$periodcontact = GETPOST('periodcontact', 'int');

// Si vide, on considère que l'on les prend tous
$filterbystatut = explode(",", GETPOST('filterbystatut',"text") !=""?GETPOST('filterbystatut', 'text'):"nouser,notmade,notplanned,made");

$dolstatut = GETPOST('dolstatut', 'int');

/*
 * View
 */

top_httphead();

//print '<!-- Ajax page called with url '.dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.dol_escape_htmltag($_SERVER["QUERY_STRING"]).' -->'."\n";

// Load original field value
if (! empty($datedeb) && ! empty($datefin)) {

	$return=array();
	$sql = 'SELECT DISTINCT f.ref, f.description as descinter, 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, '.MAIN_DB_PREFIX.'fichinter as f';
	$sql.= ' , '.MAIN_DB_PREFIX.'societe as s';
	if ($perioduser > 0 || $periodcontact > 0) {
		$sql.= ' , '.MAIN_DB_PREFIX.'element_contact as ec  , '.MAIN_DB_PREFIX.'c_type_contact as ctc';
		if ($perioduser > 0)
			$sql.= ' , '.MAIN_DB_PREFIX.'user as u ';
		if ($periodcontact > 0)
			$sql.= ' , '.MAIN_DB_PREFIX.'socpeople as sp ';
	}
	$sql.= ' WHERE date_format(ft.date, "%Y-%m-%d") >= "'.$datedeb.'"';
	$sql.= ' AND date_format(ft.date, "%Y-%m-%d") <= "'.$datefin.'"';
	$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  || $periodcontact > 0) {
		$sql.= ' AND f.rowid = ec.element_id AND ec.fk_c_type_contact = ctc.rowid';
		$sql.= ' AND ctc.element="fichinter"';
		if ($perioduser < 0) {
			// pas de filtre sur les user, juste sur les contacts
			$sql.= ' AND source="external" AND ec.fk_socpeople = sp.rowid';
		} elseif ($periodcontact < 0) {
			// pas de filtre sur les contacts, juste sur les user
			$sql.= ' AND source="internal" AND ec.fk_socpeople = u.rowid';
				// pour récupérer les subalterne quand on est le boss
			if ($conf->global->MYSCHEDULE_showsubordinateuser)
				$sql.= ' AND (u.rowid='.$perioduser.' OR u.fk_user='.$perioduser.')';
			else 
				$sql.= ' AND u.rowid='.$perioduser;
			} else {
			// on filtre sur les deux à la fois
			$sql.= ' AND (( source="external" AND ec.fk_socpeople = sp.rowid)';
			$sql.= ' OR (source="internal" AND ec.fk_socpeople = u.rowid';
			if ($conf->global->MYSCHEDULE_showsubordinateuser)
				$sql.= ' AND (u.rowid='.$perioduser.' OR u.fk_user='.$perioduser.')))';
			else
				$sql.= ' AND u.rowid='.$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';
	//$return['query']=$sql;
	$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);
		$contactstatic = new Contact($db);

		while ($j < $num) {
			$objp = $db->fetch_object($resql);
			$object->fetch($objp->fk_fichinter);
			$object->fetch_thirdparty();
			$tab = $object->liste_contact(-1, 'internal');
			$tabContact = $object->liste_contact(-1, 'external');

			$ret = $fichinterdet_schedule->fetch(0, 0, $objp->rowid);
			$headEvent = "<table border=0 style='background-color:#E0E0E0;'>";
			$headEvent.= "<tr><td><div class='classfortooltip' title='".$objp->descinter."'>";
			$headEvent.=img_picto('', 'object_intervention','',false, 0, 1 )." ".$objp->ref;
			$headEvent.="</div>";
			$headEvent.= "</td><td align=right >".$object->getLibStatut(2)."</td>";

			$title=$object->thirdparty->getNomUrl(3, "", 0, 1);
			//La ligne de description est toujours présente
			$title.="<br><div class='classfortooltip' title='".$objp->description."'>";
			$title.=dol_trunc($objp->description, 30)."</div>";

			// si il y a des utilisateurs d'affecté
			$userArray=array();
			if (count($tab) > 0) {
				$title.="<hr>";
				$totalPlanned= 0;
				$totalMade= 0;

				foreach($tab as $userinter) {
					$ret = $userstatic->fetch($userinter['id']);
					$title.=$userstatic->getnomUrl(1, "", 0, 1); //.' ('.$userinter['libelle'].')'."<br>";
					// on récupère ce qui a été saisie pour cet user/inter
					$sql = 'SELECT rowid, 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;
					$made = 0;
					if ($reusersql) {
						$objuser = $db->fetch_object($reusersql);
						$planned = ($objuser->duration_planned?$objuser->duration_planned:0);
						$made = ($objuser->duration_made!=0?$objuser->duration_made:0);
						$title.= " (".convertSecondToTime($planned, "allhourmin", 86400);
						if ($made)
							$title.= '/'.convertSecondToTime($made, "allhourmin", 86400);
						$title.= ')';
						$totalPlanned+= $planned;
						$totalMade+= $made;
					}
					$madehour = round($made/3600, 0, PHP_ROUND_HALF_DOWN);
					$plannedhour = round($planned/3600, 0, PHP_ROUND_HALF_DOWN);
	
					$userArray[$userinter['id']] = array(
						"name" => $userinter['nom'],
						"madehour" => $madehour,
						"mademin" => ($made - ($madehour*3600)) / 60,
						"plannedhour" => $plannedhour,
						"plannedmin" => ($planned - ($plannedhour*3600)) / 60,

					);
					$title.='<br>';
				}
			}

			// si il y a des utilisateurs d'affecté
			$contactArray=array();
			if (count($tabContact) > 0) {
				$totalContactPlanned= 0;
				$totalContactMade= 0;

				foreach($tabContact as $contactInter) {
					$ret = $contactstatic->fetch($contactInter['id']);
					$contactstatic->fetch_thirdparty();

					// on récupère ce qui a été saisie pour ce contact/inter
					$sql = 'SELECT rowid, duration_planned, duration_made';
					$sql.= ' FROM '.MAIN_DB_PREFIX.'fichinterdet_schedule';
					$sql.= ' WHERE fk_fichinterdet = '.$objp->rowid;
					$sql.= ' AND fk_socpeople = '.$contactInter['id'];
					$reusersql = $db->query($sql);
					$planned = 0;
					$made = 0;
					if ($reusersql) {
						$objuser = $db->fetch_object($reusersql);
						$planned = ($objuser->duration_planned?$objuser->duration_planned:0);
						$made = ($objuser->duration_made!=0?$objuser->duration_made:0);
						$totalContactPlanned+= $planned;
						$totalContactMade+= $made;
					}
					$madehour = round($made/3600, 0, PHP_ROUND_HALF_DOWN);
					$plannedhour = round($planned/3600, 0, PHP_ROUND_HALF_DOWN);
	
					$contactArray[$contactInter['id']] = array(
						"name" => $contactstatic->getnomUrl(1),
						"socname" => $contactstatic->thirdparty->getNomUrl(3, "", 0, 1),
						"madehour" => $madehour,
						"mademin" => ($made - ($madehour*3600)) / 60,
						"plannedhour" => $plannedhour,
						"plannedmin" => ($planned - ($plannedhour*3600)) / 60,
					);
				}
			}

			// il y a trois durées au niveau de la ligne d'intervention
			// la durée de la ligne d'intervention
			// la durée planifiée
			// la durée réalisée (made)
			$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) {
				// pourquoi tester le $ret????
				// si on a pas tout plannifié
				$bgcolor="#".$conf->global->MYSCHEDULE_colornotplanned;
				if(in_array('notplanned', $filterbystatut))
					$bshowelement=true;
			} elseif($totalPlanned >= $objp->duree && $made == 0){
				// tout plannifié mais rien fait
				$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;
				// pour gérer le bug de mise en forme
				$event['title'] = "";

				$event['start'] = $objp->date_intervention;

				$dateInter=$db->jdate($objp->date_intervention);
				$event['startyear'] = date("Y", $dateInter);
				$event['startmonth'] = date("m", $dateInter);
				$event['startday'] = date("d", $dateInter);
				$event['starthour'] = date("H", $dateInter);
				$event['startmin'] = date("i", $dateInter);

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

				$datedebevent =$db->jdate($objp->date_intervention);
				$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 >".$event['dureehour'].":".$event['dureemin']."</td></tr></table>";
				$event['htmltitle'] = $headEvent.$title;

				// $event['color'] = $bgcolor;
				$event['backgroundColor'] = $bgcolor;
				$event['borderColor'] = $textColor;
				$event['textColor'] = $textColor;
				$event['allDay'] = false;
				// infos additionnelle
				$event['ref'] = $object->ref;
				$event['duree_made'] = $object->duration_made;
				$event['fk_soc'] = $object->socid;
				$event['socname'] = $object->thirdparty->name;
				$event['fk_statut'] = $object->statut;
				$event['fi_description'] = $object->description;
				$event['note_private'] = ($object->note_private?$object->note_private:"");
				$event['note_public'] = ($object->note_public?$object->note_public:"");
				$event['fk_contract'] = $object->fk_contrat;
				$event['fk_fichinter'] = $objp->fk_fichinter;
				$event['classicediturl'] = dol_buildpath("fichinter", 1)."/card.php?id=".$objp->fk_fichinter."&lineid=".$objp->rowid;
				$event['description'] = ($objp->description?$objp->description:"");
				$event['selected'] = false;
				$event['userArray'] = $userArray;
				$event['contactArray'] = $contactArray;

				array_push($return, $event);
			}
			$j++;
		}
	}
	echo json_encode($return);
}
