<?php
/* Copyright (C) 2026 Eduard Wisch <data@data-it-solution.de>
 * GPL v3+
 *
 * Liefert ein Beispiel-Lieferschein-PDF fuer den signature_box_editor.
 * Nur fuer eingeloggte Admins / bericht-admin Rechte.
 */

$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 __DIR__.'/../lib/bericht.lib.php';
require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';

if (!$user->admin && !$user->hasRight('bericht', 'admin')) accessforbidden();

$id = (int) GETPOST('id', 'int');
$template = GETPOST('template', 'alphanohtml');
if (!$id) { http_response_code(400); exit('id fehlt'); }

$shipment = new Expedition($db);
if ($shipment->fetch($id) <= 0) { http_response_code(404); exit('Lieferung nicht gefunden'); }
$shipment->fetch_thirdparty();

// Vorschau-PDF generieren mit dem ausgewaehlten Template — Overrides nur request-lokal
// (keine dolibarr_set_const, sonst persistieren wir DB-Konstanten ungewollt).
$pdf_path = null;
if ($template) {
    if (strpos($template, 'odt:') === 0) {
        // ODT-Datei aus doctemplates/shipments/ — generic_shipment_odt nimmt das erste ODT im konfigurierten Pfad.
        // Wir kopieren das gewuenschte ODT in einen tempo-Pfad und stellen den ODT_PATH request-lokal um.
        $odt_filename = substr($template, 4).'.odt';
        $odt_full = null;
        $raw_dirs = getDolGlobalString('EXPEDITION_ADDON_PDF_ODT_PATH', 'DOL_DATA_ROOT/doctemplates/shipments');
        foreach (explode(',', preg_replace('/[\r\n]+/', ',', trim($raw_dirs))) as $d) {
            $d = trim($d);
            if (!$d) continue;
            $d = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $d);
            if (file_exists($d.'/'.$odt_filename)) { $odt_full = $d.'/'.$odt_filename; break; }
        }
        if ($odt_full) {
            $tmp_tpl_dir = DOL_DATA_ROOT.'/bericht/temp/sigbox_tpl_'.uniqid();
            dol_mkdir($tmp_tpl_dir);
            @copy($odt_full, $tmp_tpl_dir.'/'.$odt_filename);

            // Nur in-memory overriden — schreibt NICHT in llx_const
            $old_path = $conf->global->EXPEDITION_ADDON_PDF_ODT_PATH ?? '';
            $conf->global->EXPEDITION_ADDON_PDF_ODT_PATH = $tmp_tpl_dir;
            try {
                $shipment->generateDocument('generic_shipment_odt', $langs);
            } catch (Throwable $e) {
                dol_syslog('signature_box_preview ODT: '.$e->getMessage(), LOG_ERR);
            }
            $conf->global->EXPEDITION_ADDON_PDF_ODT_PATH = $old_path;
            @unlink($tmp_tpl_dir.'/'.$odt_filename);
            @rmdir($tmp_tpl_dir);

            $pdf_path = bericht_get_shipment_pdf($db, $shipment);
        }
    } else {
        // PDF/ODT-Modul direkt
        try { $shipment->generateDocument($template, $langs); } catch (Throwable $e) {}
        $pdf_path = bericht_get_shipment_pdf($db, $shipment);
    }
} else {
    $pdf_path = bericht_get_shipment_pdf($db, $shipment);
}

if (!$pdf_path || !file_exists($pdf_path)) { http_response_code(404); exit('Lieferschein-PDF nicht verfuegbar'); }

header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="'.basename($pdf_path).'"');
header('Content-Length: '.filesize($pdf_path));
readfile($pdf_path);
exit;
