<?php
/* Copyright (C) 2011		Dimitri Mouillard			<dmouillard@teclib.com>
 * Copyright (C) 2013-2020	Laurent Destailleur			<eldy@users.sourceforge.net>
 * Copyright (C) 2012-2016	Regis Houssin				<regis.houssin@inodbox.com>
 * Copyright (C) 2018		Charlene Benke				<charlie@patas-monkey.com>
 * Copyright (C) 2019-2024  Frédéric France				<frederic.france@free.fr>
 * Copyright (C) 2024		Benjamin Falière			<benjamin.faliere@altairis.fr>
 * Copyright (C) 2024		Alexandre Spangaro			<alexandre@inovea-conseil.com>
 * Copyright (C) 2024-2025	MDW							<mdeweerd@users.noreply.github.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 <https://www.gnu.org/licenses/>.
 */

/**
 *   	\file       htdocs/holiday/list.php
 *		\ingroup    holiday
 *		\brief      List of holiday
 */

// Load Dolibarr environment
require '../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
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.'/core/lib/date.lib.php';
require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
require_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php';
require_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/usergroups.lib.php';

/**
 * @var Conf $conf
 * @var DoliDB $db
 * @var HookManager $hookmanager
 * @var Translate $langs
 * @var User $user
 */

// Load translation files required by the page
$langs->loadLangs(array('users', 'other', 'holiday', 'hrm'));

// Protection if external user
if ($user->socid > 0) {
	accessforbidden();
}

$action     = GETPOST('action', 'aZ09'); // The action 'add', 'create', 'edit', 'update', 'view', ...
$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists)
$show_files = GETPOSTINT('show_files'); // Show files area generated by bulk actions ?
$confirm    = GETPOST('confirm', 'alpha'); // Result of a confirmation
$cancel     = GETPOST('cancel', 'alpha'); // We click on a Cancel button
$toselect   = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list
$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'holidaylist'; // To manage different context of search
$mode        = GETPOST('mode', 'alpha'); // for switch mode view result
$backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page
$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print')

$id = GETPOSTINT('id');

$childids = $user->getAllChildIds(1);


$diroutputmassaction = $conf->holiday->dir_output.'/temp/massgeneration/'.$user->id;


// Load variable for pagination
$limit = GETPOSTINT('limit') ? GETPOSTINT('limit') : $conf->liste_limit;
$sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT("page");
if (empty($page) || $page == -1) {
	$page = 0;
}     // If $page is not defined, or '' or -1
$offset = $limit * $page;
$pageprev = $page - 1;
$pagenext = $page + 1;
if (!$sortorder) {
	$sortorder = "DESC";
}
if (!$sortfield) {
	$sortfield = "cp.date_debut";
}

$search_all          = trim(GETPOST('search_all', 'alphanohtml'));
$search_ref          = GETPOST('search_ref', 'alphanohtml');
$search_day_create   = GETPOST('search_day_create', 'int');
$search_month_create = GETPOST('search_month_create', 'int');
$search_year_create  = GETPOST('search_year_create', 'int');
$search_day_start    = GETPOST('search_day_start', 'int');
$search_month_start  = GETPOST('search_month_start', 'int');
$search_year_start   = GETPOST('search_year_start', 'int');
$search_day_end      = GETPOST('search_day_end', 'int');
$search_month_end    = GETPOST('search_month_end', 'int');
$search_year_end     = GETPOST('search_year_end', 'int');
$search_employee     = GETPOST('search_employee', 'intcomma');
$search_valideur     = GETPOST('search_valideur', 'intcomma');
$search_status       = GETPOST('search_status', 'intcomma');
$search_type         = GETPOST('search_type', 'intcomma');

// Initialize a technical objects
$object = new Holiday($db);
$extrafields = new ExtraFields($db);
$hookmanager->initHooks(array('holidaylist')); // Note that conf->hooks_modules contains array

// Fetch optionals attributes and labels
$extrafields->fetch_name_optionals_label($object->table_element);

$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');

// List of fields to search into when doing a "search in all"
$fieldstosearchall = array(
	'cp.ref' => 'Ref',
	'cp.description' => 'Description',
	'uu.lastname' => 'EmployeeLastname',
	'uu.firstname' => 'EmployeeFirstname',
	'uu.login' => 'Login'
);

$arrayfields = array(
	'cp.ref' => array('label' => $langs->trans("Ref"), 'checked' => '1'),
	'cp.fk_user' => array('label' => $langs->trans("Employee"), 'checked' => '1', 'position' => 20),
	'cp.fk_validator' => array('label' => $langs->trans("ValidatorCP"), 'checked' => '1', 'position' => 30),
	'cp.fk_type' => array('label' => $langs->trans("Type"), 'checked' => '1', 'position' => 35),
	'duration' => array('label' => $langs->trans("NbUseDaysCPShort"), 'checked' => '1', 'position' => 38),
	'cp.date_debut' => array('label' => $langs->trans("DateStart"), 'checked' => '1', 'position' => 40),
	'cp.date_fin' => array('label' => $langs->trans("DateEnd"), 'checked' => '1', 'position' => 42),
	'cp.date_valid' => array('label' => $langs->trans("DateValidation"), 'checked' => '1', 'position' => 60),
	'cp.date_approval' => array('label' => $langs->trans("DateApprove"), 'checked' => '1', 'position' => 70),
	'cp.date_create' => array('label' => $langs->trans("DateCreation"), 'checked' => '0', 'position' => 500),
	'cp.tms' => array('label' => $langs->trans("DateModificationShort"), 'checked' => '0', 'position' => 501),
	'cp.statut' => array('label' => $langs->trans("Status"), 'checked' => '1', 'position' => 1000),
);
// Extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php';


// Security check
$socid = 0;
if ($user->socid > 0) {	// Protection if external user
	//$socid = $user->socid;
	accessforbidden();
}

$permissiontoread = $user->hasRight('holiday', 'read');
$permissiontodelete = $user->hasRight('holiday', 'delete');
$permissiontoapprove = $user->hasRight('holiday', 'approve');

if (!isModEnabled('holiday')) {
	accessforbidden('Module holiday not enabled');
}

$result = restrictedArea($user, 'holiday', '', '');
// If we are on the view of a specific user
if ($id > 0) {
	$canread = 0;
	if ($id == $user->id) {
		$canread = 1;
	}
	if ($user->hasRight('holiday', 'readall')) {
		$canread = 1;
	}
	if ($user->hasRight('holiday', 'read') && in_array($id, $childids)) {
		$canread = 1;
	}
	if (!$canread) {
		accessforbidden();
	}
}



/*
 * Actions
 */

if (GETPOST('cancel', 'alpha')) {
	$action = 'list';
	$massaction = '';
}
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
	$massaction = '';
}

$parameters = array('socid' => $socid, 'arrayfields' => &$arrayfields);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) {
	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}

if (empty($reshook)) {
	// Selection of new fields
	include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';

	// Purge search criteria
	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
		$search_ref = "";
		$search_month_create = "";
		$search_year_create = "";
		$search_month_start = "";
		$search_year_start = "";
		$search_month_end = "";
		$search_year_end = "";
		$search_employee = "";
		$search_valideur = "";
		$search_status = "";
		$search_type = '';
		$toselect = array();
		$search_array_options = array();
	}
	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')
		|| GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) {
		$massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
	}

	// Mass actions
	$objectclass = 'Holiday';
	$objectlabel = 'Holiday';
	$uploaddir = $conf->holiday->dir_output;
	include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
}


/*
 * View
 */

$form = new Form($db);
$formother = new FormOther($db);
$formfile = new FormFile($db);

$fuser = new User($db);
$holidaystatic = new Holiday($db);

// Update sold
$result = $object->updateBalance();

$title = $langs->trans('Holidays');
$help_url = 'EN:Module_Holiday';

llxHeader('', $title, $help_url, '', 0, 0, '', '', '', 'bodyforlist mod-holiday page-list');

$max_year = 5;
$min_year = 10;

// Get current user id
$user_id = $user->id;

if ($id > 0) {
	// Charge utilisateur edite
	$fuser->fetch($id, '', '', 1);
	$fuser->loadRights();
	$user_id = $fuser->id;

	$search_employee = $user_id;
}

// Récupération des congés payés de l'utilisateur ou de tous les users de sa hierarchy
// Load array $object->holiday

$sql = "SELECT";
$sql .= " cp.rowid,";
$sql .= " cp.ref,";

$sql .= " cp.fk_user,";
$sql .= " cp.fk_type,";
$sql .= " cp.date_create,";
$sql .= " cp.tms as date_modification,";
$sql .= " cp.description,";
$sql .= " cp.date_debut,";
$sql .= " cp.date_fin,";
$sql .= " cp.halfday,";
$sql .= " cp.statut as status,";
$sql .= " cp.fk_validator,";
$sql .= " cp.date_valid,";
$sql .= " cp.fk_user_valid,";
$sql .= " cp.date_approval,";
$sql .= " cp.fk_user_approve,";
$sql .= " cp.date_refuse,";
$sql .= " cp.fk_user_refuse,";
$sql .= " cp.date_cancel,";
$sql .= " cp.fk_user_cancel,";
$sql .= " cp.detail_refuse,";

$sql .= " uu.lastname as user_lastname,";
$sql .= " uu.firstname as user_firstname,";
$sql .= " uu.admin as user_admin,";
$sql .= " uu.email as user_email,";
$sql .= " uu.login as user_login,";
$sql .= " uu.statut as user_status,";
$sql .= " uu.photo as user_photo,";

$sql .= " ua.lastname as validator_lastname,";
$sql .= " ua.firstname as validator_firstname,";
$sql .= " ua.admin as validator_admin,";
$sql .= " ua.email as validator_email,";
$sql .= " ua.login as validator_login,";
$sql .= " ua.statut as validator_status,";
$sql .= " ua.photo as validator_photo";
// Add fields from extrafields
if (!empty($extrafields->attributes[$object->table_element]['label'])) {
	foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
		$sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key." as options_".$key : '');
	}
}
// Add fields from hooks
$parameters = array();
$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook
$sql .= $hookmanager->resPrint;
$sql = preg_replace('/,\s*$/', '', $sql);

$sqlfields = $sql; // $sql fields to remove for count total

$sql .= " FROM ".MAIN_DB_PREFIX."holiday as cp";
if (isset($extrafields->attributes[$object->table_element]['label']) && is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) {
	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (cp.rowid = ef.fk_object)";
}
$sql .= ", ".MAIN_DB_PREFIX."user as uu, ".MAIN_DB_PREFIX."user as ua";
$sql .= " WHERE cp.entity IN (".getEntity('holiday').")";
$sql .= " AND cp.fk_user = uu.rowid AND cp.fk_validator = ua.rowid "; // Hack pour la recherche sur le tableau
// Search all
if (!empty($search_all)) {
	$sql .= natural_search(array_keys($fieldstosearchall), $search_all);
}
// Ref
if (!empty($search_ref)) {
	$sql .= natural_search("cp.ref", $search_ref);
}
// Start date
$sql .= dolSqlDateFilter("cp.date_debut", $search_day_start, $search_month_start, $search_year_start);
// End date
$sql .= dolSqlDateFilter("cp.date_fin", $search_day_end, $search_month_end, $search_year_end);
// Create date
$sql .= dolSqlDateFilter("cp.date_create", $search_day_create, $search_month_create, $search_year_create);
// Employee
if (!empty($search_employee) && $search_employee != -1) {
	$sql .= " AND cp.fk_user = '".$db->escape($search_employee)."'\n";
}
// Validator
if (!empty($search_valideur) && $search_valideur != -1) {
	$sql .= " AND cp.fk_validator = '".$db->escape($search_valideur)."'\n";
}
// Type
if (!empty($search_type) && $search_type != -1) {
	$sql .= ' AND cp.fk_type IN ('.$db->sanitize($db->escape($search_type)).')';
}
// Status
if (!empty($search_status) && $search_status != -1) {
	$sql .= " AND cp.statut = '".$db->escape($search_status)."'\n";
}

if (!$user->hasRight('holiday', 'readall')) {
	$sql .= ' AND cp.fk_user IN ('.$db->sanitize(implode(',', $childids)).')';
}
if ($id > 0) {
	$sql .= " AND cp.fk_user = ".((int) $id);
}

// Add where from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
// Add where from hooks
$parameters = array();
$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
$sql .= $hookmanager->resPrint;

// Count total nb of records
$nbtotalofrecords = '';
if (!getDolGlobalInt('MAIN_DISABLE_FULL_SCANLIST')) {
	/* The fast and low memory method to get and count full list converts the sql into a sql count */
	$sqlforcount = preg_replace('/^'.preg_quote($sqlfields, '/').'/', 'SELECT COUNT(*) as nbtotalofrecords', $sql);
	$sqlforcount = preg_replace('/GROUP BY .*$/', '', $sqlforcount);
	$resql = $db->query($sqlforcount);
	if ($resql) {
		$objforcount = $db->fetch_object($resql);
		$nbtotalofrecords = $objforcount->nbtotalofrecords;
	} else {
		dol_print_error($db);
	}

	if (($page * $limit) > $nbtotalofrecords) {	// if total resultset is smaller than the paging size (filtering), goto and load page 0
		$page = 0;
		$offset = 0;
	}
	$db->free($resql);
}

// Complete request and execute it with limit
$sql .= $db->order($sortfield, $sortorder);
if ($limit) {
	$sql .= $db->plimit($limit + 1, $offset);
}

//print $sql;
$resql = $db->query($sql);
if (!$resql) {
	dol_print_error($db);
	exit;
}

$num = $db->num_rows($resql);

$arrayofselected = is_array($toselect) ? $toselect : array();

$param = '';
if (!empty($mode)) {
	$param .= '&mode='.urlencode($mode);
}
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
	$param .= '&contextpage='.urlencode($contextpage);
}
if ($limit > 0 && $limit != $conf->liste_limit) {
	$param .= '&limit='.((int) $limit);
}
if ($optioncss != '') {
	$param .= '&optioncss='.urlencode($optioncss);
}
if ($search_ref) {
	$param .= '&search_ref='.urlencode($search_ref);
}
if ($search_day_create) {
	$param .= '&search_day_create='.urlencode($search_day_create);
}
if ($search_month_create) {
	$param .= '&search_month_create='.urlencode($search_month_create);
}
if ($search_year_create) {
	$param .= '&search_year_create='.urlencode($search_year_create);
}
if ($search_day_start) {
	$param .= '&search_day_start='.urlencode($search_day_start);
}
if ($search_month_start) {
	$param .= '&search_month_start='.urlencode($search_month_start);
}
if ($search_year_start) {
	$param .= '&search_year_start='.urlencode($search_year_start);
}
if ($search_day_end) {
	$param .= '&search_day_end='.urlencode($search_day_end);
}
if ($search_month_end) {
	$param .= '&search_month_end='.urlencode($search_month_end);
}
if ($search_year_end) {
	$param .= '&search_year_end='.urlencode($search_year_end);
}
if ($search_employee > 0) {
	$param .= '&search_employee='.urlencode($search_employee);
}
if ($search_valideur > 0) {
	$param .= '&search_valideur='.urlencode((string) ($search_valideur));
}
if ($search_type > 0) {
	$param .= '&search_type='.urlencode((string) ($search_type));
}
if ($search_status > 0) {
	$param .= '&search_status='.urlencode($search_status);
}
// Add $param from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';

// List of mass actions available
$arrayofmassactions = array(
	//'generate_doc'=>img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("ReGeneratePDF"),
	//'builddoc'=>img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("PDFMerge"),
	//'presend'=>img_picto('', 'email', 'class="pictofixedwidth"').$langs->trans("SendByMail"),
);
if (!empty($permissiontodelete)) {
	$arrayofmassactions['predelete'] = img_picto('', 'delete', 'class="pictofixedwidth"').$langs->trans("Delete");
}
if (!empty($permissiontoapprove)) {
	$arrayofmassactions['preapproveleave'] = img_picto('', 'check', 'class="pictofixedwidth"').$langs->trans("Approve");
}
if (GETPOSTINT('nomassaction') || in_array($massaction, array('presend', 'predelete'))) {
	$arrayofmassactions = array();
}
$massactionbutton = $form->selectMassAction('', $arrayofmassactions);

print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n";
if ($optioncss != '') {
	print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
}
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="'.($action == 'edit' ? 'update' : 'list').'">';
print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
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="page_y" value="">';
print '<input type="hidden" name="mode" value="'.$mode.'">';
if ($id > 0) {
	print '<input type="hidden" name="id" value="'.$id.'">';
}

if ($id > 0) {		// For user tab
	$title = $langs->trans("User");
	$linkback = '<a href="'.DOL_URL_ROOT.'/user/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
	$head = user_prepare_head($fuser);

	print dol_get_fiche_head($head, 'paidholidays', $title, -1, 'user');

	dol_banner_tab($fuser, 'id', $linkback, $user->hasRight('user', 'user', 'lire') || $user->admin);

	if (!getDolGlobalString('HOLIDAY_HIDE_BALANCE')) {
		print '<div class="underbanner clearboth"></div>';

		print '<br>';

		print showMyBalance($object, $user_id);
	}

	print dol_get_fiche_end();

	// Buttons for actions

	print '<div class="tabsAction">';

	$cancreate = 0;
	if ($user->hasRight('holiday', 'writeall')) {
		$cancreate = 1;
	}
	if ($user->hasRight('holiday', 'write') && in_array($user_id, $childids)) {
		$cancreate = 1;
	}

	if ($cancreate) {
		print '<a href="'.DOL_URL_ROOT.'/holiday/card.php?action=create&fuserid='.$user_id.'" class="butAction">'.$langs->trans("AddCP").'</a>';
	}

	print '</div>';
} else {
	$newcardbutton = '';
	$newcardbutton .= dolGetButtonTitle($langs->trans('ViewList'), '', 'fa fa-bars imgforviewmode', $_SERVER["PHP_SELF"].'?mode=common'.preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ((empty($mode) || $mode == 'common') ? 2 : 1), array('morecss' => 'reposition'));
	$newcardbutton .= dolGetButtonTitle($langs->trans('ViewKanban'), '', 'fa fa-th-list imgforviewmode', $_SERVER["PHP_SELF"].'?mode=kanban'.preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ($mode == 'kanban' ? 2 : 1), array('morecss' => 'reposition'));
	$newcardbutton .= dolGetButtonTitleSeparator();
	$newcardbutton .= dolGetButtonTitle($langs->trans('MenuAddCP'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/holiday/card.php?action=create', '', $user->hasRight('holiday', 'write'));

	print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_hrm', 0, $newcardbutton, '', $limit, 0, 0, 1);
}

$topicmail = "Information";
$modelmail = "leaverequest";
$objecttmp = new Holiday($db);
$trackid = 'leav'.$object->id;
include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';

if ($search_all) {
	$setupstring = '';
	foreach ($fieldstosearchall as $key => $val) {
		$fieldstosearchall[$key] = $langs->trans($val);
		$setupstring .= $key."=".$val.";";
	}
	print '<!-- Search done like if HOLIDAY_QUICKSEARCH_ON_FIELDS = '.$setupstring.' -->'."\n";
	print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).implode(', ', $fieldstosearchall).'</div>';
}

$moreforfilter = '';

$parameters = array();
$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
if (empty($reshook)) {
	$moreforfilter .= $hookmanager->resPrint;
} else {
	$moreforfilter = $hookmanager->resPrint;
}

if (!empty($moreforfilter)) {
	print '<div class="liste_titre liste_titre_bydiv centpercent">';
	print $moreforfilter;
	print '</div>';
}

$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
$htmlofselectarray = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage, getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN'));  // This also change content of $arrayfields with user setup
$selectedfields = ($mode != 'kanban' ? $htmlofselectarray : '');
$selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : '');

$include = '';
if (!$user->hasRight('holiday', 'readall')) {
	$include = 'hierarchyme'; // Can see only its hierarchyl
}

print '<div class="div-table-responsive">'; // You can use div-table-responsive-no-min if you don't need reserved height for your table
print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";

// Fields title search
// --------------------------------------------------------------------
print '<tr class="liste_titre_filter">';
// Action column
if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
	print '<td class="liste_titre center maxwidthsearch">';
	$searchpicto = $form->showFilterButtons('left');
	print $searchpicto;
	print '</td>';
}
if (!empty($arrayfields['cp.ref']['checked'])) {
	print '<td class="liste_titre">';
	print '<input class="flat maxwidth50" type="text" name="search_ref" value="'.dol_escape_htmltag($search_ref).'">';
	print '</td>';
}

if (!empty($arrayfields['cp.fk_user']['checked'])) {
	$morefilter = '';
	if (getDolGlobalString('HOLIDAY_HIDE_FOR_NON_SALARIES')) {
		$morefilter = 'AND employee = 1';
	}

	// User
	$disabled = 0;
	// If into the tab holiday of a user ($id is set in such a case)
	if ($id && !GETPOSTISSET('search_employee')) {
		$search_employee = $id;
		$disabled = 1;
	}

	print '<td class="liste_titre maxwidthonsmartphone left">';
	print $form->select_dolusers($search_employee, "search_employee", 1, null, $disabled, $include, '', '0', 0, 0, $morefilter, 0, '', 'maxwidth125');
	print '</td>';
}

// Approver
if (!empty($arrayfields['cp.fk_validator']['checked'])) {
	if ($user->hasRight('holiday', 'readall')) {
		print '<td class="liste_titre maxwidthonsmartphone left">';
		$validator = new UserGroup($db);
		$excludefilter = $user->admin ? '' : 'u.rowid <> '.((int) $user->id);
		$valideurobjects = $validator->listUsersForGroup($excludefilter, 1);
		$valideurarray = array();
		foreach ($valideurobjects as $val) {
			$valideurarray[$val] = $val;
		}
		print $form->select_dolusers($search_valideur, "search_valideur", 1, null, 0, $valideurarray, '', '0', 0, 0, $morefilter, 0, '', 'maxwidth125');
		print '</td>';
	} else {
		print '<td class="liste_titre">&nbsp;</td>';
	}
}

// Type
if (!empty($arrayfields['cp.fk_type']['checked'])) {
	print '<td class="liste_titre">';
	if (empty($mysoc->country_id)) {
		setEventMessages(null, array($langs->trans("ErrorSetACountryFirst"), $langs->trans("CompanyFoundation")), 'errors');
	} else {
		$typeleaves = $holidaystatic->getTypes(1, -1);
		$arraytypeleaves = array();
		foreach ($typeleaves as $key => $val) {
			$labeltoshow = ($langs->trans($val['code']) != $val['code'] ? $langs->trans($val['code']) : $val['label']);
			//$labeltoshow .= ($val['delay'] > 0 ? ' ('.$langs->trans("NoticePeriod").': '.$val['delay'].' '.$langs->trans("days").')':'');
			$arraytypeleaves[$val['rowid']] = $labeltoshow;
		}
		print $form->selectarray('search_type', $arraytypeleaves, $search_type, 1, 0, 0, '', 0, 0, 0, '', 'maxwidth100', 1);
	}
	print '</td>';
}

// Duration
if (!empty($arrayfields['duration']['checked'])) {
	print '<td class="liste_titre">&nbsp;</td>';
}

// Start date
if (!empty($arrayfields['cp.date_debut']['checked'])) {
	print '<td class="liste_titre center nowraponall">';
	print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_month_start" value="'.dol_escape_htmltag($search_month_start).'">';
	print $formother->selectyear($search_year_start, 'search_year_start', 1, $min_year, $max_year);
	print '</td>';
}

// End date
if (!empty($arrayfields['cp.date_fin']['checked'])) {
	print '<td class="liste_titre center nowraponall">';
	print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_month_end" value="'.dol_escape_htmltag($search_month_end).'">';
	print $formother->selectyear($search_year_end, 'search_year_end', 1, $min_year, $max_year);
	print '</td>';
}

// Date validation
if (!empty($arrayfields['cp.date_valid']['checked'])) {
	print '<td class="liste_titre center nowraponall">';
	print '</td>';
}

// Date approval
if (!empty($arrayfields['cp.date_approval']['checked'])) {
	print '<td class="liste_titre center nowraponall">';
	print '</td>';
}

// Extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';

// Fields from hook
$parameters = array('arrayfields' => $arrayfields);
$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;

// Create date
if (!empty($arrayfields['cp.date_create']['checked'])) {
	print '<td class="liste_titre center width200">';
	print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_month_create" value="'.dol_escape_htmltag($search_month_create).'">';
	print $formother->selectyear($search_year_create, 'search_year_create', 1, $min_year, 0);
	print '</td>';
}

// Create date
if (!empty($arrayfields['cp.tms']['checked'])) {
	print '<td class="liste_titre center width200">';
	print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_month_update" value="'.dol_escape_htmltag($search_month_update).'">';
	print $formother->selectyear($search_year_update, 'search_year_update', 1, $min_year, 0);
	print '</td>';
}

// Status
if (!empty($arrayfields['cp.statut']['checked'])) {
	print '<td class="liste_titre center parentonrightofpage">';
	print $object->selectStatutCP($search_status, 'search_status', 'search_status width100 onrightofpage');
	print '</td>';
}

// Action column
if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
	print '<td class="liste_titre center maxwidthsearch">';
	$searchpicto = $form->showFilterButtons();
	print $searchpicto;
	print '</td>';
}

print '</tr>'."\n";

$totalarray = array();
$totalarray['nbfield'] = 0;

// Fields title label
// --------------------------------------------------------------------
print '<tr class="liste_titre">';
if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
	print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n";
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['cp.ref']['checked'])) {
	print_liste_field_titre($arrayfields['cp.ref']['label'], $_SERVER["PHP_SELF"], "cp.ref", "", $param, '', $sortfield, $sortorder);
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['cp.fk_user']['checked'])) {
	print_liste_field_titre($arrayfields['cp.fk_user']['label'], $_SERVER["PHP_SELF"], "cp.fk_user", "", $param, '', $sortfield, $sortorder);
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['cp.fk_validator']['checked'])) {
	print_liste_field_titre($arrayfields['cp.fk_validator']['label'], $_SERVER["PHP_SELF"], "cp.fk_validator", "", $param, '', $sortfield, $sortorder);
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['cp.fk_type']['checked'])) {
	print_liste_field_titre($arrayfields['cp.fk_type']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder);
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['duration']['checked'])) {
	print_liste_field_titre($arrayfields['duration']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'right maxwidth100');
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['cp.date_debut']['checked'])) {
	print_liste_field_titre($arrayfields['cp.date_debut']['label'], $_SERVER["PHP_SELF"], "cp.date_debut", "", $param, '', $sortfield, $sortorder, 'center ');
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['cp.date_fin']['checked'])) {
	print_liste_field_titre($arrayfields['cp.date_fin']['label'], $_SERVER["PHP_SELF"], "cp.date_fin", "", $param, '', $sortfield, $sortorder, 'center ');
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['cp.date_valid']['checked'])) {
	print_liste_field_titre($arrayfields['cp.date_valid']['label'], $_SERVER["PHP_SELF"], "cp.date_valid", "", $param, '', $sortfield, $sortorder, 'center ');
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['cp.date_approval']['checked'])) {
	print_liste_field_titre($arrayfields['cp.date_approval']['label'], $_SERVER["PHP_SELF"], "cp.date_approval", "", $param, '', $sortfield, $sortorder, 'center ');
	$totalarray['nbfield']++;
}
// Extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
// Hook fields
$parameters = array('arrayfields' => $arrayfields, 'param' => $param, 'sortfield' => $sortfield, 'sortorder' => $sortorder, 'totalarray' => &$totalarray);
$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
if (!empty($arrayfields['cp.date_create']['checked'])) {
	print_liste_field_titre($arrayfields['cp.date_create']['label'], $_SERVER["PHP_SELF"], "cp.date_create", "", $param, '', $sortfield, $sortorder, 'center ');
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['cp.tms']['checked'])) {
	print_liste_field_titre($arrayfields['cp.tms']['label'], $_SERVER["PHP_SELF"], "cp.tms", "", $param, '', $sortfield, $sortorder, 'center ');
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['cp.statut']['checked'])) {
	print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "cp.statut", "", $param, '', $sortfield, $sortorder, 'center ');
	$totalarray['nbfield']++;
}
// Action column
if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
	print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n";
	$totalarray['nbfield']++;
}
print '</tr>'."\n";

$listhalfday = array('morning' => $langs->trans("Morning"), "afternoon" => $langs->trans("Afternoon"));


// Loop on record
// --------------------------------------------------------------------

// If we ask a dedicated card and not allow to see it, we force on user.
if ($id && !$user->hasRight('holiday', 'readall') && !in_array($id, $childids)) {
	$langs->load("errors");
	print '<tr class="oddeven opacitymedium"><td colspan="10">'.$langs->trans("NotEnoughPermissions").'</td></tr>';
	$result = 0;
} elseif ($num > 0 && !empty($mysoc->country_id)) {
	// Lines
	$userstatic = new User($db);
	$approbatorstatic = new User($db);

	$typeleaves = $object->getTypes(1, -1);

	$i = 0;
	$savnbfield = $totalarray['nbfield'];
	$totalarray = array();
	$totalarray['nbfield'] = 0;
	$totalduration = 0;
	$imaxinloop = ($limit ? min($num, $limit) : $num);
	while ($i < $imaxinloop) {
		$obj = $db->fetch_object($resql);
		if (empty($obj)) {
			break; // Should not happen
		}

		// Leave request
		$holidaystatic->id = $obj->rowid;
		$holidaystatic->ref = ($obj->ref ? $obj->ref : $obj->rowid);
		$holidaystatic->status = $obj->status;
		$holidaystatic->date_debut = $db->jdate($obj->date_debut);
		$holidaystatic->date_fin = $db->jdate($obj->date_fin);

		// User
		$userstatic->id = $obj->fk_user;
		$userstatic->lastname = $obj->user_lastname;
		$userstatic->firstname = $obj->user_firstname;
		$userstatic->admin = $obj->user_admin;
		$userstatic->email = $obj->user_email;
		$userstatic->login = $obj->user_login;
		$userstatic->status = $obj->user_status;
		$userstatic->photo = $obj->user_photo;

		// Validator
		$approbatorstatic->id = $obj->fk_validator;
		$approbatorstatic->lastname = $obj->validator_lastname;
		$approbatorstatic->firstname = $obj->validator_firstname;
		$approbatorstatic->admin = $obj->validator_admin;
		$approbatorstatic->email = $obj->validator_email;
		$approbatorstatic->login = $obj->validator_login;
		$approbatorstatic->status = $obj->validator_status;
		$approbatorstatic->photo = $obj->validator_photo;

		$date = $obj->date_create;
		$date_modif = $obj->date_modification;

		$starthalfday = ($obj->halfday == -1 || $obj->halfday == 2) ? 'afternoon' : 'morning';
		$endhalfday = ($obj->halfday == 1 || $obj->halfday == 2) ? 'morning' : 'afternoon';

		$nbopenedday = num_open_day($db->jdate($obj->date_debut, 1), $db->jdate($obj->date_fin, 1), 0, 1, $obj->halfday);	// user jdate(..., 1) because num_open_day need UTC dates
		$totalduration += $nbopenedday;

		if ($mode == 'kanban') {
			if ($i == 0) {
				print '<tr class="trkanban"><td colspan="'.$savnbfield.'">';
				print '<div class="box-flex-container kanban">';
			}

			$holidaystatic->fk_type = empty($typeleaves[$obj->fk_type]['rowid']) ? 0 : $typeleaves[$obj->fk_type]['rowid'];

			$arraydata = array();
			// Output Kanban
			if ($massactionbutton || $massaction) {
				$selected = 0;
				if (in_array($object->id, $arrayofselected)) {
					$selected = 1;
				}
				if (empty($typeleaves[$obj->fk_type])) {
					$labeltypeleavetoshow = $langs->trans("TypeWasDisabledOrRemoved", $obj->fk_type);
				} else {
					$labeltypeleavetoshow = ($langs->trans($typeleaves[$obj->fk_type]['code']) != $typeleaves[$obj->fk_type]['code'] ? $langs->trans($typeleaves[$obj->fk_type]['code']) : $typeleaves[$obj->fk_type]['label']);
				}

				$arraydata = array('user' => $userstatic, 'labeltype' => $labeltypeleavetoshow, 'selected' => $selected, 'nbopenedday' => $nbopenedday);
			}
			print $holidaystatic->getKanbanView('', $arraydata);
			if ($i == ($imaxinloop - 1)) {
				print '</div>';
				print '</td></tr>';
			}
		} else {
			// Show here line of result
			$j = 0;
			print '<tr data-rowid="'.$object->id.'" class="oddeven">';
			// Action column
			if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
				print '<td class="nowrap center">';
				if ($massactionbutton || $massaction) {   // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
					$selected = 0;
					if (in_array($obj->rowid, $arrayofselected)) {
						$selected = 1;
					}
					print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>';
				}
				print '</td>';
				if (!$i) {
					$totalarray['nbfield']++;
				}
			}
			if (!empty($arrayfields['cp.ref']['checked'])) {
				print '<td class="nowraponall">';
				print $holidaystatic->getNomUrl(1, 1);
				print '</td>';
				if (!$i) {
					$totalarray['nbfield']++;
				}
			}
			if (!empty($arrayfields['cp.fk_user']['checked'])) {
				print '<td class="tdoverflowmax125">'.$userstatic->getNomUrl(-1, 'leave').'</td>';
				if (!$i) {
					$totalarray['nbfield']++;
				}
			}
			if (!empty($arrayfields['cp.fk_validator']['checked'])) {
				print '<td class="tdoverflowmax125">'.$approbatorstatic->getNomUrl(-1).'</td>';
				if (!$i) {
					$totalarray['nbfield']++;
				}
			}
			if (!empty($arrayfields['cp.fk_type']['checked'])) {
				if (empty($typeleaves[$obj->fk_type])) {
					$labeltypeleavetoshow = $langs->trans("TypeWasDisabledOrRemoved", $obj->fk_type);
				} else {
					$labeltypeleavetoshow = ($langs->trans($typeleaves[$obj->fk_type]['code']) != $typeleaves[$obj->fk_type]['code'] ? $langs->trans($typeleaves[$obj->fk_type]['code']) : $typeleaves[$obj->fk_type]['label']);
				}

				print '<td class="tdoverflowmax100" title="'.dol_escape_htmltag($labeltypeleavetoshow).'">';
				print $labeltypeleavetoshow;
				print '</td>';
				if (!$i) {
					$totalarray['nbfield']++;
				}
			}
			if (!empty($arrayfields['duration']['checked'])) {
				print '<td class="right">';
				print $nbopenedday;
				//print ' '.$langs->trans('DurationDays');
				print '</td>';
				if (!$i) {
					$totalarray['nbfield']++;
				}
			}
			if (!empty($arrayfields['cp.date_debut']['checked'])) {
				print '<td class="center">';
				print dol_print_date($db->jdate($obj->date_debut), 'day');
				print ' <span class="opacitymedium nowraponall">('.$langs->trans($listhalfday[$starthalfday]).')</span>';
				print '</td>';
				if (!$i) {
					$totalarray['nbfield']++;
				}
			}
			if (!empty($arrayfields['cp.date_fin']['checked'])) {
				print '<td class="center">';
				print dol_print_date($db->jdate($obj->date_fin), 'day');
				print ' <span class="opacitymedium nowraponall">('.$langs->trans($listhalfday[$endhalfday]).')</span>';
				print '</td>';
				if (!$i) {
					$totalarray['nbfield']++;
				}
			}
			// Date validation
			if (!empty($arrayfields['cp.date_valid']['checked'])) {		// date_valid is both date_valid but also date_approval
				print '<td class="center" title="'.dol_print_date($db->jdate($obj->date_valid), 'dayhour').'">';
				print dol_print_date($db->jdate($obj->date_valid), 'day');
				print '</td>';
				if (!$i) {
					$totalarray['nbfield']++;
				}
			}
			// Date approval
			if (!empty($arrayfields['cp.date_approval']['checked'])) {
				print '<td class="center" title="'.dol_print_date($db->jdate($obj->date_approval), 'dayhour').'">';
				print dol_print_date($db->jdate($obj->date_approval), 'day');
				print '</td>';
				if (!$i) {
					$totalarray['nbfield']++;
				}
			}

			// Extra fields
			include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
			// Fields from hook
			$parameters = array('arrayfields' => $arrayfields, 'object' => $object, 'obj' => $obj, 'i' => $i, 'totalarray' => &$totalarray);
			$reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
			print $hookmanager->resPrint;

			// Date creation
			if (!empty($arrayfields['cp.date_create']['checked'])) {
				print '<td style="text-align: center;">'.dol_print_date($date, 'dayhour').'</td>';
				if (!$i) {
					$totalarray['nbfield']++;
				}
			}
			if (!empty($arrayfields['cp.tms']['checked'])) {
				print '<td style="text-align: center;">'.dol_print_date($date_modif, 'dayhour').'</td>';
				if (!$i) {
					$totalarray['nbfield']++;
				}
			}
			// Status
			if (!empty($arrayfields['cp.statut']['checked'])) {
				print '<td class="center nowrap">'.$holidaystatic->getLibStatut(5).'</td>';
				if (!$i) {
					$totalarray['nbfield']++;
				}
			}

			// Action column
			if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
				print '<td class="nowrap center">';
				if ($massactionbutton || $massaction) {   // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
					$selected = 0;
					if (in_array($obj->rowid, $arrayofselected)) {
						$selected = 1;
					}
					print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>';
				}
				print '</td>';
				if (!$i) {
					$totalarray['nbfield']++;
				}
			}

			print '</tr>'."\n";
		}
		$i++;
	}

	// Add a line for total if there is a total to show
	if ($mode != 'kanban' && !empty($arrayfields['duration']['checked'])) {
		print '<tr class="total">';
		if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
			print '<td></td>';
		}
		foreach ($arrayfields as $key => $val) {
			if (!empty($val['checked'])) {
				if ($key == 'duration') {
					print '<td class="right">'.$totalduration.' '.$langs->trans('DurationDays').'</td>';
				} else {
					print '<td></td>';
				}
			}
		}
		// status
		if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
			print '<td></td>';
		}
		print '</tr>';
	}
}

// If no record found
if ($num == 0) {
	$colspan = 1;
	foreach ($arrayfields as $key => $val) {
		if (!empty($val['checked'])) {
			$colspan++;
		}
	}
	print '<tr><td colspan="'.$colspan.'"><span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span></td></tr>';
}

$db->free($resql);

$parameters = array('arrayfields' => $arrayfields, 'sql' => $sql);
$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;

print '</table>'."\n";
print '</div>'."\n";

print '</form>'."\n";

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





/**
 * Show balance of user
 *
 * @param 	Holiday	$holiday	Object $holiday
 * @param	int		$user_id	User id
 * @return	string				Html code with balance
 */
function showMyBalance($holiday, $user_id)
{
	global $langs;

	//$alltypeleaves = $holiday->getTypes(1, -1); // To have labels

	$out = '';
	$nb_holiday = 0;
	$typeleaves = $holiday->getTypes(1, 1);
	foreach ($typeleaves as $key => $val) {
		$nb_type = $holiday->getCPforUser($user_id, $val['rowid']);
		$nb_holiday += $nb_type;
		$out .= ' - '.$val['label'].': <strong>'.($nb_type ? price2num($nb_type) : 0).'</strong><br>';
	}
	$out = $langs->trans('SoldeCPUser', (string) round($nb_holiday, 5)).'<br>'.$out;

	return $out;
}
