<?php
$debugMode = false;
/* 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/usernaplo.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/settlements/class/helper.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/settlements/class/grouptoolstools.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/settlements/class/toolnaplo.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/settlements/class/package.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/settlements/class/grouptoolspackages.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/settlements/core/tpl/printPDF_szisz.php';

// Include the main TCPDF library (search for installation path).
require_once DOL_DOCUMENT_ROOT . '/includes/tecnickcom/tcpdf/examples/tcpdf_include.php';
require_once DOL_DOCUMENT_ROOT . '/includes/tecnickcom/tcpdf/tcpdf.php';


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

$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists)
$massactionadd = GETPOST('massactionadd', 'alpha'); // The bulk action (combo box choice into lists)
$action = GETPOST('action', 'aZ09');
$cancel = GETPOST('cancel', 'int');
$id = GETPOST('id', 'int');
$idmenu = GETPOST('idmenu', 'int');
$toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list
$toselectnewpackage = GETPOST('toselectnewpackage', 'array'); // Array of ids of elements selected into a list
$search_package_name = GETPOST('search_package_name', 'alpha');
$search_group_title = GETPOST('search_group_title', 'alpha');
$confirmbutton = GETPOST('confirmbutton', 'int');
$printbutton = GETPOST('printbutton', 'alpha');
$confirm = GETPOST('confirm', 'alpha');
$confirmtools = GETPOST('confirmtools', 'alpha');
$delete = GETPOST('delete', 'int');
$toolclearall = GETPOST('toolclearall', 'int');
$confirmUserAndPackageAssignment = GETPOST('confirmUserAndPackageAssignment', 'int');
$packageuser = GETPOST('packageuser', 'array');
$nopackageuser = GETPOST('nopackageuser', 'int');
$confirmUsersButton = GETPOST('confirmUsersButton', 'int');
$groupuser_id = GETPOST('groupuser_id', 'int');

if ($nopackageuser == 1) {
	$packageuser = [];
}


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

$max = 5;
$now = dol_now();


$form = new Form($db);
$formfile = new FormFile($db);
$toolNaplo = new ToolNaplo($db);
$helper = new Helper($db);
$entities = $helper->getAllEntities();

$entitiesArray = [];
$selectedEntities = '';
//$entitiesArrayIsEmpty = true;

# get all emtity_ variable
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->getGroupsFromGroupToolsClass($db, $selectedEntities);
$groups = $helper->getFilteredpackageGroups($search_group_title, $selectedEntities);

if (empty($id) || $id == 0) {
	foreach ($groups as $group) {
		$keys[] = $group['rowid'];
	}
	unset($_SESSION['package_array']);
	$id = $keys[0];
}

if ($delete == 1) {
	unset($_SESSION['package_array']);
}

#
# Confirm 
#

#
# Massactions
#

if ($confirm == 'delete') {
	$grouptoolsPackages = new GroupToolsPackages($db);
	$PackageNaplo = new PackageNaplo($db);
	foreach ($toselect as $packageid) {
		$moredata = explode('_', $packageid);
		$grouptoolsPackages->deleteLine($user, $moredata[0]);
		$data = $helper->createDataToolArray($id, 0, $moredata[1]);
		$PackageNaplo->createNaplo($user, $data);
		dol_syslog("A {$moredata[1]} szamu csomag torlesre kerult.", LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
	}
	$url = $_SERVER["PHP_SELF"] . '?id=' . $id;
	header("Location: " . $url);
	$confirm = '';
}

if ($massactionadd == 'add') {
	if ($helper->checkEquality($id)) {
		setEventMessage($langs->trans("equalNumbers"), 'warnings');
		unset($_SESSION['package_array']);
		$hideConfirmBoolean = true;
	} else {
		if ((!isset($toselectnewpackage) || empty($toselectnewpackage)) && isset($_SESSION['package_array'])) {
			$toselectnewpackage = array_filter($_SESSION['package_array'], function ($elem) {
				return !empty($elem);
			});
		}
		if (!empty($toselectnewpackage)) {
			$userCounter = $helper->getNumberOfUsers();
			if ((count($toselectnewpackage) > $userCounter[$id][0]) || $helper->checkSumAndUsers($toselectnewpackage, $id)) {
				setEventMessage($langs->trans("TooManyPackages"), 'warnings');
				unset($_SESSION['package_array']);
			} else {
				$assignedPackageObj = new Package($db);
				$grouptoolsPackages = new GroupToolsPackages($db);
				foreach ($_SESSION['package_array'] as $newtool) {
					$assignedPackageObj->fetch($newtool);
					$helper->savePackageData($grouptoolsPackages, $id, $newtool, $langs);
				}
				setEventMessage($langs->trans("tooladded"));
				unset($_SESSION['package_array']);
			}
		}
	}
}

if ($confirmtools == 'confirm') {
	foreach ($toselect as $selected) {
		$moredata = explode('_', $selected);
		$data = $helper->createDataToolArray($id, 'add', $moredata[1]);
		$toolNaplo->createToolsNaplo($user, $data);
	}
	$url = $_SERVER["PHP_SELF"] . '?id=' . $id;
	header("Location: " . $url);
}

if ($confirmUsersButton) {
	//print $confirmUsersButton;exit;
	$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?groupuser_id=' . $confirmUsersButton . '&id=' . $id, $langs->trans('UserConfirm'), $langs->trans('UserConfirmObject', $userString), 'confirm_users_settlement', '', 0, 1);
}

$assignementIsReady = $helper->checkPackageUserAssignement($id);
$eztHasznalomAzosszerendelesekre = empty($assignementIsReady) ? $packageuser : $assignementIsReady;
$newUserDetected = array_diff_assoc($eztHasznalomAzosszerendelesekre, $assignementIsReady);

if (!empty($id)) {
	$PackagesOfGroups = $helper->getPackagesById($id);
	// The devices have to change packages 
	$allPackages = $helper->getAllPackagesFromSelectedEntity($id, $selectedEntities);
	$confirmButtonDisplay = empty($helper->getToolsFromNaploToday($db, $id)) && !empty($PackagesOfGroups) ? "display:block;" : "display:none;";
	$PrintButtonDisplay = !empty($helper->getToolsFromNaploToday($db, $id)) && !empty($PackagesOfGroups) ? "display:block;" : "display:none;";
	$buttonContent = $helper->createButtonContent($db, $id, $PackagesOfGroups, $confirmButtonDisplay, $PrintButtonDisplay);
}

$permissiontoclearall = $user->hasRight('settlements', 'settlementsgroup', 'clearall');

$title = '';
$help_url = '';
$morejs = '';
$morecss = '';
llxHeader('', $title, $help_url, '', 0, 0, $morejs, $morecss, '', 'classforhorizontalscrolloftabs');
include DOL_DOCUMENT_ROOT . '/custom/settlements/core/actions_addupdatedelete.inc.php';

//print_r($_REQUEST);

$url = $_SERVER["PHP_SELF"] . '?idmenu=' . $idmenu . '&mainmenu=settlements&leftmenu=&id=' . $id;

print '<form method="POST" id="AssociationFormList" action="' . $url . '" onkeyup="submitFormAjaxPackages()">' . "\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="confirm" value="' . $confirm . '">';
print '<input type="hidden" id ="groupid" name="groupid" value="' . $id . '">';
print '<input type="hidden" id ="delete" name="delete" value="">';

if ($permissiontoclearall) {
	if ($helper->packageGroupsAreEmpty()) {
		$clearAllButton = '<div style="text-align: center; color:red; margin-bottom: 30px;">' . $langs->trans('EmptyToolsGroup') . '</div>';
	} else {
		$clearAllButton = include DOL_DOCUMENT_ROOT . '/custom/settlements/core/tpl/packageclearall.tpl.php';
	}
}

print load_fiche_titre($langs->trans("AssociationGroupAndTools"), '', 'settlements.png@settlements');
if ($confirmUsersButton) {
	print $formconfirm;
}

if ($massaction == 'delete') {
	$hideConfirmBoolean = true;
	print $helper->massactionDelete();
}

if ($confirmbutton) {
	print $helper->confirmButtonConfirmeText();
}

include DOL_DOCUMENT_ROOT . '/custom/settlements/core/tpl/packagecheckboxes.tpl.php';

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" id="entity_' . $key . '" name="entity_' . $key . '" value="' . $key . '" ' . $checked . '><label for="' . $key . '">' . $value . '</label></div>';
}
print '</div>';
print '<div style="clear:both;></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 colspan="2">' . $langs->trans("groupname") . '</td></tr>';
print '<tr><td class="liste_titre"><input id="group_search" style="width:100%; height:30px;" type="text" class="" name="search_group_title" value="' . $search_group_title . '" placeholder="Search..."></td>
	<td id="delete_group_search" class="right"><div style="cursor: pointer;"><a href="' . $_SERVER["PHP_SELF"] . '?idmenu=' . $idmenu . '&mainmenu=settlements&leftmenu="><span class="fa fa-trash"></span></a></div>
	</td></tr>';

if (!empty($groups)) {
	$stringLine .= '<table style="width: 100%; margin-bottom: 20px;"><tr><td style="width: 33%;"><hr></td><td style="width: 20%; text-align: center; color: grey;">Empty groups</td><td style="width: 33%;"><hr></td></tr></table>';
	$groupsString = '';
	$groupsStringEmpty = '';
	print '<tr><td colspan="3"><div id="searchedPackagesDiv"><table style="width:100%;">';
	$userCounter = $helper->getNumberOfUsers();
	foreach ($groups as $group) {
		$confirmedGroup = $helper->checkConfirmation($group['rowid']);
		$coloredLine = $id == $group['rowid'] ? ' background-color: #b0c4de' : '';
		$checker = $confirmedGroup ? '<span class="fa fa-check" style="color: green;"></span>' : '<span class="fa fa-exclamation" style="color: red;"></span>';
		$numberOfUsers = '';
		$usersArray = [];
		if (isset($userCounter[$group['rowid']][0])) {
			$peopleOrPerson = intval($userCounter[$group['rowid']][0]) > 1 ? $langs->trans('people') : $langs->trans('person');
			$numberOfUsers = '(' . $userCounter[$group['rowid']][0] . ' ' . $peopleOrPerson . ')';
			$usersArray = $helper->getUsersById($db, $userCounter[$group['rowid']][1]);
		}

		$popupBox = $helper->createPopoupBox($numberOfUsers, $usersArray, $group['rowid']);
		if (!empty($usersArray)) {
			$groupsString .= '<tr style="height:30px; cursor:pointer;' . $coloredLine . '"><td><div  class="submitFormLink" data-value="' . $group['rowid'] . '"><span class="fa fa-group pictofixedwidth"></span> ' . $group['ref'] . '</div><div class="groupColumn2ndLine submitFormLink" data-value="' . $group['rowid'] . '" style="float:left;">' . $group['label'] . '</div>' . $popupBox . '</td>';
			//print '<tr style="height:30px; cursor:pointer;' . $coloredLine . '"><td><div  class="submitFormLink" data-value="' . $group['rowid'] . '"><span class="fa fa-group pictofixedwidth"></span> ' . $group['ref'] . '</div><div class="groupColumn2ndLine submitFormLink" data-value="' . $group['rowid'] . '" style="float:left;">' . $group['label'] . '</div>' . $popupBox . '</td>';
			//print '<td>' . $checker . '</td>';
			$groupsString .= '</tr>';
			//print '</tr>';
			$groupsString .= '<tr id="users_' . $group['rowid'] . '"  style="display:none; width:100%; background-color:lightgrey;"><td>';
			//print '<tr id="users_' . $group['rowid'] . '"  style="display:none; width:100%; background-color:lightgrey;"><td>';
			foreach ($usersArray as $users) {
				$groupsString .= '&nbsp;<a href="/user/card.php?id=' . $users['fk_user'] . '&save_lastsearch_values=1"><span class="fas fa-user" style="color: #a69944; cursor: pointer;"></span>&nbsp;' . $users['lastname'] . ' ' . $users['firstname'] . ' (' . $users['login'] . ')</a><br>';
				//print '&nbsp;<a href="/user/card.php?id=' . $users['fk_user'] . '&save_lastsearch_values=1"><span class="fas fa-user" style="color: #a69944; cursor: pointer;"></span>&nbsp;' . $users['lastname'] . ' ' . $users['firstname'] . ' (' . $users['login'] . ')</a><br>';
			}
			$groupsString .= '</td></tr>';
		}else{
			$groupsStringEmpty .= '<tr style="height:30px; cursor:pointer;' . $coloredLine . '"><td><div  class="submitFormLink" data-value="' . $group['rowid'] . '"><span class="fa fa-group pictofixedwidth"></span> ' . $group['ref'] . '</div><div class="groupColumn2ndLine submitFormLink" data-value="' . $group['rowid'] . '" style="float:left;">' . $group['label'] . '</div>' . $popupBox . '</td>';
			$groupsStringEmpty .= '</tr>';
		}
	}

	print $groupsString;
	print $stringLine;
	print $groupsStringEmpty;
	print '</table>';
	print '</div></td></tr>';

} else {
	print '<tr style="height: 60px; text-align: center; color:red;"><td>' . $langs->trans('nogroup') . '</td></tr>';
}

print '</table>';
//---------------------------------------------
#2
//---------------------------------------------
$groupName = $helper->getGroupLabelById($id);
$DeviceCounter = $helper->getNumberOfDevices();
$group_id = $helper->getGroupIdBygroupToolId($id);

print '</div><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="3">
			<div style="margin-left:10px;">
				<div style="float:left; margin-top:10px;"><a href="settlementsindex.php?idmenu=965&mainmenu=settlements&leftmenu=&id=' . $id . '"><span class="fa fa-arrow-left"></span> Groups</a></div>
				<div><a href="/custom/financialreport/settlementsstatementsindex.php?id=' . $group_id . '">' . $langs->trans("packagesofgroup", $groupName) . '</a></div>
			</div>
		</td>
		</tr>';

if (!empty($PackagesOfGroups)) {
	print '<tr><td class="right" style="color:gray;" colspan="2">' . $langs->trans('selectAll') . '</td><td class="nowrap center"><input id="cb912" class="flat checkforallselect" type="checkbox"></td></tr>';
	$packageAssigned = false;
	foreach ($PackagesOfGroups as $package) {
		$popupBox2 = $helper->createPopupBox($package, $DeviceCounter);

		#--------------------
		#	Checkbox
		#--------------------
		$selected = in_array($package['rowid'] . '_' . $package['fk_package'], $toselect) ? 'checked' : '';
		$chkCol2Disabled = "";
		$recordClosed = "";

		$assignementsOfThisPackage = $helper->getAssignementsOfThisPackage($id, $package['fk_package']);

		if (!empty($assignementsOfThisPackage)) {
			foreach ($assignementsOfThisPackage as $record) {
				if (!$record['status']) {
					$chkCol2Disabled = "disabled";
				}
			}
		}

		print '<tr style="height:30px; background-color:lightgrey">
			<td><span class="fa fa-toolbox pictofixedwidth"></span> <a href="/custom/settlements/settlementpackagetoolssettingsindex.php?idmenu=1592&mainmenu=settlements&leftmenu=&id=' . $package['fk_package'] . '">' . $package['ref'] . '</a></td><td>' . $popupBox2 . '</td>
			<td class="nowrap center"><input id="id_2_' . $package['rowid'] . '" class="flat checkforselect" type="checkbox" name="toselect[]" value="' . $package['rowid'] . '_' . $package['fk_package'] . '"' . $selected . ' ' . $chkCol2Disabled . '></td>
			</tr>';
		foreach ($assignementsOfThisPackage as $listRecord) {
			$packageHistoryId = $listRecord['rowid'];
			$sql = "SELECT * FROM " . MAIN_DB_PREFIX . "user WHERE rowid = {$listRecord['user_id']}";
			$userData = $db->query($sql);
			while ($row = $db->fetch_object($userData)) {
				$userObj = $row;
			}
			//$userObj = new User($db);
			//$userObj->fetch($listRecord['user_id']);
			if ($listRecord['status']) {
				$recordClosed = '<font color="red">Closed</font>';
			} else {
				$recordClosed = '';
			}
			print '<tr><td><a href="/custom/rollerstorage/packagehistory_card.php?id=' . $packageHistoryId . '&idmenu=' . $idmenu . '&fk_group_id=' . $id . '&changeback=1" class="AssignedPackageHistoryRecord">' . $langs->trans('PackageHistoryRecord') . '</a> ' . $recordClosed . ' </td>
					<td colspan="2"><a href="/user/card.php?id=' . $userObj->rowid . '&save_lastsearch_values=1">' . $userObj->firstname . ' ' . $userObj->lastname . '</td></tr>';
		}

		print '<tr><td><a href="/custom/rollerstorage/packagehistory_card.php?action=create&package_id=' . $package['fk_package'] . '&fk_group_id=' . $id . '&fk_groupuser_id=' . $userCounter[$id][1] . '&idmenu=' . $idmenu . '" class=""><span class="fa fa-plus createPackageHistoryRecord"></span></td></tr>';

	}
	//$confirmedGroup = $helper->checkConfirmation($id);
	$confirmedGroup = true;
	if (!$confirmedGroup) {
		if ($userCounter[$id][0] > 0) {
			print '<tr><td>&nbsp;</td></tr>';
			print '<tr><td colspan="3"><button type="submit" name="confirmUsersButton" value="' . $userCounter[$id][1] . '" class="confirmUsersButton">' . $langs->trans('ConfirmUsers') . '</button></td></tr>';
		}
	}
} else {
	print '<tr style="height: 60px; text-align: center; color:red;"><td>' . $langs->trans('nopackageassigned') . '</td></tr>';
}

print '</table>';
//---------------------------------------------
#3
//---------------------------------------------
print '</div><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="3">' . $langs->trans("freepackages") . '</td></tr>';
print '<tr><td class="liste_titre"><input id="package_search" style="width:100%; height:30px;" type="text" class="" name="search_package_name" value="' . $search_package_name . '" placeholder="' . $langs->trans("search") . '" ></td>
<td id="delete_search" class="center" onclick="deleteFunction()"><div style="cursor: pointer;"><span class="fa fa-trash"></span></div>
</td></tr>';

if (is_array($allPackages)) {
	print '<td colspan="4"><div id="searchedPackageDiv">
	<table style="width:100%;">';
	$deviceCounter = $helper->getNumberOfDevices();
	if (!empty($allPackages['freePackages'])) {
		foreach ($allPackages['freePackages'] as $freePackage) {
			$numberOfDevices3 = '';
			$devicesArray3 = [];
			if (isset($DeviceCounter[$freePackage['rowid']])) {
				$numberOfDevices3 = '(' . $DeviceCounter[$freePackage['rowid']] . ' ' . $langs->trans('device') . ')';
				$devicesArray3 = $helper->getDevicesById($db, $freePackage['rowid']);
			}
			$popupBox3Text = $helper->createPopoupBoxForDeviceList($numberOfDevices3, $devicesArray3);
			$popupBox3 = $popupBox3Text != '' ? $popupBox3Text : '<font style="color:red;">' . $langs->trans('emptyPackage') . '</font>';
			print '<tr style="height:30px;">
			<td class="nowrap center"><input id="id_3_' . $freePackage['rowid'] . '" class="flat checkforselectadd" type="checkbox" onclick="submitFormAddPackage(event)" name="toselectnewpackage[]" value="' . $freePackage['rowid'] . '"></td>
			<td><span class="fa fa-toolbox pictofixedwidth"></span><a href="/custom/settlements/settlementpackagetoolssettingsindex.php?idmenu=1592&mainmenu=settlements&leftmenu=&id=' . $freePackage['rowid'] . '"> ' . $freePackage['ref'] . '</a></td>
			<td>' . $popupBox3 . '</td>
			</tr>';
		}
	}
	print '</table><table style="width:100%; color: red;"><tr><td>';
	if (is_array($allPackages['addedPackages'])) {
		$helper->addedPackageDiv($allPackages, $DeviceCounter);
	}
	print '</td></tr></table>';

	print '</div></td>';
}
print '</div></div>';
print '</form>' . "\n";

// End of page
llxFooter();
$db->close();
?>
<style>
	.groupColumn2ndLine {
		color: grey !important;
	}

	.createPackageHistoryRecord {
		display: block;
		height: 25px;
		width: 40px;
		background-color: green;
		border-radius: 5px;
		text-decoration: none;
		color: white !important;
		text-align: center;
		padding-top: 10px;
	}

	.confirmUsersButton {
		display: block;
		height: 40px;
		width: 100%;
		border-radius: 5px;
		text-decoration: none;
		text-align: center;

		background-color: #98FB98;
	}

	.createPackageHistoryRecord:hover {
		text-decoration: none;
	}

	.cursorNotAllowed {
		cursor: not-allowed;
	}

	.clearAllButton {
		height: 20px;
		width: 70px;
		background-color: red;
		border: 1px red solid;
		border-radius: 5px;
		text-align: center;
		color: white !important;
		text-decoration: none;
	}

	.clearAllButton:hover {
		text-decoration: none;
	}
</style>

<script>
	$(document).ready(function () {
		// Az űrlap elküldése, ha a checkbox változik
		$('.entitiesChk').change(function () {
			$('#AssociationFormList').submit();
		});



		var elements = document.getElementsByClassName('submitFormLink');
		for (var i = 0; i < elements.length; i++) {
			//console.log(i);
			elements[i].addEventListener('click', function (event) {
				event.preventDefault();
				var form = document.getElementById('AssociationFormList');
				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 + '&nopackageuser=1';
				document.getElementById('AssociationFormList').submit();
			});
		}
	});

	function popupboxClick(id) {
		var opened = $('#users_' + id).css('display');
		if (opened == 'none') {
			$('#users_' + id).css('display', 'inline-block');
		} else {
			$('#users_' + id).css('display', 'none');
		}
	}

	function deleteSelectorsFunction() {
		$('.userSelectors').each(function () {
			$(this).val("-1");
		});
		document.getElementById("AssociationFormList").submit();
	}

	function submitSelect() {
		document.getElementById("AssociationFormList").submit();
	}

	function groupconfirm() {
		$('.checkforselect').prop('checked', true);
	}

	function deleteFunction() {
		$("#package_search").val('');
		$(".checkforselectadd").prop('checked', false);
		$("#delete").val(1);
		document.getElementById("AssociationFormList").submit();
	}

	function submitFormAjaxPackages() {
		var input = document.getElementById("package_search");
		var inputGroup = document.getElementById("group_search");
		var checkboxes = document.querySelectorAll('.checkforselectadd:checked');
		var values = Array.from(checkboxes).map(function (checkbox) {
			return checkbox.value;
		});
		//if (input.value != '') {
		var xhr = new XMLHttpRequest();
		xhr.open("GET", "ajaxPackage.php?search_package_name=" + input.value + "&toselectnewpackage=" + values + "&groupid=" + groupid.value, true);
		xhr.onreadystatechange = function () {
			if (xhr.readyState === 4 && xhr.status === 200) {
				$("#searchedPackageDiv").html(xhr.responseText);
			}
		};
		xhr.send();
		//}
		//if (inputGroup.value != '') {
		var xhrGroup = new XMLHttpRequest();
		var selectedCheckboxes = $('input[type="checkbox"][id*="entity_"]:checked');
		var checkboxValues = selectedCheckboxes.toArray().map(function (checkbox) {
			return $(checkbox).val();
		});
		xhrGroup.open("GET", "ajaxPackageName.php?search_group_title=" + inputGroup.value + '&selectedEntities=' + checkboxValues, true);
		xhrGroup.onreadystatechange = function () {
			if (xhrGroup.readyState === 4 && xhrGroup.status === 200) {
				$("#searchedPackagesDiv").html(xhrGroup.responseText);
			}
		};
		xhrGroup.send();
		//}
	}

	function submitFormAddPackage(event) {
		//alert('submitFormAddPackage');
		var checkbox = event.target;
		var groupid = document.getElementById("groupid");
		if (checkbox.checked) {
			var input = document.getElementById("package_search");
			var checkboxes = document.querySelectorAll('.checkforselectadd:checked');
			var values = Array.from(checkboxes).map(function (checkbox1) {
				return checkbox1.value;
			});
			var xhr = new XMLHttpRequest();
			xhr.open("GET", "ajaxPackage.php?search_package_name=" + input.value + "&toselectnewpackage=" + values + "&groupid=" + groupid.value, true);
			xhr.onreadystatechange = function () {
				if (xhr.readyState === 4 && xhr.status === 200) {
					$("#searchedPackageDiv").html(xhr.responseText);
				}
			};
			xhr.send();
		} else {
			var input = document.getElementById("package_search");
			var checkboxes = document.querySelectorAll('.checkforselectadd:checked');
			var values = Array.from(checkboxes).map(function (checkbox1) {
				return checkbox1.value;
			});
			var xhr = new XMLHttpRequest();
			xhr.open("GET", "ajaxPackage.php?search_package_name=" + input.value + "&reduction=" + values + "&groupid=" + groupid.value, true);
			xhr.onreadystatechange = function () {
				if (xhr.readyState === 4 && xhr.status === 200) {
					$("#searchedPackageDiv").html(xhr.responseText);
				}
			};
			xhr.send();
		}
	}

	$('.massactionaddconfirmed').click(function () {
		$("#package_search").val('');
	})

	$('.massactionconfirmed').click(function () {
		$("#package_search").val('');
		$("#deletechk").val(1);
	})

	$('.checkforallselect').click(function () {
		if ($(this).is(':checked')) {
			$('.checkforselect').prop('checked', true);
			$('#divDelete').css('display', 'inline-block');
			$('#massaction').css('display', 'inline-block');
			$('.massactionselect ').css('display', '');
			$('.massactionconfirmed ').css('display', '');

		} else {
			$('#divDelete').css('display', 'none');
			$('.checkforselect').prop('checked', false);
			$('#massaction').css('display', 'none');
			$('.massactionselect ').css('display', 'none');
			$('.massactionconfirmed ').css('display', 'none');

		}
	})

	$('.checkforselect').click(function () {
		if ($(this).is(':checked')) {
			$('#divDelete').css('display', 'inline-block');
			$('#massaction').css('display', 'inline-block');
			$('.massactionselect ').css('display', '');
			$('.massactionconfirmed ').css('display', '');

		} else {
			$('#massaction').css('display', 'none');
			$('#divDelete').css('display', 'none');
			$('.massactionselect ').css('display', 'none');
			$('.massactionconfirmed ').css('display', 'none');

		}
	})

	$('.checkforselectadd').click(function () {
		if ($(this).is(':checked')) {
			$('#divAdd').css('display', 'inline-block');
			$('#massactionadd').css('display', 'inline-block');
			$('.massactionaddselect ').css('display', '');
			$('.massactionaddconfirmed ').css('display', '');
		} else {
			$('#divAdd').css('display', 'none');
			$('#massactionadd').css('display', 'none');
			$('.massactionaddselect ').css('display', 'none');
			$('.massactionaddconfirmed ').css('display', 'none');

		}
	})

	var input = document.getElementById("package_search");
	input.focus();
	input.setSelectionRange(input.value.length, input.value.length);
</script>