<?php
/* GET /api/pdf.php?id=<bericht_id>
 *   Liefert das finale PDF eines Berichts zur Anzeige/Download.
 *   Auth über das awl_sso-Cookie (same-origin).
 *   Wenn noch kein final_pdf_path existiert oder die Datei fehlt,
 *   wird direkt eine temporäre Vorschau generiert (wie preview_pdf.php).
 */
if (!defined('NOLOGIN'))     define('NOLOGIN', '1');
if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1');
if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1');
if (!defined('NOREQUIREMENU'))  define('NOREQUIREMENU', '1');
if (!defined('NOREQUIREHTML'))  define('NOREQUIREHTML', '1');
if (!defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX', '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 __DIR__.'/../class/bericht.class.php';
require_once __DIR__.'/../lib/bericht.lib.php';

// Auth über das zentrale SSO-Cookie awl_sso. awlauth_verify (OHNE CSRF), weil
// dieser reine GET-Read auch per window.location/<object> geladen wird.
if (!dol_include_once('/awlauth/lib/awlauth.lib.php') || !function_exists('awlauth_verify')) {
    http_response_code(500);
    header('Content-Type: text/plain');
    echo 'SSO-Modul (awlauth) nicht verfügbar';
    exit;
}
$user = awlauth_verify();
if (!$user || !$user->hasRight('bericht', 'read')) {
    http_response_code(401);
    header('Content-Type: text/plain');
    echo 'Nicht angemeldet';
    exit;
}

$id = (int) ($_GET['id'] ?? 0);
if (!$id) { http_response_code(400); exit; }

$bericht = new Bericht($db);
if ($bericht->fetch($id) <= 0) { http_response_code(404); exit; }

// Fertiges PDF ausliefern wenn vorhanden
if ($bericht->final_pdf_path) {
    $full = bericht_resolve_data_path($bericht->final_pdf_path);
    if ($full && file_exists($full)) {
        header('Content-Type: application/pdf');
        header('Content-Length: '.filesize($full));
        header('Cache-Control: private, max-age=60');
        readfile($full);
        exit;
    }
}

// Sonst: on-the-fly Vorschau (wie preview_pdf.php)
$parent = bericht_fetch_parent($db, $bericht->element_type, $bericht->fk_element);
if (!$parent) { http_response_code(404); exit; }
$pages = BerichtPage::fetchAllForBericht($db, $bericht->id);
if (empty($pages)) { http_response_code(400); exit; }

$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; }

$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';
$pdf = ($fpdi_loaded && class_exists('BerichtPdfFpdi'))
    ? new BerichtPdfFpdi($ori, 'mm', $fmt, true, 'UTF-8', false)
    : new BerichtPdf($ori, 'mm', $fmt, true, 'UTF-8', false);

global $mysoc, $conf;
$pdf->SetCreator('Dolibarr Bericht (PWA Vorschau)');
$pdf->SetAuthor($user->getFullName($langs ?? null));
$pdf->SetTitle($bericht->titel ?: $bericht->ref);
$logo_path = !empty($mysoc->logo) ? $conf->mycompany->dir_output.'/logos/'.$mysoc->logo : '';
$pdf->berichtInit($bericht->titel ?: $bericht->ref, $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);

foreach ($pages as $page) {
    bericht_render_page_to_pdf($pdf, $page, $ori, $fmt, $fpdi_loaded);
}

header('Content-Type: application/pdf');
header('Cache-Control: no-store');
$pdf->Output('bericht_'.$bericht->ref.'.pdf', 'I');
exit;
