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

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/financialreport/class/userinvoice.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/settlements/class/groupusers.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/financialreport/class/helper.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/settlements/class/helper.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/financialreport/class/commissionsettlements.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/financialreport/class/financialreportformhelper.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/commissionhandler.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/userloginnaplo.class.php';

require_once DOL_DOCUMENT_ROOT . '/custom/settlements/core/tpl/printPDF_szisz.php';


$helper = new HelperUserInvoice($db);
$settlementsHelper = new Helper($db);
$formHelper = new FinancialreportFormHelper($db);
$commmissionhandler = new CommissionHandler();
$userLoginNaploObj = new UserLoginNaplo($db);


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

$action = GETPOST('action', 'aZ09');
$cancel = GETPOST('cancel', 'int');
$id = GETPOST('id', 'int');
$idmenu = GETPOST('idmenu', 'int');
$daterange = GETPOST('daterange', 'alpha');
$datepicker = GETPOST('datepicker', 'alpha');
$interval = GETPOST('interval', 'alpha');
$array = GETPOST('array', 'array');
$options = GETPOST('options', 'array');
$commission = GETPOST('commission', 'array');
$commissions = GETPOST('commissions', 'alpha');
$optionsString = GETPOST('optionsString', 'alpha');
$groupEntity = GETPOST('groupEntity', 'int');
$printSummary = GETPOST('printSummary', 'int');

$confirmsettlements = GETPOST('confirmsettlements', 'int');
$confirmpersonalsettlements = GETPOST('confirmpersonalsettlements', 'alpha');

if ($daterange == '' && $datepicker == '') {
	$now = dol_now();
	$daterange = date("Y-m-d", $now) . ' - ' . date("Y-m-d", $now);
	$isSetDatepicker = true;
	$datesOfRange = $helper->createArray($daterange);
} else {
	$daterange = $daterange != '' ? $daterange : $datepicker;
	$datesOfRange = $helper->createArray($daterange);
	$isSetDatepicker = $datepicker != '';
}

$socid = GETPOST('socid', 'int');
if (isset($user->socid) && $user->socid > 0) {
	$action = '';
	$socid = $user->socid;
}

$form = new Form($db);
$formfile = new FormFile($db);
$entities = $settlementsHelper->getAllEntities();

$entitiesArray = [];
$selectedEntities = '';
foreach ($entities as $key => $value) {
	$val = GETPOST('entity_' . $key, 'int');
	$entitiesArray[$key] = $val;
	/* if ($val != '') {
		   $entitiesArrayIsEmpty = false;
	   } */
}

if (empty(array_filter($entitiesArray))) {
	$entitiesArray[1] = 1;
}

$selectedEntities = $helper->getEntities($entitiesArrayIsEmpty, $entities, $entitiesArray);

$groups = $helper->getAllGroupsFromGroupClass($selectedEntities);
$groupToolsAndGroupUsersArray = $helper->getGTAndGUArray();

if (empty($id)) {
	$keys = array_keys($groups);
	$id = $keys[0];
}

include DOL_DOCUMENT_ROOT . '/custom/financialreport/core/actions_addupdatedelete.inc.php';

foreach ($datesOfRange as $date) {
	$usersOfGroups = $helper->getUsersByIdWithDate($db, $id, $date);
	$usersOfGroupsCol2 = $helper->getUsersByIdWithDateCol2($db, $id, $date);
	$groupEntityId = $helper->getGroupEntityId($id);
}

$formconfirm = '';

if ($confirmsettlements == 1) {
	$string = implode("@", $commission);
	foreach ($options as $optionkey => $optionValue) {
		$array[] = $optionkey . '|' . $optionValue;
	}
	$optionsString = implode("@", $array);
	//print $string;
	//print $optionsString;
	//exit;
	$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $id . '&commissions=' . $string . '&optionsString=' . $optionsString . '&groupEntity=' . $groupEntityId, $langs->trans('GroupSettlementsConfirm'), $langs->trans('GroupSettlementsConfirmObject'), 'confirm_settlement', '', 0, 1);
}

if ($confirmpersonalsettlements) {
	$commissionArray = [];
	$successfully = false;

	$selectedUserArray = explode('_', $confirmpersonalsettlements);
	$result = explode('_', $commission[$selectedUserArray[1]]);
	$userObj = new User($db);
	$commissionArray['user_id'] = $result[0];
	$commissionArray['interval'] = $result[1];
	$commissionArray['HUF'] = $result[2];
	$commissionsForPost = implode('_', $commissionArray);
	$result = $userObj->fetch($result[0]);
	$userString = $userObj->firstname . ' ' . $userObj->lastname . ' (' . $userObj->login . ')';
	$successfully = true;

	if (!$successfully) {
		setEventMessages('Sikertelen művelet.', [], 'errors');
	} else {
		$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $id . '&commissions=' . $commissionsForPost, $langs->trans('PersonalSettlementsConfirm'), $langs->trans('PersonalSettlementsConfirmObject', $userString), 'confirm_personal_settlement', '', 0, 1);
	}
}

if (isset($excelexport)) {
	$helper->createExcelHotelReport($daterange, $id, $entity, $groups);
}

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

if (($confirmsettlements == 1) || $confirmpersonalsettlements) {
	print $formconfirm;
}

$url = $_SERVER["PHP_SELF"] . '?idmenu=' . $idmenu . '&mainmenu=financialreport&leftmenu=&id=' . $id;
$now3thSection = dol_now();
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="datepickerdata" value="' . $daterange . '">';
print '<input type="hidden" name="intervalchk" value="' . $interval . '">';
$nowTitle = date('Y.m.d', dol_now());
print load_fiche_titre($langs->trans("SettlementsArea") . '&nbsp; ' . $nowTitle, '', 'settlements.png@settlements');

print '<div style="width:100%; padding-bottom: 50px;">';
$columnWidth = 100 / count($entities);
foreach ($entities as $key => $value) {
	if (!$entitiesArrayIsEmpty) {
		$checked = $entitiesArray[$key] == $key ? 'checked' : '';
	} else {
		$checked = 'checked';
	}
	print '<div class="entitiesChk" style="float:left; width:' . $columnWidth . '%; text-align:center;"><input type="checkbox" class="entitycheckbox" id="entity_' . $key . '" name="entity_' . $key . '" value="' . $key . '" ' . $checked . '><label for="' . $key . '">' . $value . '</label></div>';
}
print '</div>';

# 1
print '<div class=""><div class="" style="width:33%;float:left;">';
print '<table style="width:100%;">';
print '<tr style="width: 100%; height: 45px; 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 class="submitFormLink" data-value="' . $key . '" style="height:30px; ' . $coloredLine . '; cursor:pointer;">
		<td>
		<div>
			<span class="fa fa-group pictofixedwidth"></span> ' . $val . '
			
		</div>
		<div class="groupColumn2ndLine" style="float:left;">
			' . $entities[$helper->getGroupEntityId($key)] . '
		</div>
		</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: 45px; text-align: center; background-color: lightgrey;"><td colspan="2"><a href="/custom/settlements/settlementtoolssettingsindex.php?idmenu=1594&mainmenu=settlements&leftmenu=&id=' . $groupToolsAndGroupUsersArray[$id] . '&nopackageuser=1">' . $langs->trans("usersofgroup", $helper->getGroupRefByID($id)) . '</a></td></tr>';
print '<tr style="width: 100%;" colspan="2"><td>' . $langs->trans('Name') . '</td></tr>';
if (count($usersOfGroupsCol2) > 0) {
	foreach ($usersOfGroupsCol2 as $user) {
		print '<tr style="height:30px;">
			<td><span class="fa fa-user pictofixedwidth"></span> <a href="/user/card.php?id=' . $user['user_id'] . '&save_lastsearch_values=1">' . $user['lastname'] . ' ' . $user['firstname'] . '</a>  (' . $user['login'] . ')</td><td></td>
		</tr>';
	}
} else {
	print '<tr style="height: 60px; text-align: center; color:red;"><td>' . $langs->trans('nouser') . '</td></tr>';
}
print '</table>';
print '</div>';

# 3
$colspan = 2;
$payed = '<span class="fa fa-check pictofixedwidth" style="color: green;"></span>';
print '<div class="" style="width:33%;float:left;">';
print '<table style="width:100%;">';
print '<tr style="width: 100%; height: 45px; text-align: center; background-color: lightgrey;"><td colspan="' . $colspan . '">' . $langs->trans("settlements") . '</td></tr>';
print '<tr style="width: 100%; height: 20px; text-align: right;"><td colspan="' . $colspan . '">' . $langs->trans('selectAll') . '<input type="checkbox" id="allOptions" name="AllOptions" value="1" onclick="checkAll()"></td></tr>';
$allUsersCommissionsAmountForGroupsettlementButton = 0;
$totalCommissionHUFEUR = 0;

foreach ($datesOfRange as $date) {
	if (count($usersOfGroups) > 0) {
		$k = 0;
		$userOption = 0;
		foreach ($usersOfGroups as $userOfGroups) {

			$user_id = $userOfGroups['user_id'];
			$from = $userOfGroups['date_creation'];

			$logoutDate = $helper->checklogoutRecordInUserNaplo($user_id, $from, $id);
			$to = $logoutDate != '' ? $logoutDate : date('Y-m-d H:i:s', $now3thSection);
			$iNeedThisIdForRefreshDate = $logoutDate == '' ? 'class="refreshThis"' : '';
			$checked = in_array($user_id, $options) ? 'checked' : '';
			$dateInterval = $from;
			$dateInterval2 = $from . ' - ' . $to;
			$totalCommission = $commmissionhandler->getTotalCommission($user_id, $from, $to);
			$totalCommissionHUFEUR += $totalCommission;
			$disabledButton = $totalCommission == 0 ? 'disabled' : '';
			$hiddenCommissionDataValue = $user_id . '_' . $dateInterval;

			$last5commissionSql = "SELECT ui.date_creation, ui.amount FROM llx_financialreport_userinvoice as ui WHERE ui.user_id = {$user_id} ORDER BY ui.rowid DESC LIMIT 2";
			$last5commissionResult = $db->query($last5commissionSql);
			$last5CommissionArray = [];
			if ($db->num_rows($last5commissionResult) > 0){
				while($l5row = $db->fetch_object($last5commissionResult)){
					$last5CommissionArray[] = $l5row;
				}
			}

				print '<input type="hidden" name="commission[]" value="' . $hiddenCommissionDataValue . '">';
			print '<tr><td colspan=' . $colspan . ' style="text-align: center;">';
			print '<div class="box">
				<div  style="height: 10%;text-align: right; margin-right: 20px; margin-top:10px;">' . $langs->trans('asGroup') . '<input type="checkbox" class="options" id="option_' . $user_id . '" name="options[' . $userOption . ']" value="' . $user_id . '" ' . $checked . ' onclick="checkOptions()"></div>
				<div style="margin-top: 30px;">
				<div style="height: 10%; color: rgb(163,0,51); font-size: 30px; margin-left: 40px; float: left;">' . $userOfGroups['lastname'] . ' ' . $userOfGroups['firstname'] . '</div>
				<div style="height: 10%; color: rgb(163,0,51); font-size: 30px; text-align: right; padding-right: 40px;">' . $helper->correctNumber($totalCommission) . '<sup style="font-size: 10px;"> HUF</sup></div>
				</div>
				<div style="clear:both; height: 10%; color: rgb(163,0,51); margin-left: 40px; float: left;"> (' . $userOfGroups['login'] . ')</div>
				<div style="height: 10%; color: rgb(10, 20, 100); text-align: right; padding-right: 40px;">' . $langs->trans('Commission') . '</div>
				<div style="color:green;">' . $langs->trans('dailyMinimumCommission') . ': ' . $helper->correctNumber($commmissionhandler->getDailyMinimumCommission()) . ' HUF</div>
				<div style="text-align: center;"><table style="width:100%;"><tr style=" color:rgb(163,0,51);"><td style="text-align:right;">' . $from . '</td><td style="width:10px;"> - </td><td style="text-align:left;" ' . $iNeedThisIdForRefreshDate . '>' . $to . '</td></tr></table></div>
				
				<div style="text-align: center;"><table style="width:100%;">';
				print '<tr><td colspan=2 style="text-align: center;">Last commissions</td></tr>';
				foreach($last5CommissionArray as $commissionRecord){
					print '<tr><td>' . $commissionRecord->date_creation . '</td><td style="text-align: left;">' . $commissionRecord->amount . ' HUF</td></tr>';
				}
			print '</table></div>
				<div class="container content" style="clear: both; height: 10%"><button id="confirmpersonalsettlements" name="confirmpersonalsettlements" type="submit" value="' . $user_id . '_' . $k . '" ' . $disabledButton . '>' . $langs->trans("PersonalSettlement") . '</button></div>
				</div>';
			print '</div>';
			print '</td></tr>';
			$allUsersCommissionsAmountForGroupsettlementButton += $totalCommission;
			$currentUser = $user_id;
			$k++;
			$userOption++;
		}
	}
	if ($allUsersCommissionsAmountForGroupsettlementButton != 0) {
		$displayNone = empty($options) ? 'none;' : 'block';
		print '<tr style="text-align:center;"><td colspan="3"><button id="confirmsettlements" name="confirmsettlements" style="width:100%; height:30px; margin-bottom: 40px; display:' . $displayNone . ';" type="submit" value="1">' . $langs->trans("GroupSettlement") . '</button></td></tr>';
	}

}
print '</div></div>';
print '</form>' . "\n";
print '</td></tr>';
$formHelper->summary($id, $totalCommissionHUFEUR);
// End of page
llxFooter();
$db->close();
?>
<style>
	.groupColumn2ndLine {
		color: grey !important;
	}

	button {
		width: 200px;
		height: 30px;
		background-color: rgb(163, 0, 51);
		color: white;
		border-radius: 20px;
		border: none;
		cursor: pointer;
	}

	button:disabled {
		background-color: #cccccc;
		color: #666666;
		cursor: not-allowed;
	}

	.container {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.content {
		margin-top: auto;
	}

	.box {
		height: 400px;
		width: 100%;
		background-image: url('img/rectangle-7.png');
		background-repeat: no-repeat;
		background-position: center;
	}

	.summary {
		clear: both;
		width: 93%;
		height: 20px;
		display: block;
		background-color: rgb(163, 0, 51);
		color: white;
		border-radius: 10px 10px 0 0;
	}
</style>

<script>
	$(document).ready(function () {
		var timer = 1000;
		var frissites = setInterval(function () {
			var currentDate = new Date(Date.now());
			var formattedDate = currentDate.getFullYear() + '-' +
				('0' + (currentDate.getMonth() + 1)).slice(-2) + '-' +
				('0' + currentDate.getDate()).slice(-2) + ' ' +
				('0' + currentDate.getHours()).slice(-2) + ':' +
				('0' + currentDate.getMinutes()).slice(-2) + ':' +
				('0' + currentDate.getSeconds()).slice(-2);
			$('.refreshThis').html(formattedDate);
		}, timer);

		$('.entitiesChk').change(function () {
			$('#statementlists').submit();
		});
		var elements = document.getElementsByClassName('submitFormLink');
		for (var i = 0; i < elements.length; i++) {
			elements[i].addEventListener('click', function (event) {
				event.preventDefault();
				var form = document.getElementById('statementlists');
				var actionValue = form.getAttribute('action');
				var clickedElementValue = this.getAttribute('data-value');
				lastIndex = actionValue.lastIndexOf('&');
				var trimmedQueryString = actionValue.substring(0, lastIndex);
				form.action = trimmedQueryString + '&id=' + clickedElementValue;
				document.getElementById('statementlists').submit();
			});
		}
	});

	function giveMeUserData(id) {
		var divDisplay = $('#commissiondata_' + id).css("display"); // Az "myDiv" div display tulajdonságának lekérése
		if (divDisplay === "none") {
			$('#commissiondata_' + id).slideDown();
			$('#commissiondata_' + id).css('display', 'block');
			$('#span_' + id).removeClass('fa-angle-down').addClass('fa-angle-up');
		} else {
			$('#commissiondata_' + id).slideUp();
			$('#span_' + id).removeClass('fa-angle-up').addClass('fa-angle-down');
			//$('#commissiondata_' + id).css('display', 'none');
		}
	}

	function checkAll() {
		var checkbox = document.getElementById("allOptions");
		var optionsCheckboxes = document.querySelectorAll(".options");
		if (checkbox.checked) {
			$("#confirmsettlements").css('display', 'block');
			for (var i = 0; i < optionsCheckboxes.length; i++) {
				optionsCheckboxes[i].checked = true;
			}
		} else {
			$("#confirmsettlements").css('display', 'none');
			for (var i = 0; i < optionsCheckboxes.length; i++) {
				optionsCheckboxes[i].checked = false;
			}
		}
	}

	function checkOptions() {
		var optionsCheckboxes = document.querySelectorAll(".options");
		var vanBejelolt = false;

		for (var i = 0; i < optionsCheckboxes.length; i++) {
			if (optionsCheckboxes[i].checked) {
				vanBejelolt = true;
				break;
			}
		}

		if (vanBejelolt) {
			$("#confirmsettlements").css('display', 'block');
		} else {
			$("#confirmsettlements").css('display', 'none');
			var checkbox = document.getElementById("allOptions");
			checkbox.checked = false;
		}
	}


</script>