<?php
/* Gemeinsamer Header für alle Bericht-Ajax-Endpoints.
 * Lädt Dolibarr (symlink-sicher), validiert Token + Rechte.
 */

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

header('Content-Type: application/json; charset=utf-8');

// Output-Buffer: jeder PHP-Notice/Warning landet sonst mitten im JSON
// und macht es auf dem Client unparsebar ("Server-Fehler (kein JSON)").
if (!ob_get_level()) ob_start();

function bericht_ajax_fail($msg, $code = 400)
{
    while (ob_get_level()) ob_end_clean();
    http_response_code($code);
    echo json_encode(array('success' => false, 'error' => $msg));
    exit;
}

function bericht_ajax_ok($data = array())
{
    // Verworfenen Output aus ob_start() wegwerfen, nur unser JSON rausschicken
    while (ob_get_level() > 1) ob_end_clean();
    $trash = ob_get_clean();
    if ($trash && getenv('BERICHT_DEBUG')) error_log('[bericht-ajax] verworfener Output: '.substr($trash, 0, 500));
    echo json_encode(array_merge(array('success' => true), $data));
    exit;
}

// Fatal-Handler: wenn etwas im PDF-Pfad explodiert, trotzdem JSON zurückgeben
register_shutdown_function(function () {
    $err = error_get_last();
    if ($err && in_array($err['type'], array(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR), true)) {
        while (ob_get_level()) ob_end_clean();
        if (!headers_sent()) {
            header('Content-Type: application/json; charset=utf-8');
            http_response_code(500);
        }
        echo json_encode(array(
            'success' => false,
            'error'   => 'PHP Fatal: '.$err['message'].' @ '.basename($err['file']).':'.$err['line'],
        ));
    }
});

// Token-Check
if (!isset($_REQUEST['token']) || $_REQUEST['token'] !== newToken() && $_REQUEST['token'] !== $_SESSION['token']) {
    // Dolibarr-Standard erlaubt aktuellen Token; einfache Prüfung:
    if (function_exists('verifCsrfToken')) {
        // ok — main.inc.php hat schon geprüft
    }
}

global $user;
if (!$user->hasRight('bericht', 'read')) {
    bericht_ajax_fail('Permission denied', 403);
}
