<?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';

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";
}

//dol_include_once('/management/class/managementfichinter.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');
$confirm= GETPOST('confirm', 'alpha');
$lineid	= GETPOST('lineid', 'int');

// Nombre de ligne pour choix de produit/service predefinis
$NBLINES=4;

// 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 
			$object->fetch_thirdparty();
	}
} else {
	header('Location: '.DOL_URL_ROOT.'/fichinter/list.php');
	exit;
}



/*
 * View
 */

llxHeader(); 

$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');

$formconfirm='';


// Confirmation delete product/service line
if ($action == 'ask_deleteline')
	$formconfirm=$form->formconfirm(
					$_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, 
					$langs->trans('DeleteProductLine'), 
					$langs->trans('ConfirmDeleteProductLine'), 
					'confirm_deleteline', '', 0, 1
	);


if (! $formconfirm) {
	$parameters=array('lineid'=>$lineid);
	// Note that $action and $object may have been modified by hook
	$reshook=$hookmanager->executeHooks('formConfirm', $parameters, $object, $action);
	if (empty($reshook))
		$formconfirm.=$hookmanager->resPrint;
	elseif ($reshook > 0)
		$formconfirm=$hookmanager->resPrint;
}
// Print form confirm
print $formconfirm;

$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);
print '</div>';
print '<div class="fichecenter">';
dol_fiche_end();

print load_fiche_titre($title, "", 'myschedule@myschedule');

//print '<div class="underbanner clearboth"></div>';
print '<table class="noborder" width="100%">';
// r�cup�ration des jours d'interventions dans les lignes
// Intervention lines
$sqldate = 'SELECT Distinct ft.date as date_intervention';
$sqldate.= ' FROM '.MAIN_DB_PREFIX.'fichinterdet as ft';
$sqldate.= ' WHERE ft.fk_fichinter = '.$object->id;
$sqldate.= ' ORDER BY ft.date ASC';

$resqldate = $db->query($sqldate);
if ($resqldate) {
	$num = $db->num_rows($resqldate);
	$i = 0;
	print '<tr class="title">';
	print '<th >'.$langs->trans("InterventionDetail").'</th>';
	print '<th >'.$langs->trans("Duration").'</th>';

	if ($num) {
		$var=true;
		while ($i < $num) {
			$objdate = $db->fetch_object($resqldate);
			print '<th>';
			print dol_print_date($db->jdate($objdate->date_intervention), 'day');
			print '</th>';
			$i++;
		}
	}
	print '</tr>';
}

// 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.= ' ORDER BY ft.rang ASC, ft.date ASC, ft.rowid';

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

	if ($num) {
		$var=true;
		while ($i < $num) {
			$objp = $db->fetch_object($resql);
			print '<tr class="oddeven">';
			print '<td width="200px">';
			print '<a name="'.$objp->rowid.'"></a>'; // ancre pour retourner sur la ligne
			print dol_htmlentitiesbr($objp->description);

			// Date
//			print '<td align="center" width="150">'.(empty($conf->global->FICHINTER_DATE_WITHOUT_HOUR)?dol_print_date($db->jdate($objp->date_intervention),'dayhour'):dol_print_date($db->jdate($objp->date_intervention),'day')).'</td>';

			// Duration
			print '<td align="right" width="50px">';
			print convertSecondToTime($objp->duree);
			print '</td>';
			// on se positionne sur le bon jour
			$resqldate = $db->query($sqldate);
			$numdt = $db->num_rows($resqldate);
			$j = 0;
			while ($j< $numdt) {
				$objdate = $db->fetch_object($resqldate);
				if ($objdate->date_intervention == $objp->date_intervention) {
					print '<td align=center>';
					print '<table>';
					print '<tr>';
					print '<th>'.$langs->trans("User").'</th>';
					print '<th>'.$langs->trans("TimePlanned").'</th>';
					print '<th>'.$langs->trans("TimeMade").'</th>';

					print '</tr>';
					$tab = $object->liste_contact(-1,'internal');
					$userstatic=new User($db);
					
					foreach($tab as $userinter) {
						print "<tr><td>";
						if (count($tab)!=1)
							print "<a href=#>".img_picto($langs->trans("AffectTime"), "rightarrow")."</a>&nbsp;";						
						$ret = $userstatic->fetch($userinter['id']);
						print $userstatic->getnomUrl(1); //.' ('.$userinter['libelle'].')'."<br>";
						print '</td><td>';
						$defaut="";
						// si un seul user on lui affecte l'heure par d�faut
						if (count($tab)==1)
							$defaut = $objp->duree/3600;
						print "<input type=text size=1 value='".$defaut."'>";
						print '</td><td>';
						print "<input type=text size=1>";
						print '</td></tr>';
					}
					print '</table>';
					print '</td>';
					
				} else
					print '<td></td>';
				$j++;
			}

			print '</tr>';
			
			$i++;
		}
	}
}

print '</table>';


/*
 * Boutons Actions
 */
print '<div class="tabsAction">';
// 0 = draft
// 1 = Valided
// 2 = Billed
// 3 = Close
// 4 = Partial Close

if ($object->statut < 2 ) {
	//$objectelement =$object->element;
	if ($user->rights->facture->creer) {
		if ((int) DOL_VERSION < 6)
			$loc = DOL_URL_ROOT.'/compta/facture.php';
		else
			$loc = DOL_URL_ROOT.'/compta/facture/card.php';
		print '<a class="butAction" href="'.$loc.'?action=create';
		print '&origin='.$objectelement.'&originid='.$object->id.'&socid='.$object->socid.'">';
	} else
		print '<a class="butActionRefused" href="#" title="'.$langs->trans("NotEnoughPermissions").'">';
	print $langs->trans("Save").'</a>';
}

print '</div>';
print '<br>';

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