<?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.
 */

include_once DOL_DOCUMENT_ROOT.'/core/boxes/modules_boxes.php';

/**
 * Dashboard widget showing pending bank transaction matches
 */
class box_bankimport_pending extends ModeleBoxes
{
	public $boxcode = "bankimport_pending";
	public $boximg = "fa-money-check-alt";
	public $boxlabel = "BoxBankImportPending";
	public $depends = array("bankimport");

	/**
	 * Constructor
	 *
	 * @param DoliDB $db  Database handler
	 * @param string $param  More parameters
	 */
	public function __construct($db, $param = '')
	{
		global $user;
		$this->db = $db;
		$this->hidden = !$user->hasRight('bankimport', 'read');
	}

	/**
	 * Load data into info_box_contents array to show on dashboard
	 *
	 * @param int $max  Maximum number of records to load
	 * @return void
	 */
	public function loadBox($max = 5)
	{
		global $user, $langs, $conf;

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

		$this->max = $max;

		// Box header
		$this->info_box_head = array(
			'text' => $langs->trans("BoxBankImportPending"),
			'sublink' => dol_buildpath('/bankimport/confirm.php', 1).'?mainmenu=bank&leftmenu=bankimport',
			'subtext' => $langs->trans("ReviewAndConfirm"),
			'subpicto' => 'payment',
		);

		$line = 0;
		$bankAccountId = getDolGlobalInt('BANKIMPORT_BANK_ACCOUNT_ID');

		if (empty($bankAccountId)) {
			// No bank account configured
			$this->info_box_contents[$line][] = array(
				'td' => 'class="center" colspan="4"',
				'text' => img_warning().' '.$langs->trans("NoBankAccountConfigured"),
				'url' => dol_buildpath('/bankimport/admin/setup.php', 1),
			);
			return;
		}

		// Count new (unmatched) transactions
		$sql = "SELECT COUNT(*) as cnt FROM ".MAIN_DB_PREFIX."bankimport_transaction";
		$sql .= " WHERE entity IN (".getEntity('banktransaction').")";
		$sql .= " AND status = 0";
		$resql = $this->db->query($sql);
		$newCount = 0;
		if ($resql) {
			$obj = $this->db->fetch_object($resql);
			$newCount = (int) $obj->cnt;
		}

		if ($newCount > 0) {
			// Summary line: X transactions pending
			$this->info_box_contents[$line][] = array(
				'td' => 'class="left" colspan="3"',
				'text' => '<strong>'.$langs->trans("PendingPaymentMatches", $newCount).'</strong>',
				'asis' => 1,
			);
			$this->info_box_contents[$line][] = array(
				'td' => 'class="right"',
				'text' => '<a class="butActionSmall" href="'.dol_buildpath('/bankimport/confirm.php', 1).'?mainmenu=bank&leftmenu=bankimport">'.$langs->trans("ReviewAndConfirm").'</a>',
				'asis' => 1,
			);
			$line++;

			// Show last few unmatched transactions
			$sql2 = "SELECT t.rowid, t.date_trans, t.name, t.amount, t.currency";
			$sql2 .= " FROM ".MAIN_DB_PREFIX."bankimport_transaction as t";
			$sql2 .= " WHERE t.entity IN (".getEntity('banktransaction').")";
			$sql2 .= " AND t.status = 0 AND t.amount > 0";
			$sql2 .= " ORDER BY t.date_trans DESC";
			$sql2 .= $this->db->plimit($max, 0);

			$resql2 = $this->db->query($sql2);
			if ($resql2) {
				$num = $this->db->num_rows($resql2);
				$i = 0;
				while ($i < $num && $line < $max + 1) {
					$obj2 = $this->db->fetch_object($resql2);
					if (!$obj2) {
						break;
					}

					// Date
					$this->info_box_contents[$line][] = array(
						'td' => 'class="nowraponall"',
						'text' => dol_print_date($this->db->jdate($obj2->date_trans), 'day'),
					);

					// Name
					$this->info_box_contents[$line][] = array(
						'td' => 'class="tdoverflowmax150"',
						'text' => dol_trunc($obj2->name, 28),
						'url' => dol_buildpath('/bankimport/card.php', 1).'?id='.$obj2->rowid.'&mainmenu=bank&leftmenu=bankimport',
					);

					// Amount
					$amountColor = $obj2->amount >= 0 ? 'color: green;' : 'color: red;';
					$amountPrefix = $obj2->amount >= 0 ? '+' : '';
					$this->info_box_contents[$line][] = array(
						'td' => 'class="right nowraponall"',
						'text' => '<span style="'.$amountColor.'">'.$amountPrefix.price($obj2->amount, 0, $langs, 1, -1, 2, $obj2->currency).'</span>',
						'asis' => 1,
					);

					// Status badge
					$this->info_box_contents[$line][] = array(
						'td' => 'class="right"',
						'text' => '<span class="badge badge-status4 badge-status">'.$langs->trans("New").'</span>',
						'asis' => 1,
					);

					$line++;
					$i++;
				}
			}
		} else {
			// No pending transactions
			$this->info_box_contents[$line][] = array(
				'td' => 'class="center opacitymedium" colspan="4"',
				'text' => $langs->trans("NoNewMatchesFound"),
			);
		}
	}

	/**
	 * Render the box
	 *
	 * @param array|null $head     Optional head array
	 * @param array|null $contents Optional contents array
	 * @param int        $nooutput No print, return output
	 * @return string
	 */
	public function showBox($head = null, $contents = null, $nooutput = 0)
	{
		return parent::showBox($this->info_box_head, $this->info_box_contents, $nooutput);
	}
}
