<?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    datanorm_list.php
 * \ingroup importzugferd
 * \brief   List of Datanorm articles for a supplier
 */

// 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/class/html.form.class.php';
require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
require_once './class/datanorm.class.php';
require_once './lib/importzugferd.lib.php';

$langs->loadLangs(array('importzugferd@importzugferd', 'companies', 'products'));

// Access control
if (!$user->hasRight('importzugferd', 'datanorm', 'write')) {
    accessforbidden();
}

// Parameters
$fk_soc = GETPOSTINT('fk_soc');
$search_article = GETPOST('search_article', 'alpha');
$search_text = GETPOST('search_text', 'alpha');
$limit = GETPOSTINT('limit') ?: $conf->liste_limit;
$page = GETPOSTINT('page');
$offset = $limit * $page;
$sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma');

if (empty($sortfield)) {
    $sortfield = 'article_number';
}
if (empty($sortorder)) {
    $sortorder = 'ASC';
}

// Check supplier
if ($fk_soc <= 0) {
    header('Location: datanorm.php');
    exit;
}

$supplier = new Societe($db);
if ($supplier->fetch($fk_soc) <= 0) {
    header('Location: datanorm.php');
    exit;
}

// Objects
$form = new Form($db);
$datanorm = new Datanorm($db);

/*
 * View
 */

$title = $langs->trans('DatanormArticles').' - '.$supplier->name;
llxHeader('', $title, '', '', 0, 0, '', '', '', 'mod-importzugferd page-datanorm-list');

// Build SQL
$sql = "SELECT rowid, article_number, short_text1, short_text2, ean,";
$sql .= " manufacturer_ref, manufacturer_name, unit_code, price, price_unit,";
$sql .= " discount_group, product_group";
$sql .= " FROM ".MAIN_DB_PREFIX."importzugferd_datanorm";
$sql .= " WHERE fk_soc = ".(int)$fk_soc;
$sql .= " AND entity = ".(int)$conf->entity;
$sql .= " AND active = 1";

// Search filters
if (!empty($search_article)) {
    $sql .= " AND (article_number LIKE '%".$db->escape($search_article)."%'";
    $sql .= " OR ean LIKE '%".$db->escape($search_article)."%'";
    $sql .= " OR manufacturer_ref LIKE '%".$db->escape($search_article)."%')";
}
if (!empty($search_text)) {
    $sql .= " AND (short_text1 LIKE '%".$db->escape($search_text)."%'";
    $sql .= " OR short_text2 LIKE '%".$db->escape($search_text)."%')";
}

// Count total
$sqlcount = preg_replace('/^SELECT .* FROM/', 'SELECT COUNT(*) as nb FROM', $sql);
$resqlcount = $db->query($sqlcount);
$total = 0;
if ($resqlcount) {
    $objcount = $db->fetch_object($resqlcount);
    $total = $objcount->nb;
}

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

// Header with back link
$linkback = '<a href="datanorm.php">'.$langs->trans("Back").'</a>';
print load_fiche_titre($title, $linkback, 'fa-database');

// Search form
print '<form method="GET" action="'.$_SERVER['PHP_SELF'].'">';
print '<input type="hidden" name="fk_soc" value="'.$fk_soc.'">';

print '<div class="div-table-responsive-no-min">';
print '<table class="noborder centpercent">';

// Header row
print '<tr class="liste_titre">';
print_liste_field_titre('ArticleNumber', $_SERVER['PHP_SELF'], 'article_number', '', '&fk_soc='.$fk_soc, '', $sortfield, $sortorder);
print_liste_field_titre('Description', $_SERVER['PHP_SELF'], 'short_text1', '', '&fk_soc='.$fk_soc, '', $sortfield, $sortorder);
print_liste_field_titre('EAN', $_SERVER['PHP_SELF'], 'ean', '', '&fk_soc='.$fk_soc, '', $sortfield, $sortorder);
print_liste_field_titre('Manufacturer', $_SERVER['PHP_SELF'], 'manufacturer_name', '', '&fk_soc='.$fk_soc, '', $sortfield, $sortorder);
print_liste_field_titre('Price', $_SERVER['PHP_SELF'], 'price', '', '&fk_soc='.$fk_soc, 'class="right"', $sortfield, $sortorder);
print_liste_field_titre('Unit', $_SERVER['PHP_SELF'], 'unit_code', '', '&fk_soc='.$fk_soc, 'class="center"', $sortfield, $sortorder);
print '<td class="liste_titre"></td>';
print '</tr>';

// Search row
print '<tr class="liste_titre">';
print '<td><input type="text" name="search_article" value="'.dol_escape_htmltag($search_article).'" class="flat width150"></td>';
print '<td><input type="text" name="search_text" value="'.dol_escape_htmltag($search_text).'" class="flat width200"></td>';
print '<td></td>';
print '<td></td>';
print '<td></td>';
print '<td></td>';
print '<td class="center">';
print '<input type="submit" class="button small" value="'.$langs->trans('Search').'">';
print ' <a href="'.$_SERVER['PHP_SELF'].'?fk_soc='.$fk_soc.'" class="button small">'.$langs->trans('Reset').'</a>';
print '</td>';
print '</tr>';

// Data rows
$resql = $db->query($sql);
if ($resql) {
    $num = $db->num_rows($resql);
    $i = 0;

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

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

        // Article number
        print '<td class="nowrap">';
        print '<strong>'.dol_escape_htmltag($obj->article_number).'</strong>';
        print '</td>';

        // Description
        print '<td>';
        print dol_escape_htmltag($obj->short_text1);
        if (!empty($obj->short_text2)) {
            print '<br><span class="opacitymedium small">'.dol_escape_htmltag($obj->short_text2).'</span>';
        }
        print '</td>';

        // EAN
        print '<td>';
        if (!empty($obj->ean)) {
            print '<span class="opacitymedium"><i class="fas fa-barcode paddingright"></i></span>';
            print dol_escape_htmltag($obj->ean);
        }
        print '</td>';

        // Manufacturer
        print '<td>';
        if (!empty($obj->manufacturer_name)) {
            print dol_escape_htmltag($obj->manufacturer_name);
        }
        if (!empty($obj->manufacturer_ref)) {
            print '<br><span class="opacitymedium small">'.dol_escape_htmltag($obj->manufacturer_ref).'</span>';
        }
        print '</td>';

        // Price
        print '<td class="right nowrap">';
        $price = $obj->price;
        if ($obj->price_unit > 1) {
            print price($price).' / '.$obj->price_unit;
        } else {
            print price($price);
        }
        print '</td>';

        // Unit
        print '<td class="center">';
        print dol_escape_htmltag($obj->unit_code);
        print '</td>';

        // Actions placeholder
        print '<td class="center">';
        print '</td>';

        print '</tr>';

        $i++;
    }

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

    $db->free($resql);
} else {
    dol_print_error($db);
}

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

print '</form>';

// Pagination
print_barre_liste('', $page, $_SERVER['PHP_SELF'], '&fk_soc='.$fk_soc.'&search_article='.urlencode($search_article).'&search_text='.urlencode($search_text), $sortfield, $sortorder, '', $num, $total, '', 0, '', '', $limit);

// Stats
print '<br>';
print '<div class="opacitymedium">';
print $langs->trans('TotalArticles').': <strong>'.$total.'</strong>';
print '</div>';

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