<?php
/* Copyright (C) 2001-2003	Rodolphe Quiedeville		<rodolphe@quiedeville.org>
 * Copyright (C) 2004-2020	Laurent Destailleur			<eldy@users.sourceforge.net>
 * Copyright (C) 2005-2009	Regis Houssin				<regis.houssin@inodbox.com>
 * Copyright (C) 2011-2024	Alexandre Spangaro			<alexandre@inovea-conseil.com>
 * Copyright (C) 2020		Tobias Sekan				<tobias.sekan@startmail.com>
 * Copyright (C) 2021		Gauthier VERDOL				<gauthier.verdol@atm-consulting.fr>
 * Copyright (C) 2024		MDW							<mdeweerd@users.noreply.github.com>
 * Copyright (C) 2024       Frédéric France         <frederic.france@free.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		htdocs/compta/tva/list.php
 *	\ingroup	tax
 *	\brief		List of VAT payments
 */

// Load Nube environment
require '../../main.inc.php';

require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
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', 'bills'));

$action     = GETPOST('action', 'aZ09') ? GETPOST('action', 'aZ09') : 'view'; // The action 'create'/'add', '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') : 'salestaxeslist';
$backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page
$optioncss = GETPOST('optioncss', 'alpha');
$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print')
$mode       = GETPOST('mode', 'aZ'); // The output mode ('list', 'kanban', 'hierarchy', 'calendar', ...)

$search_ref = GETPOST('search_ref', 'alpha');
$search_label = GETPOST('search_label', 'alpha');
$search_dateend_start = dol_mktime(0, 0, 0, GETPOSTINT('search_dateend_startmonth'), GETPOSTINT('search_dateend_startday'), GETPOSTINT('search_dateend_startyear'));
$search_dateend_end = dol_mktime(23, 59, 59, GETPOSTINT('search_dateend_endmonth'), GETPOSTINT('search_dateend_endday'), GETPOSTINT('search_dateend_endyear'));
$search_datepayment_start = dol_mktime(0, 0, 0, GETPOSTINT('search_datepayment_startmonth'), GETPOSTINT('search_datepayment_startday'), GETPOSTINT('search_datepayment_startyear'));
$search_datepayment_end = dol_mktime(23, 59, 59, GETPOSTINT('search_datepayment_endmonth'), GETPOSTINT('search_datepayment_endday'), GETPOSTINT('search_datepayment_endyear'));
$search_type = GETPOST('search_type', 'intcomma');
$search_account	= GETPOST('search_account', 'alpha');
$search_amount = GETPOST('search_amount', 'alpha');
$search_status = GETPOST('search_status', 'intcomma');

$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 = 't.datev';
}
if (!$sortorder) {
	$sortorder = 'DESC';
}

$arrayfields = array(
	't.rowid'			=> array('checked' => 1, 'position' => 10, 'label' => "Ref",),
	't.label'			=> array('checked' => 1, 'position' => 20, 'label' => "Label"),
	't.datev'			=> array('checked' => 1, 'position' => 30, 'label' => "PeriodEndDate"),
	't.fk_typepayment'	=> array('checked' => 1, 'position' => 50, 'label' => "DefaultPaymentMode"),
	't.amount'			=> array('checked' => 1, 'position' => 90, 'label' => "Amount"),
	't.datec'			=> array('checked' => 1, 'position' => 91, 'label' => "DateCreation"),
	't.status'			=> array('checked' => 1, 'position' => 92, 'label' => "Status"),
);

if (isModEnabled("bank")) {
	$arrayfields['t.fk_account'] = array('checked' => 1, 'position' => 60, 'label' => "DefaultBankAccount");
}

$arrayfields = dol_sort_array($arrayfields, 'position');
'@phan-var-force array<string,array{label:string,checked?:int<0,1>,position?:int,help?:string}> $arrayfields';  // dol_sort_array looses type for Phan

// Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
$hookmanager->initHooks(array('salestaxeslist'));
$object = new Tva($db);

$permissiontoadd = $user->hasRight('tax', 'charges', 'creer');
$permissiontodelete = $user->hasRight('tax', 'charges', 'supprimer');

// Security check
$socid = GETPOSTINT('socid');
if ($user->socid) {
	$socid = $user->socid;
}
$result = restrictedArea($user, 'tax', '', 'tva', 'charges');


/*
 * Actions
 */

$parameters = array('socid' => $socid);
$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';

	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // Both test are required to be compatible with all browsers
		$search_ref = '';
		$search_label = '';
		$search_dateend_start = '';
		$search_dateend_end = '';
		$search_datepayment_start = '';
		$search_datepayment_end = '';
		$search_type = '';
		$search_account = '';
		$search_amount = '';
		$search_status = '';
		$toselect = array();
		$search_array_options = array();
	}

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


/*
 * View
 */

$form = new Form($db);
$formother = new FormOther($db);
$formfile = new FormFile($db);
$tva_static = new Tva($db);
$bankstatic = new Account($db);
$accountingjournal = new AccountingJournal($db);
$bankline = new AccountLine($db);

$now = dol_now();

$title = $langs->trans("VATDeclarations");
//$help_url = "EN:Module_MyObject|FR:Module_MyObject_FR|ES:Módulo_MyObject";
$help_url = '';


// Build and execute select
// --------------------------------------------------------------------
$sql = 'SELECT t.rowid, t.amount, t.label, t.datec, t.datev, t.paye as status, t.fk_typepayment as type, t.fk_account,';
$sql .= ' ba.label as blabel, ba.ref as bref, ba.number as bnumber, ba.account_number, ba.iban_prefix as iban, ba.bic, ba.currency_code, ba.clos,';
$sql .= ' t.num_payment, pst.code as payment_code,';
$sql .= ' SUM(ptva.amount) as alreadypayed';

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

$sql .= ' FROM '.MAIN_DB_PREFIX.'tva as t';
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as pst ON (t.fk_typepayment = pst.id)';
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON (t.fk_account = ba.rowid)';
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."payment_vat as ptva ON (ptva.fk_tva = t.rowid)";
$sql .= ' WHERE t.entity IN ('.getEntity($object->element).')';

if (!empty($search_ref)) {
	$sql .= natural_search('t.rowid', $search_ref);
}
if (!empty($search_label)) {
	$sql .= natural_search('t.label', $search_label);
}
if (!empty($search_dateend_start)) {
	$sql .= " AND t.datev >= '".$db->idate($search_dateend_start)."'";
}
if (!empty($search_dateend_end)) {
	$sql .= " AND t.datev <= '".$db->idate($search_dateend_end)."'";
}
if (!empty($search_datepayment_start)) {
	$sql .= " AND t.datep >= '".$db->idate($search_datepayment_start)."'";
}
if (!empty($search_datepayment_end)) {
	$sql .= " AND t.datep <= '".$db->idate($search_datepayment_end)."'";
}
if (!empty($search_type) && $search_type > 0) {
	$sql .= ' AND t.fk_typepayment = '.((int) $search_type);
}
if (!empty($search_account) && $search_account > 0) {
	$sql .= ' AND t.fk_account = '.((int) $search_account);
}
if (!empty($search_amount)) {
	$sql .= natural_search('t.amount', price2num(trim($search_amount)), 1);
}
if ($search_status != '' && $search_status >= 0) {
	$sql .= " AND t.paye = ".((int) $search_status);
}

$sql .= " GROUP BY t.rowid, t.amount, t.label, t.datec, t.datev, t.paye, t.fk_typepayment, t.fk_account,";
$sql .= " ba.label, ba.ref, ba.number, ba.account_number, ba.iban_prefix, ba.bic, ba.currency_code, ba.clos, t.num_payment, pst.code";

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


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

llxHeader('', $title, $help_url, '', 0, 0, '', '', '', 'bodyforlist');

$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 (!empty($search_ref)) {
	$param .= '&search_ref="'.$search_ref.'"';
}
if (!empty($search_label)) {
	$param .= '&search_label="'.$search_label.'"';
}
if (!empty($search_dateend_start)) {
	$param .= '&search_dateend_startyear='.GETPOSTINT('search_dateend_startyear');
}
if (!empty($search_dateend_start)) {
	$param .= '&search_dateend_startmonth='.GETPOSTINT('search_dateend_startmonth');
}
if (!empty($search_dateend_start)) {
	$param .= '&search_dateend_startday='.GETPOSTINT('search_dateend_startday');
}
if (!empty($search_dateend_end)) {
	$param .= '&search_dateend_endyear='.GETPOSTINT('search_dateend_endyear');
}
if (!empty($search_dateend_end)) {
	$param .= '&search_dateend_endmonth='.GETPOSTINT('search_dateend_endmonth');
}
if (!empty($search_dateend_end)) {
	$param .= '&search_dateend_endday='.GETPOSTINT('search_dateend_endday');
}
if (!empty($search_datepayment_start)) {
	$param .= '&search_datepayment_startyear='.GETPOSTINT('search_datepayment_startyear');
}
if (!empty($search_datepayment_start)) {
	$param .= '&search_datepayment_startmonth='.GETPOSTINT('search_datepayment_startmonth');
}
if (!empty($search_datepayment_start)) {
	$param .= '&search_datepayment_startday='.GETPOSTINT('search_datepayment_startday');
}
if (!empty($search_datepayment_end)) {
	$param .= '&search_datepayment_endyear='.GETPOSTINT('search_datepayment_endyear');
}
if (!empty($search_datepayment_end)) {
	$param .= '&search_datepayment_endmonth='.GETPOSTINT('search_datepayment_endmonth');
}
if (!empty($search_datepayment_end)) {
	$param .= '&search_datepayment_endday='.GETPOSTINT('search_datepayment_endday');
}
if (!empty($search_type) && $search_type > 0) {
	$param .= '&search_type='.$search_type;
}
if (!empty($search_account) && $search_account > 0) {
	$param .= '&search_account='.$search_account;
}
if (!empty($search_amount)) {
	$param .= '&search_amount="'.$search_amount.'"';
}
if ($search_status != '' && $search_status != '-1') {
	$param .= '&search_status='.urlencode($search_status);
}

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

$moreforfilter = '';

print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">';
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="formfilteraction" id="formfilteraction" 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.'/compta/tva/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('NewVATPayment'), '', 'fa fa-plus-circle', $url, '', $permissiontoadd);

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

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

$varpage = empty($contextpage) ? $_SERVER['PHP_SELF'] : $contextpage;
$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage, getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')); // This also change content of $arrayfields
if ($massactionbutton) {
	$selectedfields .= $form->showCheckAddButtons('checkforselect', 1);
}

$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>';
}

// Filters: Lines (placeholder)
if (getDolGlobalString('MAIN_VIEW_LINE_NUMBER_IN_LIST')) {
	print '<td class="liste_titre">';
	print '</td>';
}

// Filter: Ref
if (!empty($arrayfields['t.rowid']['checked'])) {
	print '<td class="liste_titre">';
	print '<input type="text" class="flat" size="4" name="search_ref" value="'.dol_escape_htmltag($search_ref).'">';
	print '</td>';
}

// Filter: Label
if (!empty($arrayfields['t.label']['checked'])) {
	print '<td class="liste_titre">';
	print '<input type="text" class="flat" size="10" name="search_label" value="'.dol_escape_htmltag($search_label).'">';
	print '</td>';
}

// Filter: Date end period
if (!empty($arrayfields['t.datev']['checked'])) {
	print '<td class="liste_titre center">';
	print '<div class="nowrapfordate">';
	print $form->selectDate($search_dateend_start ? $search_dateend_start : -1, 'search_dateend_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("From"));
	print '</div>';
	print '<div class="nowrapfordate">';
	print $form->selectDate($search_dateend_end ? $search_dateend_end : -1, 'search_dateend_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to"));
	print '</div>';
	print '</td>';
}

// Filter: Date payment
/*if (!empty($arrayfields['t.datep']['checked'])) {
	print '<td class="liste_titre center">';
	print '<div class="nowrapfordate">';
 print $form->selectDate($search_datepayment_start ? $search_datepayment_start : -1, 'search_datepayment_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("From"));
	print '</div>';
	print '<div class="nowrapfordate">';
 print $form->selectDate($search_datepayment_end ? $search_datepayment_end : -1, 'search_datepayment_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to"));
	print '</div>';
	print '</td>';
}*/

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

// Filter: Bank Account
if (!empty($arrayfields['t.fk_account']['checked'])) {
	print '<td class="liste_titre left">';
	$form->select_comptes($search_account, 'search_account', 0, '', 1);
	print '</td>';
}

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

// Filter: Date creation
if (!empty($arrayfields['t.datec']['checked'])) {
	print '<td class="liste_titre right">';
	//print '<input name="search_amount" class="flat" type="text" size="8" value="'.$search_amount.'">';
	print '</td>';
}

// Status
if (!empty($arrayfields['t.status']['checked'])) {
	print '<td class="liste_titre right 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>';
}

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

// 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 (getDolGlobalString('MAIN_VIEW_LINE_NUMBER_IN_LIST')) {
	print_liste_field_titre('#', $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder);
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['t.rowid']['checked'])) {
	// False positive @phan-suppress-next-line PhanTypeInvalidDimOffset
	print_liste_field_titre($arrayfields['t.rowid']['label'], $_SERVER['PHP_SELF'], 't.rowid', '', $param, '', $sortfield, $sortorder);
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['t.label']['checked'])) {
	print_liste_field_titre($arrayfields['t.label']['label'], $_SERVER['PHP_SELF'], 't.label', '', $param, '', $sortfield, $sortorder);
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['t.datev']['checked'])) {
	print_liste_field_titre($arrayfields['t.datev']['label'], $_SERVER['PHP_SELF'], 't.datev', '', $param, '', $sortfield, $sortorder, 'center ');
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['t.fk_typepayment']['checked'])) {
	print_liste_field_titre($arrayfields['t.fk_typepayment']['label'], $_SERVER['PHP_SELF'], 't.fk_typepayment', '', $param, '', $sortfield, $sortorder, 'left ');
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['t.fk_account']['checked'])) {
	print_liste_field_titre($arrayfields['t.fk_account']['label'], $_SERVER['PHP_SELF'], 't.fk_account', '', $param, '', $sortfield, $sortorder, 'left ');
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['t.amount']['checked'])) {
	print_liste_field_titre($arrayfields['t.amount']['label'], $_SERVER['PHP_SELF'], 't.amount', '', $param, '', $sortfield, $sortorder, 'right ');
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['t.datec']['checked'])) {
	print_liste_field_titre($arrayfields['t.datec']['label'], $_SERVER['PHP_SELF'], 't.datec', '', $param, '', $sortfield, $sortorder, 'center ');
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['t.status']['checked'])) {
	print_liste_field_titre($arrayfields['t.status']['label'], $_SERVER["PHP_SELF"], "t.paye", "", $param, 'class="right"', $sortfield, $sortorder);
	$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);
$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";

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

	$tva_static->id = $obj->rowid;
	$tva_static->ref = $obj->rowid;
	$tva_static->label = $obj->label;
	$tva_static->type_payment = $obj->payment_code;
	$tva_static->datev = $obj->datev;
	$tva_static->date_creation = $obj->datec;
	$tva_static->amount = $obj->amount;
	$tva_static->paye = $obj->status;
	$tva_static->status = $obj->status;
	$object = $tva_static;

	if ($mode == 'kanban') {
		if ($i == 0) {
			print '<tr class="trkanban"><td colspan="'.$savnbfield.'">';
			print '<div class="box-flex-container kanban">';
		}
		// Output Kanban
		$selected = -1;
		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 $object->getKanbanView('', array('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']++;
			}
		}

		// No
		if (getDolGlobalString('MAIN_VIEW_LINE_NUMBER_IN_LIST')) {
			print '<td>'.(($offset * $limit) + $i).'</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}

		// Ref
		if (!empty($arrayfields['t.rowid']['checked'])) {
			print '<td>';
			print $tva_static->getNomUrl(1);
			$filename = dol_sanitizeFileName($tva_static->ref);
			$filedir = $conf->tax->dir_output.'/vat/'.dol_sanitizeFileName($tva_static->ref);
			$urlsource = $_SERVER['PHP_SELF'].'?id='.$tva_static->id;
			print $formfile->getDocumentsLink($tva_static->element, $filename, $filedir, '', 'valignmiddle paddingleft2imp');
			print '</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}

		// Label
		if (!empty($arrayfields['t.label']['checked'])) {
			print '<td>'.dol_trunc($obj->label, 40).'</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}

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

		// Date payment
		/*if 		// Buttons
		if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
			print '<td></td>';
		}(!empty($arrayfields['t.datep']['checked'])) {
			print '<td class="center">'.dol_print_date($db->jdate($obj->datep), 'day').'</td>';
			if (!$i) $totalarray['nbfield']++;
		}*/

		// Type
		if (!empty($arrayfields['t.fk_typepayment']['checked'])) {
			print '<td>';
			if (!empty($obj->payment_code)) {
				print $langs->trans("PaymentTypeShort".$obj->payment_code);
			}
			print '</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}

		// Account
		if (!empty($arrayfields['t.fk_account']['checked'])) {
			print '<td>';
			if ($obj->fk_account > 0) {
				$bankstatic->id = $obj->fk_account;
				$bankstatic->ref = $obj->bref;
				$bankstatic->number = $obj->bnumber;
				$bankstatic->iban = $obj->iban;
				$bankstatic->bic = $obj->bic;
				$bankstatic->currency_code = $langs->trans("Currency".$obj->currency_code);
				$bankstatic->account_number = $obj->account_number;
				$bankstatic->clos = $obj->clos;

				//$accountingjournal->fetch($obj->fk_accountancy_journal);
				//$bankstatic->accountancy_journal = $accountingjournal->getNomUrl(0, 1, 1, '', 1);

				$bankstatic->label = $obj->blabel;
				print $bankstatic->getNomUrl(1);
			}
			print '</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}

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

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

		if (!empty($arrayfields['t.status']['checked'])) {
			$totalallpayments = $obj->alreadypayed;
			// TODO Add deposit and credit notes

			print '<td class="nowrap right">' . $tva_static->getLibStatut(5, $totalallpayments) . '</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
			if (!empty($arrayfields['t.amount']['checked'])) {
				$totalarray['pos'][$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($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++;
		}
	}
	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();
