<?php
/* Copyright (C) 2026 ZUGFeRD Import Module
 *
 * 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    list.php
 * \ingroup importzugferd
 * \brief   List of imported ZUGFeRD invoices
 */

// 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 && 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';
require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';

dol_include_once('/importzugferd/class/zugferdimport.class.php');
dol_include_once('/importzugferd/lib/importzugferd.lib.php');

// Load translation files
$langs->loadLangs(array("importzugferd@importzugferd", "bills", "companies"));

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

// Get parameters
$action = GETPOST('action', 'aZ09');
$massaction = GETPOST('massaction', 'alpha');
$confirm = GETPOST('confirm', 'alpha');
$toselect = GETPOST('toselect', 'array');
$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'zugferdimportlist';

// Search parameters
$search_ref = GETPOST('search_ref', 'alpha');
$search_invoice_number = GETPOST('search_invoice_number', 'alpha');
$search_seller_name = GETPOST('search_seller_name', 'alpha');
$search_status = GETPOST('search_status', 'int');

$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) {
    $page = 0;
}
$offset = $limit * $page;
$pageprev = $page - 1;
$pagenext = $page + 1;

if (!$sortfield) {
    $sortfield = 'i.date_creation';
}
if (!$sortorder) {
    $sortorder = 'DESC';
}

// Initialize objects
$object = new ZugferdImport($db);
$form = new Form($db);
$formother = new FormOther($db);

/*
 * Actions
 */

if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) {
    $search_ref = '';
    $search_invoice_number = '';
    $search_seller_name = '';
    $search_status = '';
    $toselect = array();
}

/*
 * View
 */

$title = $langs->trans('ImportList');
llxHeader('', $title, '', '', 0, 0, '', '', '', 'mod-importzugferd page-list');

// Build SQL query
$sql = "SELECT i.rowid, i.ref, i.invoice_number, i.invoice_date, i.seller_name, i.seller_vat,";
$sql .= " i.buyer_reference, i.total_ht, i.total_ttc, i.currency, i.fk_soc, i.fk_facture_fourn,";
$sql .= " i.status, i.error_message, i.date_creation, i.pdf_filename,";
$sql .= " s.nom as supplier_name";
$sql .= " FROM ".MAIN_DB_PREFIX."importzugferd_import as i";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = i.fk_soc";
$sql .= " WHERE i.entity IN (".getEntity('importzugferd_import').")";

if (!empty($search_ref)) {
    $sql .= natural_search('i.ref', $search_ref);
}
if (!empty($search_invoice_number)) {
    $sql .= natural_search('i.invoice_number', $search_invoice_number);
}
if (!empty($search_seller_name)) {
    $sql .= natural_search('i.seller_name', $search_seller_name);
}
if ($search_status !== '' && $search_status >= 0) {
    $sql .= " AND i.status = ".(int)$search_status;
}

// Count total
$nbtotalofrecords = '';
if (!getDolGlobalInt('MAIN_DISABLE_FULL_SCANLIST')) {
    $sqlforcount = preg_replace('/^SELECT[^FROM]*FROM/', 'SELECT COUNT(*) as nbtotalofrecords FROM', $sql);
    $sqlforcount = preg_replace('/ORDER BY .*$/', '', $sqlforcount);
    $resqlforcount = $db->query($sqlforcount);
    if ($resqlforcount) {
        $objforcount = $db->fetch_object($resqlforcount);
        $nbtotalofrecords = $objforcount->nbtotalofrecords;
    }
    $db->free($resqlforcount);

    if (($page * $limit) > $nbtotalofrecords) {
        $page = 0;
        $offset = 0;
    }
}

$sql .= $db->order($sortfield, $sortorder);
$sql .= $db->plimit($limit + 1, $offset);

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

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

// List header
$param = '';
if (!empty($search_ref)) $param .= '&search_ref='.urlencode($search_ref);
if (!empty($search_invoice_number)) $param .= '&search_invoice_number='.urlencode($search_invoice_number);
if (!empty($search_seller_name)) $param .= '&search_seller_name='.urlencode($search_seller_name);
if ($search_status !== '') $param .= '&search_status='.urlencode($search_status);

print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'" name="formfilter">';
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.'">';

$newcardbutton = dolGetButtonTitle($langs->trans('Import'), '', 'fa fa-plus-circle', dol_buildpath('/importzugferd/import.php', 1));

print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'fa-file-import', 0, $newcardbutton);

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

// Header line
print '<tr class="liste_titre_filter">';
print '<td class="liste_titre"><input class="flat maxwidth75" type="text" name="search_ref" value="'.dol_escape_htmltag($search_ref).'"></td>';
print '<td class="liste_titre"><input class="flat maxwidth100" type="text" name="search_invoice_number" value="'.dol_escape_htmltag($search_invoice_number).'"></td>';
print '<td class="liste_titre"></td>';
print '<td class="liste_titre"><input class="flat maxwidth150" type="text" name="search_seller_name" value="'.dol_escape_htmltag($search_seller_name).'"></td>';
print '<td class="liste_titre"></td>';
print '<td class="liste_titre right"></td>';
print '<td class="liste_titre">';
$arrayofstatus = array(0 => $langs->trans('Imported'), 1 => $langs->trans('Processed'), 2 => $langs->trans('Error'), 3 => $langs->trans('StatusPending'));
print $form->selectarray('search_status', $arrayofstatus, $search_status, 1, 0, 0, '', 0, 0, 0, '', 'minwidth75');
print '</td>';
print '<td class="liste_titre"></td>';
print '<td class="liste_titre center">';
print '<input type="image" class="liste_titre" name="button_search" src="'.img_picto($langs->trans("Search"), 'search.png', '', '', 1).'" value="'.dol_escape_htmltag($langs->trans("Search")).'" title="'.dol_escape_htmltag($langs->trans("Search")).'">';
print '<input type="image" class="liste_titre" name="button_removefilter" src="'.img_picto($langs->trans("RemoveFilter"), 'searchclear.png', '', '', 1).'" value="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'" title="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'">';
print '</td>';
print '</tr>';

// Column headers
print '<tr class="liste_titre">';
print_liste_field_titre('Ref', $_SERVER["PHP_SELF"], 'i.ref', '', $param, '', $sortfield, $sortorder);
print_liste_field_titre('InvoiceNumber', $_SERVER["PHP_SELF"], 'i.invoice_number', '', $param, '', $sortfield, $sortorder);
print_liste_field_titre('InvoiceDate', $_SERVER["PHP_SELF"], 'i.invoice_date', '', $param, '', $sortfield, $sortorder);
print_liste_field_titre('Supplier', $_SERVER["PHP_SELF"], 'i.seller_name', '', $param, '', $sortfield, $sortorder);
print_liste_field_titre('SupplierInvoice', $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder);
print_liste_field_titre('TotalTTC', $_SERVER["PHP_SELF"], 'i.total_ttc', '', $param, '', $sortfield, $sortorder, 'right ');
print_liste_field_titre('Status', $_SERVER["PHP_SELF"], 'i.status', '', $param, '', $sortfield, $sortorder);
print_liste_field_titre('ValidationResult', $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder);
print_liste_field_titre('DateCreation', $_SERVER["PHP_SELF"], 'i.date_creation', '', $param, '', $sortfield, $sortorder, 'center ');
print '</tr>';

// Data rows
$i = 0;
while ($i < min($num, $limit)) {
    $obj = $db->fetch_object($resql);

    print '<tr class="oddeven">';

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

    // Invoice number
    print '<td>'.dol_escape_htmltag($obj->invoice_number).'</td>';

    // Invoice date
    print '<td>'.dol_print_date($db->jdate($obj->invoice_date), 'day').'</td>';

    // Seller/Supplier
    print '<td>';
    if ($obj->fk_soc > 0) {
        $supplier = new Societe($db);
        $supplier->fetch($obj->fk_soc);
        print $supplier->getNomUrl(1);
    } else {
        print '<span class="opacitymedium">'.dol_escape_htmltag($obj->seller_name).'</span>';
    }
    print '</td>';

    // Supplier invoice
    print '<td>';
    if ($obj->fk_facture_fourn > 0) {
        require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
        $invoice = new FactureFournisseur($db);
        $invoice->fetch($obj->fk_facture_fourn);
        print $invoice->getNomUrl(1);
    } else {
        print '-';
    }
    print '</td>';

    // Total TTC
    print '<td class="right nowraponall">'.price($obj->total_ttc).'</td>';

    // Status
    print '<td>';
    print $object->LibStatut($obj->status, 1);
    print '</td>';

    // Validation result / Error message
    print '<td class="tdoverflowmax200">';
    if ($obj->status == 2 && !empty($obj->error_message)) {
        // Error status - show error message in red
        print '<span class="error" title="'.dol_escape_htmltag($obj->error_message).'">';
        print '<i class="fas fa-exclamation-triangle paddingright"></i>';
        print dol_trunc(dol_escape_htmltag($obj->error_message), 40);
        print '</span>';
    } elseif ($obj->status == 1) {
        // Processed - show OK
        print '<span class="ok">';
        print '<i class="fas fa-check paddingright"></i>';
        print $langs->trans('SumValidationOk');
        print '</span>';
    } else {
        print '-';
    }
    print '</td>';

    // Date creation
    print '<td class="center">'.dol_print_date($db->jdate($obj->date_creation), 'dayhour').'</td>';

    print '</tr>';

    $i++;
}

if ($num == 0) {
    print '<tr class="oddeven"><td colspan="9" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>';
}

$db->free($resql);

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

print '</form>';

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