<?php
/* Live-PDF-Vorschau eines Berichts.
 * Funktioniert wie generate_pdf, aber:
 *   - schreibt nach DOL_DATA_ROOT/bericht/temp/<id>/preview_<rand>.pdf
 *   - registriert NICHT in llx_ecm_files
 *   - ändert NICHT den Status des Berichts
 *   - liefert das PDF direkt im Response (Content-Type: application/pdf)
 *
 * GET/POST: berichtid, token
 */

if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1);

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

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

$berichtid = (int) (GETPOSTINT('berichtid'));
$bericht = new Bericht($db);
if ($bericht->fetch($berichtid) <= 0) { http_response_code(404); exit('Bericht nicht gefunden'); }

$parent = bericht_fetch_parent($db, $bericht->element_type, $bericht->fk_element);
if (!$parent) { http_response_code(404); exit('Parent nicht gefunden'); }

$pages = BerichtPage::fetchAllForBericht($db, $bericht->id);
if (empty($pages)) { http_response_code(400); exit('Bericht enthält keine Seiten'); }

// TCPDF + FPDI
$tcpdf_loaded = false;
foreach (array(
    DOL_DOCUMENT_ROOT.'/includes/tecnickcom/tcpdf/tcpdf.php',
    DOL_DOCUMENT_ROOT.'/includes/tcpdf/tcpdf.php',
) as $p) { if (file_exists($p)) { require_once $p; $tcpdf_loaded = true; break; } }
if (!$tcpdf_loaded) { http_response_code(500); exit('TCPDF nicht gefunden'); }

$fpdi_loaded = false;
foreach (array(
    DOL_DOCUMENT_ROOT.'/includes/setasign/vendor/setasign/fpdi/src/Tcpdf/Fpdi.php',
    DOL_DOCUMENT_ROOT.'/includes/fpdi/src/Tcpdf/Fpdi.php',
) as $p) { if (file_exists($p)) { require_once $p; $fpdi_loaded = true; break; } }

$ori = in_array($bericht->page_orientation, array('P','L'), true) ? $bericht->page_orientation : 'P';
$fmt = in_array($bericht->page_format, array('A4','A3','A5','Letter'), true) ? $bericht->page_format : 'A4';
require_once __DIR__.'/../class/berichtpdf.class.php';
if ($fpdi_loaded && class_exists('BerichtPdfFpdi')) {
    $pdf = new BerichtPdfFpdi($ori, 'mm', $fmt, true, 'UTF-8', false);
} else {
    $pdf = new BerichtPdf($ori, 'mm', $fmt, true, 'UTF-8', false);
}
$pdf->SetCreator('Dolibarr Bericht-Modul (Vorschau)');
$pdf->SetAuthor($user->getFullName($langs));
$pdf->SetTitle(($bericht->titel ?: $bericht->ref).' [Vorschau]');
global $mysoc;
$logo_path = '';
if (!empty($mysoc->logo) && isset($conf->mycompany->dir_output)) {
    $logo_path = $conf->mycompany->dir_output.'/logos/'.$mysoc->logo;
    if (!file_exists($logo_path)) $logo_path = '';
}
$pdf->berichtInit($bericht->titel ?: $bericht->ref, (isset($mysoc) && !empty($mysoc->name)) ? $mysoc->name : '', $logo_path);
$pdf->SetMargins(10, 30, 10);
$pdf->SetAutoPageBreak(true, 16);
$pdf->setPrintHeader(true);
$pdf->setPrintFooter(true);
$pdf->setHeaderMargin(5);
$pdf->setFooterMargin(10);

$tempdir = DOL_DATA_ROOT.'/bericht/temp/'.$berichtid;
if (!is_dir($tempdir)) dol_mkdir($tempdir);

// Deckblatt aus ODT
if (!empty($bericht->template_odt)) {
    $template_path = DOL_DATA_ROOT.'/bericht/templates/'.dol_sanitizeFileName($bericht->template_odt);
    if (file_exists($template_path) && function_exists('bericht_render_cover_for_preview')) {
        $cover_pdf = bericht_render_cover_for_preview($template_path, $bericht, $parent, $tempdir);
        if ($cover_pdf && file_exists($cover_pdf) && $fpdi_loaded) {
            $cp = $pdf->setSourceFile($cover_pdf);
            for ($n = 1; $n <= $cp; $n++) {
                $tpl = $pdf->importPage($n);
                $size = $pdf->getTemplateSize($tpl);
                $pdf->AddPage($size['orientation'] ?? 'P', array($size['width'], $size['height']));
                $pdf->useTemplate($tpl);
            }
        }
    }
}

// Seiten via gemeinsamer Render-Funktion
foreach ($pages as $page) {
    bericht_render_page_to_pdf($pdf, $page, $ori, $fmt, $fpdi_loaded);
}

// Direkt im Browser anzeigen — kein File schreiben, kein ECM
header('Content-Type: application/pdf');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Pragma: no-cache');
$pdf->Output('preview.pdf', 'I');
exit;
