<?php
/* Copyright (C) 2011-2022  Alexandre Spangaro      <aspangaro@open-dsi.fr>
 * Copyright (C) 2015-2016  Laurent Destailleur     <eldy@users.sourceforge.net>
 * Copyright (C) 2015       Jean-François Ferry     <jfefe@aternatik.fr>
 * Copyright (C) 2021       Gauthier VERDOL         <gauthier.verdol@atm-consulting.fr>
 * Copyright (C) 2024-2025	MDW						<mdeweerd@users.noreply.github.com>
 * Copyright (C) 2024		Frédéric France			<frederic.france@free.fr>
 * Copyright (C) 2024 	    Nick Fragoulis
 *
 * 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/salaries/list.php
 *      \ingroup    salaries
 *		\brief     	List of salaries
 */

// Load Dolibarr environment
require '../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/salaries/class/paymentsalary.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
if (isModEnabled('accounting')) {
	require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.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("compta", "salaries", "bills", "hrm"));

$action = GETPOST('action', 'aZ09') ? GETPOST('action', 'aZ09') : 'view'; // 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') : str_replace('_', '', basename(dirname(__FILE__)).basename(__FILE__, '.php')); // To manage different context of search
$backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page
$optioncss  = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print')
$mode       = GETPOST('mode', 'aZ'); // The output mode ('list', 'kanban', 'hierarchy', 'calendar', ...)


// 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 < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) {
	// If $page is not defined, or '' or -1 or if we click on clear filters
	$page = 0;
}
$offset = $limit * $page;
$pageprev = $page - 1;
$pagenext = $page + 1;
if (!$sortfield) {
	$sortfield = "s.datep,s.rowid";
}
if (!$sortorder) {
	$sortorder = "DESC,DESC";
}

// Initialize technical objects
$object = new Salary($db);
$extrafields = new ExtraFields($db);
$diroutputmassaction = $conf->user->dir_output.'/temp/massgeneration/'.$user->id;
$hookmanager->initHooks(array('salarieslist')); // 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_');

if (!$sortfield) {
	$sortfield = "s.datep,s.rowid";
}
if (!$sortorder) {
	$sortorder = "DESC,DESC";
}

$search_ref = GETPOST('search_ref', 'alpha');
$search_user = GETPOST('search_user', 'alpha');
$search_label = GETPOST('search_label', 'alpha');
$search_date_start_from = dol_mktime(0, 0, 0, GETPOSTINT('search_date_start_frommonth'), GETPOSTINT('search_date_start_fromday'), GETPOSTINT('search_date_start_fromyear'));
$search_date_start_to = dol_mktime(23, 59, 59, GETPOSTINT('search_date_start_tomonth'), GETPOSTINT('search_date_start_today'), GETPOSTINT('search_date_start_toyear'));
$search_date_end_from = dol_mktime(0, 0, 0, GETPOSTINT('search_date_end_frommonth'), GETPOSTINT('search_date_end_fromday'), GETPOSTINT('search_date_end_fromyear'));
$search_date_end_to = dol_mktime(23, 59, 59, GETPOSTINT('search_date_end_tomonth'), GETPOSTINT('search_date_end_today'), GETPOSTINT('search_date_end_toyear'));
$search_amount = GETPOST('search_amount', 'alpha');
$search_account = GETPOST('search_account', 'alpha');
$search_status = GETPOST('search_status', 'intcomma');
$search_type_id = GETPOST('search_type_id', 'intcomma');

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

// Initialize array of search criteria
$search_all = GETPOST("search_all", 'alpha');
$search = array();
foreach ($object->fields as $key => $val) {
	if (GETPOST('search_'.$key, 'alpha') !== '') {
		$search[$key] = GETPOST('search_'.$key, 'alpha');
	}
	if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) {
		$search[$key.'_dtstart'] = dol_mktime(0, 0, 0, GETPOSTINT('search_'.$key.'_dtstartmonth'), GETPOSTINT('search_'.$key.'_dtstartday'), GETPOSTINT('search_'.$key.'_dtstartyear'));
		$search[$key.'_dtend'] = dol_mktime(23, 59, 59, GETPOSTINT('search_'.$key.'_dtendmonth'), GETPOSTINT('search_'.$key.'_dtendday'), GETPOSTINT('search_'.$key.'_dtendyear'));
	}
}

// List of fields to search into when doing a "search in all"
$fieldstosearchall = array();
foreach ($object->fields as $key => $val) {
	if (!empty($val['searchall'])) {
		$fieldstosearchall['s.'.$key] = $val['label'];
	}
}

// Definition of array of fields for columns
$arrayfields = array();
foreach ($object->fields as $key => $val) {
	// If $val['visible']==0, then we never show the field
	if (!empty($val['visible'])) {
		$visible = (int) dol_eval((string) $val['visible'], 1);
		$arrayfields['s.'.$key] = array(
			'label' => $val['label'],
			'checked' => (($visible < 0) ? 0 : 1),
			'enabled' => (abs($visible) != 3 && (bool) dol_eval($val['enabled'], 1)),
			'position' => $val['position'],
			'help' => isset($val['help']) ? $val['help'] : ''
		);
	}
}
// Extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php';

$object->fields = dol_sort_array($object->fields, 'position');
$arrayfields = dol_sort_array($arrayfields, 'position');

$permissiontoread = $user->hasRight('salaries', 'read');
$permissiontoadd = $user->hasRight('salaries', 'write');
$permissiontodelete = $user->hasRight('salaries', 'delete');

$error = 0;

// Security check
$socid = GETPOSTINT("socid");
if ($user->socid) {
	$socid = $user->socid;
}
restrictedArea($user, 'salaries', '', 'salary', '');


/*
 * Actions
 */

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

//credit transfer request
if ($massaction == 'withdrawrequest') {
	$langs->load("withdrawals");

	if (!$user->hasRight('paymentbybanktransfer', 'create')) {
		$error++;
		setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors');
	} else {
		//Checking error
		$error = 0;
		$listofSalries =  array();
		$arrayofselected = is_array($toselect) ? $toselect : array();
		foreach ($arrayofselected as $toselectid) {
			$objecttmp = new Salary($db);
			$result = $objecttmp->fetch($toselectid);
			if ($result > 0) {
				$totalpaid = (float) $objecttmp->getSommePaiement();
				$objecttmp->resteapayer = (float) price2num((float) $objecttmp->amount - $totalpaid, 'MT');

				// hook to finalize the remaining amount, considering e.g. cash discount agreements
				$parameters = array('remaintopay' => $objecttmp->resteapayer);
				$reshook = $hookmanager->executeHooks('finalizeAmountOfInvoice', $parameters, $objecttmp, $action); // Note that $action and $object may have been modified by some hooks
				if ($reshook > 0) {
					if (!empty($remaintopay = $hookmanager->resArray['remaintopay'])) {
						$objecttmp->resteapayer = $remaintopay;
					}
				} elseif ($reshook < 0) {
					$error++;
					setEventMessages($objecttmp->ref.' '.$langs->trans("ProcessingError"), $hookmanager->errors, 'errors');
				}

				if ($objecttmp->status == Salary::STATUS_PAID || $objecttmp->resteapayer == 0) {
					$error++;
					setEventMessages($langs->trans("Salary").' '.$objecttmp->ref.' : '.$langs->trans("AlreadyPaid"), $objecttmp->errors, 'errors');
				} elseif ($objecttmp->resteapayer < 0) {
					$error++;
					setEventMessages($langs->trans("Salary").' '.$objecttmp->ref.' : '.$langs->trans("AmountMustBePositive"), $objecttmp->errors, 'errors');
				}

				$rsql = "SELECT pfd.rowid, pfd.traite, pfd.date_demande as date_demande";
				$rsql .= " , pfd.date_traite as date_traite";
				$rsql .= " , pfd.amount";
				$rsql .= " , u.rowid as user_id, u.lastname, u.firstname, u.login";
				$rsql .= " FROM ".MAIN_DB_PREFIX."prelevement_demande as pfd";
				$rsql .= " , ".MAIN_DB_PREFIX."user as u";
				$rsql .= " WHERE fk_salary = ".((int) $objecttmp->id);
				$rsql .= " AND pfd.fk_user_demande = u.rowid";
				$rsql .= " AND pfd.traite = 0";
				$rsql .= " ORDER BY pfd.date_demande DESC";

				$numprlv = 0;
				$result_sql = $db->query($rsql);
				if ($result_sql) {
					$numprlv = $db->num_rows($result_sql);
				}

				if ($numprlv > 0) {
					//$error++;		// Not an error, a simple warning we can ignore
					setEventMessages($langs->trans("Salary").' '.$objecttmp->ref.' : '.$langs->trans("RequestAlreadyDone"), $objecttmp->errors, 'warnings');
				} elseif (!empty($objecttmp->type_payment_code) && $objecttmp->type_payment_code != 'VIR') {
					$langs->load("errors");
					$error++;
					setEventMessages($langs->trans("Salary").' '.$objecttmp->ref.' : '.$langs->trans("ErrorThisPaymentModeIsNotCreditTransfer"), $objecttmp->errors, 'errors');
				} else {
					$listofSalries[] = $objecttmp;
				}
			}
		}

		// Now process all record not in error
		if (!$error && !empty($listofSalries)) {
			$nbwithdrawrequestok = 0;
			foreach ($listofSalries as $salary) {
				$db->begin();
				$result = $salary->demande_prelevement($user, (float) $salary->resteapayer, 'salaire');
				if ($result > 0) {
					$db->commit();
					$nbwithdrawrequestok++;
				} else {
					$db->rollback();
					setEventMessages($salary->error, $salary->errors, 'errors');
				}
			}
			if ($nbwithdrawrequestok > 0) {
				setEventMessages($langs->trans("WithdrawRequestsDone", $nbwithdrawrequestok), null, 'mesgs');
			}
		}
	}
}

$parameters = array();
$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 test are required to be compatible with all browsers
		$search_ref = "";
		$search_user = "";
		$search_label = "";
		$search_date_start_from = '';
		$search_date_start_to = '';
		$search_date_end_from = '';
		$search_date_end_to = '';
		$search_date_end = '';
		$search_amount = "";
		$search_account = '';
		$search_status = '';
		$search_type_id = "";
	}
	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 = 'Salary';
	$objectlabel = 'Salaries';
	$uploaddir = $conf->salaries->dir_output;
	include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';

	// Validate records
	if (!$error && $massaction == 'buildsepa' && $permissiontoadd) {
		$objecttmp = new $objectclass($db);

		// TODO
	}
}

/*
 * View
 */

$form = new Form($db);
$salstatic = new Salary($db);
$userstatic = new User($db);
$accountstatic = new Account($db);

$now = dol_now();

$title = $langs->trans('Salaries');
//$help_url="EN:Module_BillOfMaterials|FR:Module_BillOfMaterials_FR|ES:Módulo_BillOfMaterials";
$help_url = '';
$morejs = array();
$morecss = array();

// Build and execute select
// --------------------------------------------------------------------
$sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.login, u.email, u.admin, u.photo, u.salary as current_salary, u.fk_soc as fk_soc, u.statut as status,";
$sql .= " s.rowid, s.fk_account, s.paye, s.fk_user, s.amount, s.salary, s.label, s.datesp, s.dateep, s.fk_typepayment as paymenttype, ";
$sql .= " ba.rowid as bid, ba.ref as bref, ba.number as bnumber, ba.account_number, ba.fk_accountancy_journal, ba.label as blabel, ba.iban_prefix as iban, ba.bic, ba.currency_code, ba.clos,";
$sql .= " pst.code as payment_code,";
$sql .= " SUM(ps.amount) as alreadypayed";
// 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, $object, $action); // Note that $action and $object may have been modified by hook
$sql .= $hookmanager->resPrint;
$sql = preg_replace('/,\s*$/', '', $sql);
//$sql .= ", COUNT(rc.rowid) as anotherfield";

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

$sql .= " FROM ".MAIN_DB_PREFIX."salary as s";
if (!empty($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 (s.rowid = ef.fk_object)";
}
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."payment_salary as ps ON (ps.fk_salary = s.rowid) ";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON (s.fk_typepayment = pst.id) ";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account ba ON (ba.rowid = s.fk_account), ";
//$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."payment_salary as ps ON ps.fk_salary = s.rowid, ";
$sql .= " ".MAIN_DB_PREFIX."user as u";
$sql .= " WHERE u.rowid = s.fk_user";
$sql .= " AND s.entity IN (".getEntity('salaries').")";
if (!$user->hasRight('salaries', 'readall')) {
	$sql .= " AND s.fk_user IN (".$db->sanitize(implode(',', $childids)).")";
}
//print $sql;

// Search criteria
if ($search_ref) {
	$sql .= " AND s.rowid=".((int) $search_ref);
}
if ($search_user) {
	$sql .= natural_search(array('u.login', 'u.lastname', 'u.firstname', 'u.email'), $search_user);
}
if ($search_label) {
	$sql .= natural_search(array('s.label'), $search_label);
}
if (!empty($search_date_start_from)) {
	$sql .= " AND s.datesp >= '".$db->idate($search_date_start_from)."'";
}
if (!empty($search_date_end_from)) {
	$sql .= " AND s.dateep >= '".$db->idate($search_date_end_from)."'";
}
if (!empty($search_date_start_to)) {
	$sql .= " AND s.datesp <= '".$db->idate($search_date_start_to)."'";
}
if (!empty($search_date_end_to)) {
	$sql .= " AND s.dateep <= '".$db->idate($search_date_end_to)."'";
}

if ($search_amount) {
	$sql .= natural_search("s.amount", $search_amount, 1);
}
if ($search_account > 0) {
	$sql .= " AND s.fk_account=".((int) $search_account);
}
if ($search_status != '' && $search_status >= 0) {
	$sql .= " AND s.paye = ".((int) $search_status);
}
if ($search_type_id) {
	$sql .= " AND s.fk_typepayment=".((int) $search_type_id);
}
// Add where from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
$sql .= " GROUP BY u.rowid, u.lastname, u.firstname, u.login, u.email, u.admin, u.photo, u.salary, u.fk_soc, u.statut,";
$sql .= " s.rowid, s.fk_account, s.paye, s.fk_user, s.amount, s.salary, s.label, s.datesp, s.dateep, s.fk_typepayment, s.fk_bank,";
$sql .= " ba.rowid, ba.ref, ba.number, ba.account_number, ba.fk_accountancy_journal, ba.label, ba.iban_prefix, ba.bic, ba.currency_code, ba.clos,";
$sql .= " pst.code";
// 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 : '');
	}
}

// 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);
}

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

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


// Direct jump if only one record found
if ($num == 1 && getDolGlobalString('MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE') && $search_all && !$page) {
	$obj = $db->fetch_object($resql);
	$id = $obj->rowid;
	header("Location: ".DOL_URL_ROOT.'/salaries/card.php?id='.$id);
	exit;
}


// Output page
// --------------------------------------------------------------------

llxHeader('', $title, $help_url, '', 0, 0, $morejs, $morecss, '', 'bodyforlist');	// Can use also classforhorizontalscrolloftabs instead of bodyforlist for no horizontal scroll

$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 ($search_type_id) {
	$param .= '&search_type_id='.urlencode($search_type_id);
}
if ($optioncss != '') {
	$param .= '&optioncss='.urlencode($optioncss);
}
if ($search_ref != '') {
	$param .= '&search_ref='.urlencode($search_ref);
}
if ($search_user != '') {
	$param .= '&search_user='.urlencode($search_user);
}
if ($search_label) {
	$param .= '&search_label='.urlencode($search_label);
}
if ($search_account) {
	$param .= '&search_account='.urlencode((string) ($search_account));
}
if ($search_status != '' && $search_status != '-1') {
	$param .= '&search_status='.urlencode($search_status);
}
if (!empty($search_date_start_from)) {
	$param .= '&search_date_start_fromday='.urlencode(GETPOST('search_date_start_fromday')).'&search_date_start_frommonth='.urlencode(GETPOST('search_date_start_frommonth')).'&search_date_start_fromyear='.urlencode(GETPOST('search_date_start_fromyear'));
}
if (!empty($search_date_start_to)) {
	$param .= "&search_date_start_today=".urlencode(GETPOST('search_date_start_today'))."&search_date_start_tomonth=".urlencode(GETPOST('search_date_start_tomonth'))."&search_date_start_toyear=".urlencode(GETPOST('search_date_start_toyear'));
}
if (!empty($search_date_end_from)) {
	$param .= '&search_date_end_fromday='.urlencode(GETPOST('search_date_end_fromday')).'&search_date_end_frommonth='.urlencode(GETPOST('search_date_end_frommonth')).'&search_date_end_fromyear='.urlencode(GETPOST('search_date_end_fromyear'));
}
if (!empty($search_date_end_to)) {
	$param .= "&search_date_end_today=".urlencode(GETPOST('search_date_end_today'))."&search_date_end_tomonth=".urlencode(GETPOST('search_date_end_tomonth'))."&search_date_end_toyear=".urlencode(GETPOST('search_date_end_toyear'));
}

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

// List of mass actions available
$arrayofmassactions = array(
	//'presend'=>img_picto('', 'email', 'class="pictofixedwidth"').$langs->trans("SendByMail"),
	//'buildsepa'=>img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("BuildSepa"),	// TODO
);
if (!empty($permissiontodelete)) {
	$arrayofmassactions['predelete'] = img_picto('', 'delete', 'class="pictofixedwidth"').$langs->trans("Delete");
}
if (isModEnabled('paymentbybanktransfer') && $user->hasRight('paymentbybanktransfer', 'create')) {
	$langs->load("withdrawals");
	$arrayofmassactions['withdrawrequest'] = img_picto('', 'payment', 'class="pictofixedwidth"').$langs->trans("MakeBankTransferOrder");
}
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="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="page_y" value="">';
print '<input type="hidden" name="mode" value="'.$mode.'">';


$url = DOL_URL_ROOT.'/salaries/card.php?action=create';
if (!empty($socid)) {
	$url .= '&socid='.$socid;
}

$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('NewSalary'), '', 'fa fa-plus-circle', $url, '', $permissiontoadd);

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

// Add code for pre mass action (confirmation or email presend form)
$topicmail = "SendSalaryRef";
$modelmail = "salary";
$objecttmp = new Salary($db);
$trackid = 'sal'.$object->id;
include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';

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

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>';
}
// Ref
if (!empty($arrayfields['s.ref']['checked'])) {
	print '<td class="liste_titre left">';
	print '<input class="flat width50" type="text" name="search_ref" value="'.$db->escape($search_ref).'">';
	print '</td>';
}

// Label
if (!empty($arrayfields['s.label']['checked'])) {
	print '<td class="liste_titre"><input type="text" class="flat width100" name="search_label" value="'.$db->escape($search_label).'"></td>';
}

// Date start
if (!empty($arrayfields['s.datesp']['checked'])) {
	print '<td class="liste_titre center">';
	print '<div class="nowrapfordate">';
	print $form->selectDate($search_date_start_from ? $search_date_start_from : -1, 'search_date_start_from', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From'));
	print '</div>';
	print '<div class="nowrapfordate">';
	print $form->selectDate($search_date_start_to ? $search_date_start_to : -1, 'search_date_start_to', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to'));
	print '</div>';
	print '</td>';
}

// Date End
if (!empty($arrayfields['s.dateep']['checked'])) {
	print '<td class="liste_titre center">';
	print '<div class="nowrapfordate">';
	print $form->selectDate($search_date_end_from ? $search_date_end_from : -1, 'search_date_end_from', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From'));
	print '</div>';
	print '<div class="nowrapfordate">';
	print $form->selectDate($search_date_end_to ? $search_date_end_to : -1, 'search_date_end_to', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to'));
	print '</div>';
	print '</td>';
}

// Employee
if (!empty($arrayfields['s.fk_user']['checked'])) {
	print '<td class="liste_titre">';
	print '<input class="flat" type="text" size="6" name="search_user" value="'.$db->escape($search_user).'">';
	print '</td>';
}

// Type
if (!empty($arrayfields['s.fk_typepayment']['checked'])) {
	print '<td class="liste_titre left">';
	print $form->select_types_paiements($search_type_id, 'search_type_id', '', 0, 1, 1, 16, 1, 'maxwidth125', 1);
	print '</td>';
}

// Bank account
if (isModEnabled("bank")) {
	if (!empty($arrayfields['s.fk_account']['checked'])) {
		print '<td class="liste_titre">';
		print $form->select_comptes($search_account, 'search_account', 0, '', 1, '', 0, 'maxwidth125', 1);
		print '</td>';
	}
}

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

// Amount
if (!empty($arrayfields['s.amount']['checked'])) {
	print '<td class="liste_titre right"><input name="search_amount" class="flat" type="text" size="8" value="'.$db->escape($search_amount).'"></td>';
}

// Status
if (!empty($arrayfields['s.paye']['checked'])) {
	print '<td class="liste_titre center parentonrightofpage">';
	$liststatus = array('0' => $langs->trans("Unpaid"), '1' => $langs->trans("Paid"));
	// @phan-suppress-next-line PhanPluginSuspiciousParamOrder
	print $form->selectarray('search_status', $liststatus, $search_status, 1, 0, 0, '', 0, 0, 0, '', 'search_status width100 onrightofpage');
	print '</td>';
}

// 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;
// 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">';
// Action column
if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
	print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n";
	$totalarray['nbfield']++;
}

if (!empty($arrayfields['s.ref']['checked'])) {
	print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "s.rowid", "", $param, "", $sortfield, $sortorder);
	$totalarray['nbfield']++;
}

if (!empty($arrayfields['s.label']['checked'])) {
	print_liste_field_titre("Label", $_SERVER["PHP_SELF"], "s.label", "", $param, '', $sortfield, $sortorder);
	$totalarray['nbfield']++;
}

if (!empty($arrayfields['s.datesp']['checked'])) {
	print_liste_field_titre("DateStart", $_SERVER["PHP_SELF"], "s.datesp,s.rowid", "", $param, '', $sortfield, $sortorder, 'center ');
	$totalarray['nbfield']++;
}

if (!empty($arrayfields['s.dateep']['checked'])) {
	print_liste_field_titre("DateEnd", $_SERVER["PHP_SELF"], "s.dateep,s.rowid", "", $param, '', $sortfield, $sortorder, 'center ');
	$totalarray['nbfield']++;
}

if (!empty($arrayfields['s.fk_user']['checked'])) {
	print_liste_field_titre("Employee", $_SERVER["PHP_SELF"], "u.lastname", "", $param, "", $sortfield, $sortorder);
	$totalarray['nbfield']++;
}

if (!empty($arrayfields['s.fk_typepayment']['checked'])) {
	print_liste_field_titre("DefaultPaymentMode", $_SERVER["PHP_SELF"], "type", "", $param, '', $sortfield, $sortorder);
	$totalarray['nbfield']++;
}

if (isModEnabled("bank")) {
	if (!empty($arrayfields['s.fk_account']['checked'])) {
		print_liste_field_titre("DefaultBankAccount", $_SERVER["PHP_SELF"], "ba.label", "", $param, "", $sortfield, $sortorder);
		$totalarray['nbfield']++;
	}
}

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

if (!empty($arrayfields['s.amount']['checked'])) {
	print_liste_field_titre("Amount", $_SERVER["PHP_SELF"], "s.amount", "", $param, '', $sortfield, $sortorder, 'right ');
	$totalarray['nbfield']++;
}

if (!empty($arrayfields['s.paye']['checked'])) {
	print_liste_field_titre('Status', $_SERVER["PHP_SELF"], "s.paye", '', $param, '', $sortfield, $sortorder, 'center ');
	$totalarray['nbfield']++;
}

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


// Detect if we need a fetch on each output line
$needToFetchEachLine = 0;
if (isset($extrafields->attributes[$object->table_element]['computed']) && is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) {
	foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) {
		if (!is_null($val) && preg_match('/\$object/', $val)) {
			$needToFetchEachLine++; // There is at least one compute field that use $object
		}
	}
}

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

	// Store properties in $object
	$object->setVarsFromFetchObj($obj);

	$userstatic->id = $obj->uid;
	$userstatic->lastname = $obj->lastname;
	$userstatic->firstname = $obj->firstname;
	$userstatic->admin = $obj->admin;
	$userstatic->login = $obj->login;
	$userstatic->email = $obj->email;
	$userstatic->socid = $obj->fk_soc;
	$userstatic->statut = $obj->status;		// deprecated
	$userstatic->status = $obj->status;
	$userstatic->photo = $obj->photo;

	$salstatic->id = $obj->rowid;
	$salstatic->ref = (string) $obj->rowid;
	$salstatic->label = $obj->label;
	$salstatic->paye = $obj->paye;
	$salstatic->status = $obj->paye;
	$salstatic->alreadypaid = $obj->alreadypayed;
	$salstatic->totalpaid = $obj->alreadypayed;
	$salstatic->datesp = $obj->datesp;
	$salstatic->dateep = $obj->dateep;
	$salstatic->amount = $obj->amount;
	$salstatic->type_payment = $obj->payment_code;

	if ($mode == 'kanban') {
		if ($i == 0) {
			print '<tr class="trkanban"><td colspan="'.$savnbfield.'">';
			print '<div class="box-flex-container kanban">';
		}
		// Output Kanban
		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($object->id, $arrayofselected)) {
				$selected = 1;
			}
		}
		print $salstatic->getKanbanView('', array('user' => $userstatic, 'selected' => $selected));
		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($object->id, $arrayofselected)) {
					$selected = 1;
				}
				print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>';
			}
			print '</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}

		// Ref
		if (!empty($arrayfields['s.ref']['checked'])) {
			print "<td>".$salstatic->getNomUrl(1)."</td>\n";
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}

		// Label payment
		if (!empty($arrayfields['s.label']['checked'])) {
			print '<td class="tdoverflowmax150" title="'.dol_escape_htmltag($obj->label).'">'.dol_escape_htmltag($obj->label)."</td>\n";
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}

		// Date Start
		if (!empty($arrayfields['s.datesp']['checked'])) {
			print '<td class="center">'.dol_print_date($db->jdate($obj->datesp), 'day')."</td>\n";
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}

		// Date End
		if (!empty($arrayfields['s.dateep']['checked'])) {
			print '<td class="center">'.dol_print_date($db->jdate($obj->dateep), 'day')."</td>\n";
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}

		// Employee
		if (!empty($arrayfields['s.fk_user']['checked'])) {
			print '<td class="tdoverflowmax150">'.$userstatic->getNomUrl(-1)."</td>\n";
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}

		// Payment mode
		if (!empty($arrayfields['s.fk_typepayment']['checked'])) {
			print '<td class="tdoverflowmax150" title="'.dol_escape_htmltag($langs->trans("PaymentTypeShort".$obj->payment_code)).'">';
			if (!empty($obj->payment_code)) {
				print $langs->trans("PaymentTypeShort".$obj->payment_code);
			}
			print '</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}

		// Account
		if (isModEnabled("bank")) {
			if (!empty($arrayfields['s.fk_account']['checked'])) {
				print '<td>';
				if ($obj->fk_account > 0) {
					//$accountstatic->fetch($obj->fk_bank);
					$accountstatic->id = $obj->bid;
					$accountstatic->ref = $obj->bref;
					$accountstatic->label = $obj->blabel;
					$accountstatic->number = $obj->bnumber;
					$accountstatic->iban = $obj->iban;
					$accountstatic->bic = $obj->bic;
					$accountstatic->currency_code = $langs->trans("Currency".$obj->currency_code);
					$accountstatic->account_number = $obj->account_number;
					$accountstatic->clos = $obj->clos;
					$accountstatic->status = $obj->clos;

					if (isModEnabled('accounting')) {
						$accountstatic->account_number = $obj->account_number;

						$accountingjournal = new AccountingJournal($db);
						$accountingjournal->fetch($obj->fk_accountancy_journal);

						$accountstatic->accountancy_journal = $accountingjournal->getNomUrl(0, 1, 1, '', 1);
					}
					//$accountstatic->label = $obj->blabel;
					print $accountstatic->getNomUrl(1);
				} else {
					print '&nbsp;';
				}
				print '</td>';
				if (!$i) {
					$totalarray['nbfield']++;
				}
			}
		}

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

		// Amount
		if (!empty($arrayfields['s.amount']['checked'])) {
			print '<td class="nowraponall right"><span class="amount">'.price($obj->amount).'</span></td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
			if (!$i) {
				$totalarray['pos'][$totalarray['nbfield']] = 'totalttcfield';
			}
			$totalarray['val']['totalttcfield'] += $obj->amount;
		}

		// Status
		if (!empty($arrayfields['s.paye']['checked'])) {
			print '<td class="nowraponall center">'.$salstatic->getLibStatut(5, $obj->alreadypayed).'</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}

		// 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;

		// 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($object->id, $arrayofselected)) {
					$selected = 1;
				}
				print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>';
			}
			print '</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}

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

// Show total line
include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php';


// If no record found
if ($num == 0) {
	/*$colspan = 1;
	foreach ($arrayfields as $key => $val) {
		if (!empty($val['checked'])) {
			$colspan++;
		}
	}*/
	$colspan = 9;
	if (isModEnabled("bank")) {
		$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();
