<?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.php
 * \ingroup importzugferd
 * \brief   Datanorm catalog management page
 */

// 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 DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
require_once './class/datanorm.class.php';
require_once './class/datanormparser.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
$action = GETPOST('action', 'aZ09');
$confirm = GETPOST('confirm', 'alpha');
$fk_soc = GETPOSTINT('fk_soc');
$id = GETPOSTINT('id');

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

/*
 * Actions
 */

// Upload Datanorm file
if ($action == 'upload' && !empty($_FILES['datanormfile']['name']) && $fk_soc > 0) {
    $error = 0;

    // Check supplier exists and is a supplier
    $supplier = new Societe($db);
    if ($supplier->fetch($fk_soc) <= 0 || $supplier->fournisseur != 1) {
        setEventMessages($langs->trans('ErrorSupplierNotFound'), null, 'errors');
        $error++;
    }

    if (!$error) {
        // Create upload directory
        $upload_dir = $conf->importzugferd->dir_output.'/datanorm/'.$fk_soc;
        if (!dol_is_dir($upload_dir)) {
            dol_mkdir($upload_dir);
        }

        // Handle file upload
        $uploaded_files = array();

        // Check if multiple files or single file
        if (is_array($_FILES['datanormfile']['name'])) {
            $file_count = count($_FILES['datanormfile']['name']);
            for ($i = 0; $i < $file_count; $i++) {
                if ($_FILES['datanormfile']['error'][$i] == UPLOAD_ERR_OK) {
                    $tmp_name = $_FILES['datanormfile']['tmp_name'][$i];
                    $name = $_FILES['datanormfile']['name'][$i];
                    $dest = $upload_dir.'/'.$name;

                    if (dol_move_uploaded_file($tmp_name, $dest, 1) > 0) {
                        $uploaded_files[] = $dest;
                    }
                }
            }
        } else {
            if ($_FILES['datanormfile']['error'] == UPLOAD_ERR_OK) {
                $tmp_name = $_FILES['datanormfile']['tmp_name'];
                $name = $_FILES['datanormfile']['name'];
                $dest = $upload_dir.'/'.$name;

                if (dol_move_uploaded_file($tmp_name, $dest, 1) > 0) {
                    $uploaded_files[] = $dest;
                }
            }
        }

        if (empty($uploaded_files)) {
            setEventMessages($langs->trans('ErrorUploadFailed'), null, 'errors');
            $error++;
        }
    }

    if (!$error && !empty($uploaded_files)) {
        // Use streaming import for large files (directory-based)
        $delete_existing = GETPOST('delete_existing', 'int') ? true : false;
        $imported = $datanorm->importFromDirectoryStreaming($user, $fk_soc, $upload_dir, $delete_existing);

        if ($imported > 0) {
            setEventMessages($langs->trans('DatanormImportSuccess', $imported), null, 'mesgs');
        } elseif ($imported == 0) {
            setEventMessages($langs->trans('DatanormNoArticlesFound'), null, 'warnings');
        } else {
            setEventMessages($langs->trans('DatanormImportFailed').': '.$datanorm->error, null, 'errors');
        }
    }
}

// Delete all articles for supplier
if ($action == 'delete' && $confirm == 'yes' && $fk_soc > 0) {
    $result = $datanorm->deleteAllBySupplier($user, $fk_soc);
    if ($result >= 0) {
        setEventMessages($langs->trans('DatanormDeleted', $result), null, 'mesgs');
    } else {
        setEventMessages($langs->trans('DatanormDeleteFailed').': '.$datanorm->error, null, 'errors');
    }
    $action = '';
}

/*
 * View
 */

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

print load_fiche_titre($title, '', 'fa-database');

// Confirmation dialog for delete
if ($action == 'delete' && $fk_soc > 0) {
    $supplier = new Societe($db);
    $supplier->fetch($fk_soc);

    $formconfirm = $form->formconfirm(
        $_SERVER["PHP_SELF"].'?fk_soc='.$fk_soc,
        $langs->trans('DeleteDatanorm'),
        $langs->trans('ConfirmDeleteDatanorm', $supplier->name),
        'delete',
        '',
        0,
        1
    );
    print $formconfirm;
}

// Upload form
print '<div class="fichecenter">';

print '<div class="div-table-responsive-no-min">';
print '<table class="noborder centpercent">';
print '<tr class="liste_titre">';
print '<td colspan="2">'.$langs->trans('UploadDatanorm').'</td>';
print '</tr>';

print '<tr class="oddeven">';
print '<td colspan="2">';

print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'" enctype="multipart/form-data">';
print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="action" value="upload">';

print '<table class="nobordernopadding">';

// Supplier selection
print '<tr>';
print '<td class="titlefield">'.$langs->trans('Supplier').' <span class="fieldrequired">*</span></td>';
print '<td>';
print $form->select_company($fk_soc, 'fk_soc', 's.fournisseur = 1', 1, 0, 0, array(), 0, 'minwidth300');
print '</td>';
print '</tr>';

// File upload
print '<tr>';
print '<td>'.$langs->trans('DatanormFiles').' <span class="fieldrequired">*</span></td>';
print '<td>';
print '<input type="file" name="datanormfile[]" multiple accept=".001,.002,.003,.004,.005,.wrg,.rab,.xml" class="flat">';
print '<br><span class="opacitymedium small">'.$langs->trans('DatanormFileHelp').'</span>';
print '</td>';
print '</tr>';

// Delete existing option
print '<tr>';
print '<td>'.$langs->trans('DeleteExisting').'</td>';
print '<td>';
print '<input type="checkbox" name="delete_existing" value="1" checked>';
print ' <span class="opacitymedium">'.$langs->trans('DeleteExistingHelp').'</span>';
print '</td>';
print '</tr>';

// Submit button
print '<tr>';
print '<td></td>';
print '<td>';
print '<input type="submit" class="button" value="'.$langs->trans('Upload').'">';
print '</td>';
print '</tr>';

print '</table>';
print '</form>';

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

print '<br>';

// List of suppliers with Datanorm data
$suppliers = $datanorm->getSuppliersWithData();

print '<div class="div-table-responsive-no-min">';
print '<table class="noborder centpercent">';
print '<tr class="liste_titre">';
print '<td>'.$langs->trans('Supplier').'</td>';
print '<td class="right">'.$langs->trans('ArticleCount').'</td>';
print '<td class="center">'.$langs->trans('LastImport').'</td>';
print '<td class="center">'.$langs->trans('Actions').'</td>';
print '</tr>';

if (!empty($suppliers)) {
    foreach ($suppliers as $sup) {
        print '<tr class="oddeven">';

        // Supplier name with link
        print '<td>';
        $supplier = new Societe($db);
        $supplier->fetch($sup['fk_soc']);
        print $supplier->getNomUrl(1, 'supplier');
        print '</td>';

        // Article count
        print '<td class="right">';
        print '<span class="badge badge-info">'.$sup['article_count'].'</span>';
        print '</td>';

        // Last import
        print '<td class="center">';
        print dol_print_date($sup['last_import'], 'dayhour');
        print '</td>';

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

        // View articles button
        print '<a class="paddingright" href="datanorm_list.php?fk_soc='.$sup['fk_soc'].'" title="'.$langs->trans('ViewArticles').'">';
        print img_picto($langs->trans('ViewArticles'), 'list');
        print '</a>';

        // Delete button
        print '<a class="paddingright" href="'.$_SERVER['PHP_SELF'].'?action=delete&fk_soc='.$sup['fk_soc'].'&token='.newToken().'" title="'.$langs->trans('Delete').'">';
        print img_picto($langs->trans('Delete'), 'delete');
        print '</a>';

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

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

print '</div>';

// Settings info
print '<br>';
print '<div class="info">';
print '<i class="fas fa-info-circle paddingright"></i>';
print $langs->trans('DatanormSettingsInfo');
print ' <a href="'.dol_buildpath('/importzugferd/admin/setup.php', 1).'">'.$langs->trans('Settings').'</a>';
print '</div>';

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