<?php
/* Copyright (C) 2001-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
 * Copyright (C) 2004-2015 Laurent Destailleur  <eldy@users.sourceforge.net>
 * Copyright (C) 2005-2012 Regis Houssin        <regis.houssin@inodbox.com>
 * Copyright (C) 2015      Jean-François Ferry	<jfefe@aternatik.fr>
 *
 * 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 <https://www.gnu.org/licenses/>.
 */

/**
 *	\file       settlements/settlementsindex.php
 *	\ingroup    settlements
 *	\brief      Home page of settlements top menu
 */


// Load Dolibarr environment

$res = 0;
// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) {
	$res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"] . "/main.inc.php";
}
// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME'];
$tmp2 = realpath(__FILE__);
$i = strlen($tmp) - 1;
$j = strlen($tmp2) - 1;
while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) {
	$i--;
	$j--;
}
if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1)) . "/main.inc.php")) {
	$res = @include substr($tmp, 0, ($i + 1)) . "/main.inc.php";
}
if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1))) . "/main.inc.php")) {
	$res = @include dirname(substr($tmp, 0, ($i + 1))) . "/main.inc.php";
}
// Try main.inc.php using relative path
if (!$res && file_exists("../main.inc.php")) {
	$res = @include "../main.inc.php";
}
if (!$res && file_exists("../../main.inc.php")) {
	$res = @include "../../main.inc.php";
}
if (!$res && file_exists("../../../main.inc.php")) {
	$res = @include "../../../main.inc.php";
}
if (!$res) {
	die("Include of main fails");
}

use Luracast\Restler\RestException;

require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php';
require_once DOL_DOCUMENT_ROOT . '/user/class/usergroup.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/settlements/class/groupusers.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/settlements/class/helper.class.php';

$helper = new Helper($db);

function getAllUsers($db)
{
	$sql = "SELECT * FROM llx_user as u WHERE rowid NOT IN (SELECT fk_user FROM llx_settlements_groupusers) ORDER BY u.lastname";
	$data = $db->query($sql);
	if (!$data) {
		dol_syslog("No group found.", LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
	}
	while ($row = pg_fetch_assoc($data)) {
		$allUsers[] = $row;
	}
	return $allUsers;
}

// Load translation files required by the page
$langs->loadLangs(array("settlements@settlements"));

$action = GETPOST('action', 'aZ09');
$id = GETPOST('id', 'int');
$idmenu = GETPOST('idmenu', 'int');
$daterange = GETPOST('daterange', 'alpha');
$datepicker = GETPOST('datepicker', 'alpha');
$interval = GETPOST('interval', 'alpha');



if($interval == 'on'){
	$_SESSION['interval'] = $interval;
}

// Security check
// if (! $user->rights->settlements->myobject->read) {
// 	accessforbidden();
// }
$socid = GETPOST('socid', 'int');
if (isset($user->socid) && $user->socid > 0) {
	$action = '';
	$socid = $user->socid;
}

$form = new Form($db);
$formfile = new FormFile($db);
$groups = $helper->getAllGroupsFromGroupClass($db);

if (empty($id)) {
	$keys = array_keys($groups);
	$id = $keys[0];
}else{
	$daterange = isset($_SESSION['daterange']) ? $_SESSION['daterange'] : '';
	$datepicker = isset($_SESSION['datepicker']) ? $_SESSION['datepicker'] : '';
}


$bigRedDiv = '';
$sumsHUFArray = [];
$sumsEURArray = [];
$dateforHiddenField = $datepicker != '' ? $datepicker : $daterange;

if($datepicker != ''){
	$_SESSION['datepicker'] = $datepicker;
	unset($_SESSION['daterange']);
	//unset($_SESSION['interval']);
	$datesOfRange = $helper->createArray($datepicker);
	foreach ($datesOfRange as $date) {
		$usersOfGroups = $helper->getUsersByIdWithDate($db, $id, $date);
		$deletedUsersArray = $helper->getDeletedUsers($db, $id, $date);
		if (!empty($usersOfGroups)) {
			$sumsHUFArray[$date] = $helper->getSum($db, 'HUF', $id, $usersOfGroups, $date);
			$sumsEURArray[$date] = $helper->getSum($db, 'EUR', $id, $usersOfGroups, $date);
		}
	}	$bigRedDiv = '<div style="width:100%; color: white; font-weight:bold ;background-color: #fa8072; height:30px; text-align: center; padding-top: 15px; border-radius: 10px;">' . $langs->trans('onedayfilter') . ' ' . $datepicker . '<br></div>';
}

if($daterange != ''){
	$_SESSION['daterange'] = $daterange;
	unset($_SESSION['datepicker']);
	$datesOfRange = $helper->createArray($daterange);
	foreach ($datesOfRange as $date) {
		$usersOfGroups = $helper->getUsersByIdWithDate($db, $id, $date);
		$deletedUsersArray = $helper->getDeletedUsers($db, $id, $date);
		if (!empty($usersOfGroups)) {
			$sumsHUFArray[$date] = $helper->getSum($db, 'HUF', $id, $usersOfGroups, $date);
			$sumsEURArray[$date] = $helper->getSum($db, 'EUR', $id, $usersOfGroups, $date);
		}
	}
	$bigRedDiv = '<div style="width:100%; color: white; font-weight:bold ;background-color: #fa8072; height:30px; text-align: center; padding-top: 15px; border-radius: 10px;">' . $langs->trans('moredayfilter') . ' ' . $daterange . '<br></div>';
}else{
	unset($_SESSION['interval']);
}

llxHeader('', $title, $help_url, '', 0, 0, $morejs, $morecss, '', 'classforhorizontalscrolloftabs');

//print_r($_REQUEST);

$url = $_SERVER["PHP_SELF"] . '?idmenu=' . $idmenu . '&mainmenu=settlements&leftmenu=';
if (isset($massaction) || isset($massactionadd)) {
	$url .= "&id={$id}";
}
print '<form method="POST" id="statementlists" action="' . $url . '">' . "\n";
print '<input type="hidden" name="token" value="' . newToken() . '">';
print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
print '<input type="hidden" name="action" value="list">';
print '<input type="hidden" name="sortfield" value="' . $sortfield . '">';
print '<input type="hidden" name="sortorder" value="' . $sortorder . '">';
print '<input type="hidden" name="page" value="' . $page . '">';
print '<input type="hidden" name="contextpage" value="' . $contextpage . '">';
//print '<input type="hidden" name="datepickerdata" value="' . $daterange . '">';
print '<input type="hidden" name="datepickerdata" value="' . $dateforHiddenField . '">';
//print '<input type="hidden" name="intervalchk" value="' . $interval . '">';
print '<input type="hidden" name="intervalchk" value="' . $_SESSION['interval'] . '">';
print load_fiche_titre($langs->trans("SettlementsRangeArea"), '', 'settlements.png@settlements');

print $bigRedDiv;

print '<input id="chkbdatepicker" class="flat checkforselect" type="checkbox" name="interval" onchange="checkStatus()">' . $langs->trans('intervall') . '';
print '<div id="datepickerdiv" style="display:block;">';
print '<input type="text" name="datepicker" id="datepicker" value="" />';
print '<button type="submit">' . $langs->trans('select') . '</button>';
print '</div>';
print '<div id="daterangediv" style="display:none;">';
print '<input type="text" name="daterange" id="daterange" value="" />';
print '<button type="submit">' . $langs->trans('select') . '</button>';
print '</div>';

if ($daterange != '' ||  $datepicker != '') {


	# 1
	print '<div class=""><div class="" style="width:33%;float:left;">';
	print '<table style="width:100%;">';
	print '<tr style="width: 100%; height: 40px; text-align: center; background-color: lightgrey;"><td>' . $langs->trans("nameofgroup") . '</td></tr>';
	foreach ($groups as $key => $val) {
		$coloredLine = $id == $key ? ' background-color: #b0c4de' : '';
		print '<tr style="height:30px;' . $coloredLine . '"><td><a href="' . $_SERVER['PHP_SELF'] . '?id=' . $key . '"><span class="fa fa-group pictofixedwidth"></span> ' . $val . '</a></td></tr>';
	}
	print '</table>';
	print '</div>';

	# 2
	print '<div class="" style="width:33%;float:left;">';
	print '<table style="width:100%;">';
	print '<tr style="width: 100%; height: 40px; text-align: center; background-color: lightgrey;"><td colspan="2">'.$langs->trans("usersofgroup",$group[$id]).'</td></tr>';

	if (!empty($usersOfGroups)) {
		foreach ($usersOfGroups as $user) {
			print '<tr style="height:30px;">
			<td><span class="fa fa-user pictofixedwidth"></span> ' . $user['lastname'] . ' ' . $user['firstname'] . '  (' . $user['login'] . ') <font color="red">' . $deletedUsersArray[$user['user_id']] . '</font></td>
		</tr>';
		}
	} else {
		print '<tr style="height: 60px; text-align: center; color:red;"><td>' . $langs->trans('nouser') . '</td></tr>';
	}
	print '</table>';
	print '</div>';

	# 3
	print '<div class="" style="width:33%;float:left;">';
	print '<table style="width:100%;">';
	print '<tr style="width: 100%; height: 40px; text-align: center; background-color: lightgrey;"><td colspan="3">' . $langs->trans("settlements") . '</td></tr>';
	foreach ($datesOfRange as $date) {
		print '<tr style="width:100%; height:30px;"><td class="center" colspan="3"><div style="background-color:rgb(10, 20, 100); height:30px; border-radius: 10px 10px 0 0; padding-top: 10px; color:white;">' . $date . '</div></td></tr>';
		print '<tr style="height: 70px;">';
		/* print '
					<td>
						<div style="background-color:#98FB98; height:70px; padding:5px;">
							<div>Alap</div><div style="text-align:center; font-weight:bold; font-size:40px;">' . $helper->correctNumber($sumsHUFArray[$date][0]['total_ht']) . ' </div>
						</div>
					</td>'; */
		/* print '
					<td>
						<div style="background-color:#98FB98; height:70px; padding:5px;">
							<div>Adó</div><div style="text-align:center; font-weight:bold; font-size:40px;">' .  $helper->correctNumber($sumsHUFArray[$date][0]['total_tva']) . ' </div>
						</div>
					</td>'; */
		print '
	<td colspan="3">
		<div style="background-color:#98FB98; height:70px; padding:5px;">
			<div style="text-align:center; font-weight:bold; font-size:40px;">' . $helper->correctNumber($sumsHUFArray[$date][0]['total_ttc']) . ' <sup style="font-size: 10px;"> HUF</sup></div>
			<!--<div>Teljes</div><div style="text-align:center; font-weight:bold; font-size:40px;">' . $helper->correctNumber($sumsHUFArray[$date][0]['total_ttc']) . ' </div>-->
		</div>
	</td>';
		print '</tr>';
		print '<tr style="height: 70px;">';
		/* print '
					<td>
						<div style="background-color:#98FB98; height:70px; border-radius: 0 0 0 10px; padding:5px;">
							<div>Alap</div><div style="text-align:center; font-weight:bold; font-size:40px;">' . $helper->correctNumber($sumsEURArray[$date][0]['total_ht']) . ' <sup style="font-size: 10px;"> EUR</sup></div>
						</div>
					</td>';
					print '
					<td>
						<div style="background-color:#98FB98; height:70px; padding:5px;">
							<div>Adó</div><div style="text-align:center; font-weight:bold; font-size:40px;">' . $helper->correctNumber($sumsEURArray[$date][0]['total_tva']) . ' <sup style="font-size: 10px;"> EUR</sup></div>
						</div>
					</td>'; */
		print '
	<td  colspan="3">
		<div style="background-color:#98FB98; height:70px; border-radius: 0 0 10px 10px; padding:5px;">
			<div style="text-align:center; font-weight:bold; font-size:40px;">' . $helper->correctNumber($sumsEURArray[$date][0]['total_ttc']) . ' <sup style="font-size: 10px;"> EUR</sup></div>
			<!--<div>Teljes</div><div style="text-align:center; font-weight:bold; font-size:40px;">' . $helper->correctNumber($sumsEURArray[$date][0]['total_ttc']) . ' <sup style="font-size: 10px;"> EUR</sup></div>-->
		</div>
	</td>';
		print '</tr>';
	}
	print '</table>';
}else{
	print '<div style="color: red;">' . $langs->trans('selectdate') . '</div>';
}
print '</div></div>';
print '</form>' . "\n";

// End of page
llxFooter();
$db->close();
?>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css">
<script src="https://cdn.jsdelivr.net/npm/moment"></script>
<script src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>

<script>
	var datepickerdata = document.querySelector('input[type="hidden"][name="datepickerdata"]');
	var interval = document.querySelector('input[type="hidden"][name="intervalchk"]');
	var checkbox = document.querySelector('input[type="checkbox"][name="interval"]');
	var datepickerinput = document.querySelector('input[type="text"][name="datepicker"]');
	var daterangeinput = document.querySelector('input[type="text"][name="daterange"]');
	if (interval.value == 'on') {
		checkbox.checked = true;
		checkStatus();
		daterangeinput.value = datepickerdata.value;
	}
	datepickerinput.value = datepickerdata.value;

	function checkStatus() {
		var checkbox = document.getElementById("chkbdatepicker");
		var isChecked = checkbox.checked;
		if (isChecked) {
			var datepickerdiv = document.getElementById("datepickerdiv");
			var daterangediv = document.getElementById("daterangediv");
			datepickerdiv.style.display = "none";
			daterangediv.style.display = "block";
			datepickerinput.value = '';
			daterangeinput.value = '';
		} else {
			datepickerinput.value = '';
			daterangeinput.value = '';
			var datepickerdiv = document.getElementById("datepickerdiv");
			var daterangediv = document.getElementById("daterangediv");
			datepickerdiv.style.display = "block";
			daterangediv.style.display = "none";
		}
	}
	var datepicker =
		$(function () {
			$('#daterange').daterangepicker({
				"showDropdowns": true,
				"autoUpdateInput": false,
				locale: {
					format: 'YYYY-MM-DD',
					cancelLabel: 'Mégse',
					applyLabel: 'OK',
					moLabel: 'OK',
					firstDay: 1,
					"daysOfWeek": [
						"Vas",
						"Hé",
						"Ke",
						"Sze",
						"Csü",
						"Pé",
						"Szo"
					],
					"monthNames": [
						"Január",
						"Február",
						"Március",
						"Április",
						"Május",
						"Június",
						"Július",
						"Augsztus",
						"Szeptember",
						"Október",
						"November",
						"December"
					],

				},
			});
		});
	$(function () {
		$('#datepicker').daterangepicker({
			"singleDatePicker": true,
			"showDropdowns": true,
			"autoUpdateInput": false,
			locale: {
				format: 'YYYY-MM-DD',
				cancelLabel: 'Mégse',
				applyLabel: 'OK',
				moLabel: 'OK',
				firstDay: 1,
				"daysOfWeek": [
					"Vas",
					"Hé",
					"Ke",
					"Sze",
					"Csü",
					"Pé",
					"Szo"
				],
				"monthNames": [
					"Január",
					"Február",
					"Március",
					"Április",
					"Május",
					"Június",
					"Július",
					"Augsztus",
					"Szeptember",
					"Október",
					"November",
					"December"
				],

			},
		});
	});
	$('input[name="datepicker"]').on('apply.daterangepicker', function (ev, picker) {
		$(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
	});

	$('input[name="datepicker"]').on('cancel.daterangepicker', function (ev, picker) {
		$(this).val('');
	});
	$('input[name="daterange"]').on('apply.daterangepicker', function (ev, picker) {
		$(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
	});

	$('input[name="daterange"]').on('cancel.daterangepicker', function (ev, picker) {
		$(this).val('');
	});
</script>