<?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    card.php
 * \ingroup importzugferd
 * \brief   Card page for ZUGFeRD import record
 */

// 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/class/html.formfile.class.php';
require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.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"));

// Get parameters
$id = GETPOST('id', 'int');
$ref = GETPOST('ref', 'alpha');
$action = GETPOST('action', 'aZ09');
$confirm = GETPOST('confirm', 'alpha');

// Initialize object
$object = new ZugferdImport($db);

// Load object
if ($id > 0 || !empty($ref)) {
    $result = $object->fetch($id, $ref);
    if ($result <= 0) {
        setEventMessages($langs->trans('RecordNotFound'), null, 'errors');
        header('Location: '.dol_buildpath('/importzugferd/list.php', 1));
        exit;
    }
}

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

$permissiontodelete = $user->hasRight('importzugferd', 'import', 'delete');

/*
 * Actions
 */

// Delete confirmation
if ($action == 'delete' && $confirm == 'yes' && $permissiontodelete) {
    $result = $object->delete($user);
    if ($result > 0) {
        setEventMessages($langs->trans('RecordDeleted'), null, 'mesgs');
        header('Location: '.dol_buildpath('/importzugferd/list.php', 1));
        exit;
    } else {
        setEventMessages($object->error, $object->errors, 'errors');
    }
}

/*
 * View
 */

$form = new Form($db);

$title = $langs->trans('ImportRecord').' - '.$object->ref;
llxHeader('', $title, '', '', 0, 0, '', '', '', 'mod-importzugferd page-card');

// Confirmation dialog for delete
if ($action == 'delete') {
    print $form->formconfirm(
        $_SERVER["PHP_SELF"].'?id='.$object->id,
        $langs->trans('DeleteImportRecord'),
        $langs->trans('ConfirmDeleteImportRecord', $object->ref),
        'delete',
        '',
        0,
        1
    );
}

// Header
print '<div class="fichecenter">';
print '<div class="underbanner clearboth"></div>';

print '<table class="border centpercent tableforfield">';

// Ref
print '<tr>';
print '<td class="titlefield">'.$langs->trans('Ref').'</td>';
print '<td>'.$object->ref.'</td>';
print '</tr>';

// Invoice number
print '<tr>';
print '<td>'.$langs->trans('InvoiceNumber').'</td>';
print '<td><strong>'.dol_escape_htmltag($object->invoice_number).'</strong></td>';
print '</tr>';

// Invoice date
print '<tr>';
print '<td>'.$langs->trans('InvoiceDate').'</td>';
print '<td>'.dol_print_date($object->invoice_date, 'day').'</td>';
print '</tr>';

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

// VAT ID
print '<tr>';
print '<td>'.$langs->trans('VATIntra').'</td>';
print '<td>'.dol_escape_htmltag($object->seller_vat).'</td>';
print '</tr>';

// Buyer reference
print '<tr>';
print '<td>'.$langs->trans('BuyerReference').'</td>';
print '<td>'.dol_escape_htmltag($object->buyer_reference).'</td>';
print '</tr>';

// Total HT
print '<tr>';
print '<td>'.$langs->trans('TotalHT').'</td>';
print '<td>'.price($object->total_ht).' '.$object->currency.'</td>';
print '</tr>';

// Total TTC
print '<tr>';
print '<td>'.$langs->trans('TotalTTC').'</td>';
print '<td><strong>'.price($object->total_ttc).' '.$object->currency.'</strong></td>';
print '</tr>';

// Supplier invoice
print '<tr>';
print '<td>'.$langs->trans('SupplierInvoice').'</td>';
print '<td>';
if ($object->fk_facture_fourn > 0) {
    $invoice = new FactureFournisseur($db);
    $invoice->fetch($object->fk_facture_fourn);
    print $invoice->getNomUrl(1);
} else {
    print '-';
}
print '</td>';
print '</tr>';

// Status
print '<tr>';
print '<td>'.$langs->trans('Status').'</td>';
print '<td>'.$object->getLibStatut(1).'</td>';
print '</tr>';

// Error message
if ($object->status == ZugferdImport::STATUS_ERROR && !empty($object->error_message)) {
    print '<tr>';
    print '<td>'.$langs->trans('ErrorMessage').'</td>';
    print '<td><span class="error">'.dol_escape_htmltag($object->error_message).'</span></td>';
    print '</tr>';
}

// PDF filename
print '<tr>';
print '<td>'.$langs->trans('File').'</td>';
print '<td>'.dol_escape_htmltag($object->pdf_filename).'</td>';
print '</tr>';

// Date creation
print '<tr>';
print '<td>'.$langs->trans('DateCreation').'</td>';
print '<td>'.dol_print_date($object->date_creation, 'dayhour').'</td>';
print '</tr>';

print '</table>';

print '</div>';

// Action buttons
print '<div class="tabsAction">';

// Reimport button - link to import page
print '<a class="butAction" href="'.dol_buildpath('/importzugferd/import.php', 1).'">'.$langs->trans('ImportAnother').'</a>';

// Delete button
if ($permissiontodelete) {
    print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&token='.newToken().'">'.$langs->trans('Delete').'</a>';
}

print '</div>';

// Show XML content (collapsed)
if (!empty($object->xml_content)) {
    // Format XML for better readability using class method
    $formattedXml = ZugferdImport::formatXmlForDisplay($object->xml_content);

    // XML Syntax-Highlighting
    $highlightedXml = dol_escape_htmltag($formattedXml);
    // Tag-Namen (oeffnend und schliessend)
    $highlightedXml = preg_replace('/(&lt;\/?)([\w:.-]+)/', '$1<span style="color:#2271b1;font-weight:bold;">$2</span>', $highlightedXml);
    // Attribut-Namen und -Werte
    $highlightedXml = preg_replace('/ ([\w:.-]+)(=)(&quot;)(.*?)(&quot;)/', ' <span style="color:#a83a32;">$1</span>$2<span style="color:#2e7d32;">$3$4$5</span>', $highlightedXml);

    print '<br>';
    print '<div class="div-table-responsive-no-min">';
    print '<table class="noborder centpercent">';
    print '<tr class="liste_titre">';
    print '<td colspan="2">'.$langs->trans('XMLContent').'</td>';
    print '</tr>';
    print '<tr class="oddeven">';
    print '<td colspan="2">';
    print '<a href="#" onclick="jQuery(\'#xmlcontent\').toggle(); return false;" class="butAction">'.$langs->trans('ClickToExpand').'</a>';
    print '<div id="xmlcontent" style="display: none; margin-top: 10px;">';
    print '<pre style="max-height: 600px; overflow: auto; background: #f8f9fa; padding: 12px; border: 1px solid #dee2e6; border-radius: 4px; font-size: 12px; line-height: 1.5; white-space: pre-wrap; word-wrap: break-word;">';
    print $highlightedXml;
    print '</pre>';
    print '</div>';
    print '</td>';
    print '</tr>';
    print '</table>';
    print '</div>';
}

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