<?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');

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

function bericht_ajax_ok($data = array())
{
    echo json_encode(array_merge(array('success' => true), $data));
    exit;
}

// 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);
}
