<?php
/* Copyright (C) 2026  Eduard Wisch  <data@data-it-solution.de>
 *
 * 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.
 */

/**
 * \file    bankimport/list.php
 * \ingroup bankimport
 * \brief   List page for imported bank transactions
 */

// Load Dolibarr environment
$res = 0;
if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) {
	$res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
}
$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME'];
$tmp2 = realpath(__FILE__);
$i = strlen($tmp) - 1;
$j = strlen($tmp2) - 1;
while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) {
	$i--;
	$j--;
}
if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) {
	$res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
}
if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) {
	$res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
}
if (!$res && file_exists("../main.inc.php")) {
	$res = @include "../main.inc.php";
}
if (!$res && file_exists("../../main.inc.php")) {
	$res = @include "../../main.inc.php";
}
if (!$res) {
	die("Include of main fails");
}

require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
dol_include_once('/bankimport/class/banktransaction.class.php');
dol_include_once('/bankimport/lib/bankimport.lib.php');

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

$langs->loadLangs(array("bankimport@bankimport", "banks", "bills"));

$action = GETPOST('action', 'aZ09');
$massaction = GETPOST('massaction', 'alpha');
$confirm = GETPOST('confirm', 'alpha');
$toselect = GETPOST('toselect', 'array');
$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'bankimporttransactionlist';

// Security check
if (!$user->hasRight('bankimport', 'read')) {
	accessforbidden();
}

// Search parameters
$search_ref = GETPOST('search_ref', 'alpha');
$search_iban = GETPOST('search_iban', 'alpha');
$search_name = GETPOST('search_name', 'alpha');
$search_description = GETPOST('search_description', 'alpha');
$search_amount_min = GETPOST('search_amount_min', 'alpha');
$search_amount_max = GETPOST('search_amount_max', 'alpha');
$search_status = GETPOST('search_status', 'intcomma');

// Date filter
$search_date_from = dol_mktime(0, 0, 0, GETPOSTINT('search_date_frommonth'), GETPOSTINT('search_date_fromday'), GETPOSTINT('search_date_fromyear'));
$search_date_to = dol_mktime(23, 59, 59, GETPOSTINT('search_date_tomonth'), GETPOSTINT('search_date_today'), GETPOSTINT('search_date_toyear'));

// Sorting
$sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma');
if (!$sortfield) $sortfield = 'date_trans';
if (!$sortorder) $sortorder = 'DESC';

// Pagination
$limit = GETPOSTINT('limit') ? GETPOSTINT('limit') : $conf->liste_limit;
$page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT('page');
if (empty($page) || $page < 0) $page = 0;
$offset = $limit * $page;

/*
 * Actions
 */

// Reset search
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) {
	$search_ref = '';
	$search_iban = '';
	$search_name = '';
	$search_description = '';
	$search_amount_min = '';
	$search_amount_max = '';
	$search_status = '';
	$search_date_from = '';
	$search_date_to = '';
	$toselect = array();
}

/*
 * View
 */

$form = new Form($db);
$transaction = new BankImportTransaction($db);

$title = $langs->trans("TransactionList");
llxHeader('', $title, '', '', 0, 0, '', '', '', 'mod-bankimport page-list');

print load_fiche_titre($title, '', 'bank');

// Build filter array
$filter = array();
if (!empty($search_ref)) $filter['ref'] = $search_ref;
if (!empty($search_iban)) $filter['iban'] = $search_iban;
if (!empty($search_name)) $filter['name'] = $search_name;
if (!empty($search_description)) $filter['description'] = $search_description;
if (!empty($search_amount_min)) $filter['amount_min'] = price2num($search_amount_min);
if (!empty($search_amount_max)) $filter['amount_max'] = price2num($search_amount_max);
if ($search_status !== '' && $search_status >= 0) $filter['status'] = (int) $search_status;
if (!empty($search_date_from)) $filter['date_from'] = $search_date_from;
if (!empty($search_date_to)) $filter['date_to'] = $search_date_to;

// Count total
$totalRecords = $transaction->fetchAll('', '', 0, 0, $filter, 'count');

// Fetch records
$records = $transaction->fetchAll($sortfield, $sortorder, $limit, $offset, $filter);

// Form
$param = '';
if (!empty($search_ref)) $param .= '&search_ref='.urlencode($search_ref);
if (!empty($search_iban)) $param .= '&search_iban='.urlencode($search_iban);
if (!empty($search_name)) $param .= '&search_name='.urlencode($search_name);
if (!empty($search_description)) $param .= '&search_description='.urlencode($search_description);
if (!empty($search_amount_min)) $param .= '&search_amount_min='.urlencode($search_amount_min);
if (!empty($search_amount_max)) $param .= '&search_amount_max='.urlencode($search_amount_max);
if ($search_status !== '' && $search_status >= 0) $param .= '&search_status='.urlencode($search_status);
if (!empty($search_date_from)) {
	$param .= '&search_date_fromday='.dol_print_date($search_date_from, '%d');
	$param .= '&search_date_frommonth='.dol_print_date($search_date_from, '%m');
	$param .= '&search_date_fromyear='.dol_print_date($search_date_from, '%Y');
}
if (!empty($search_date_to)) {
	$param .= '&search_date_today='.dol_print_date($search_date_to, '%d');
	$param .= '&search_date_tomonth='.dol_print_date($search_date_to, '%m');
	$param .= '&search_date_toyear='.dol_print_date($search_date_to, '%Y');
}

print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'" name="formulaire">';
print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';

// Navigation
print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', is_array($records) ? count($records) : 0, $totalRecords, '', 0, '', '', $limit);

print '<div class="div-table-responsive">';
print '<table class="tagtable liste listwithfilterbefore centpercent">';

// Header row with filters
print '<tr class="liste_titre_filter">';

// Ref
print '<td class="liste_titre">';
print '<input type="text" class="flat maxwidth75" name="search_ref" value="'.dol_escape_htmltag($search_ref).'">';
print '</td>';

// IBAN
print '<td class="liste_titre">';
print '<input type="text" class="flat maxwidth100" name="search_iban" value="'.dol_escape_htmltag($search_iban).'">';
print '</td>';

// Date
print '<td class="liste_titre center">';
print '<div class="nowraponall">';
print $form->selectDate($search_date_from, 'search_date_from', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("From"));
print '</div>';
print '<div class="nowraponall">';
print $form->selectDate($search_date_to, 'search_date_to', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("To"));
print '</div>';
print '</td>';

// Name
print '<td class="liste_titre">';
print '<input type="text" class="flat maxwidth150" name="search_name" value="'.dol_escape_htmltag($search_name).'">';
print '</td>';

// Description
print '<td class="liste_titre">';
print '<input type="text" class="flat maxwidth200" name="search_description" value="'.dol_escape_htmltag($search_description).'">';
print '</td>';

// Amount
print '<td class="liste_titre right">';
print '<input type="text" class="flat maxwidth50" name="search_amount_min" placeholder="Min" value="'.dol_escape_htmltag($search_amount_min).'">';
print ' - ';
print '<input type="text" class="flat maxwidth50" name="search_amount_max" placeholder="Max" value="'.dol_escape_htmltag($search_amount_max).'">';
print '</td>';

// Statement
print '<td class="liste_titre">';
print '</td>';

// Status
print '<td class="liste_titre center">';
$statusArray = array(
	'' => $langs->trans("AllStatuses"),
	'0' => $langs->trans("StatusNew"),
	'1' => $langs->trans("StatusMatched"),
	'2' => $langs->trans("StatusReconciled"),
	'9' => $langs->trans("StatusIgnored")
);
print $form->selectarray('search_status', $statusArray, $search_status, 0, 0, 0, '', 0, 0, 0, '', 'minwidth100');
print '</td>';

// Action buttons
print '<td class="liste_titre center">';
print '<input type="image" class="liste_titre" src="'.img_picto('', 'search.png', '', 0, 1).'" name="button_search" value="'.dol_escape_htmltag($langs->trans("Search")).'" title="'.dol_escape_htmltag($langs->trans("Search")).'">';
print '&nbsp;';
print '<input type="image" class="liste_titre" src="'.img_picto('', 'searchclear.png', '', 0, 1).'" name="button_removefilter" value="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'" title="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'">';
print '</td>';

print '</tr>';

// Header titles
print '<tr class="liste_titre">';
print_liste_field_titre($langs->trans("TransactionRef"), $_SERVER["PHP_SELF"], "ref", "", $param, "", $sortfield, $sortorder);
print_liste_field_titre($langs->trans("AccountIBAN"), $_SERVER["PHP_SELF"], "iban", "", $param, "", $sortfield, $sortorder);
print_liste_field_titre($langs->trans("Date"), $_SERVER["PHP_SELF"], "date_trans", "", $param, 'class="center"', $sortfield, $sortorder);
print_liste_field_titre($langs->trans("Counterparty"), $_SERVER["PHP_SELF"], "name", "", $param, "", $sortfield, $sortorder);
print_liste_field_titre($langs->trans("Description"), $_SERVER["PHP_SELF"], "description", "", $param, "", $sortfield, $sortorder);
print_liste_field_titre($langs->trans("Amount"), $_SERVER["PHP_SELF"], "amount", "", $param, 'class="right"', $sortfield, $sortorder);
print_liste_field_titre($langs->trans("PDFStatement"), $_SERVER["PHP_SELF"], "fk_statement", "", $param, 'class="center"', $sortfield, $sortorder);
print_liste_field_titre($langs->trans("Status"), $_SERVER["PHP_SELF"], "status", "", $param, 'class="center"', $sortfield, $sortorder);
print_liste_field_titre('', $_SERVER["PHP_SELF"], "", "", $param, 'class="center"', $sortfield, $sortorder);
print '</tr>';

// Data rows
if (is_array($records) && count($records) > 0) {
	foreach ($records as $obj) {
		print '<tr class="oddeven">';

		// Ref
		print '<td class="nowraponall">';
		print '<a href="'.dol_buildpath('/bankimport/card.php', 1).'?id='.$obj->id.'">'.dol_escape_htmltag($obj->ref).'</a>';
		print '</td>';

		// IBAN
		print '<td class="nowraponall">';
		print dol_escape_htmltag(dol_trunc($obj->iban, 20));
		print '</td>';

		// Date
		print '<td class="center nowraponall">';
		print dol_print_date($obj->date_trans, 'day');
		print '</td>';

		// Name
		print '<td>';
		print dol_escape_htmltag($obj->name);
		print '</td>';

		// Description
		print '<td class="small">';
		print dol_escape_htmltag(dol_trunc($obj->description, 60));
		print '</td>';

		// Amount
		print '<td class="right nowraponall">';
		if ($obj->amount >= 0) {
			print '<span style="color: green;">+'.price($obj->amount, 0, $langs, 1, -1, 2, $obj->currency).'</span>';
		} else {
			print '<span style="color: red;">'.price($obj->amount, 0, $langs, 1, -1, 2, $obj->currency).'</span>';
		}
		print '</td>';

		// Statement link
		print '<td class="center nowraponall">';
		if (!empty($obj->fk_statement)) {
			print '<a href="'.dol_buildpath('/bankimport/pdfstatements.php', 1).'?action=view&id='.$obj->fk_statement.'&token='.newToken().'" target="_blank" title="'.$langs->trans("ViewPDFStatement").'">';
			print img_picto($langs->trans("ViewPDFStatement"), 'pdf');
			print '</a>';
		}
		print '</td>';

		// Status
		print '<td class="center">';
		print $obj->getLibStatut(5);
		print '</td>';

		// Actions
		print '<td class="center nowraponall">';
		print '<a href="'.dol_buildpath('/bankimport/card.php', 1).'?id='.$obj->id.'">'.img_edit().'</a>';
		print '</td>';

		print '</tr>';
	}
} else {
	print '<tr class="oddeven"><td colspan="9" class="opacitymedium center">';
	print $langs->trans("NoTransactionsInDatabase");
	print '</td></tr>';
}

print '</table>';
print '</div>';

print '</form>';

// Buttons
print '<div class="tabsAction">';
print '<a class="butAction" href="'.dol_buildpath('/bankimport/statements.php', 1).'">'.$langs->trans("FetchStatements").'</a>';
print '</div>';

llxFooter();
$db->close();
