<?php
/* Copyright (C) 2026 Eduard Wisch <data@data-it-solution.de>
 * GPL v3+
 *
 * Speichert die Geometrie der Unterschriftsbox in llx_bericht_signature_box.
 * UNIQUE-Index (entity, template_name) → ON DUPLICATE KEY UPDATE.
 */

require_once __DIR__.'/_inc.php';

if (!$user->admin && !$user->hasRight('bericht', 'admin')) {
    http_response_code(403);
    echo json_encode(array('error' => 'Forbidden'));
    exit;
}

// Token-Check (Dolibarr-Standard: Session-Token im POST muss matchen)
$posted_token = GETPOST('token', 'alpha');
if (!$posted_token || !isset($_SESSION['token']) || $posted_token !== $_SESSION['token']) {
    http_response_code(403);
    echo json_encode(array('error' => 'CSRF-Token ungueltig'));
    exit;
}

$template = trim((string) GETPOST('template_name', 'alphanohtml'));
$page     = trim((string) GETPOST('page', 'alphanohtml')) ?: 'last';
$x_mm     = (float) GETPOST('x_mm', 'alpha');
$y_mm     = (float) GETPOST('y_mm', 'alpha');
$w_mm     = (float) GETPOST('w_mm', 'alpha');
$h_mm     = (float) GETPOST('h_mm', 'alpha');
$label    = trim((string) GETPOST('label', 'restricthtml')) ?: 'Unterschrift Kunde';

if ($template === '' || $w_mm <= 0 || $h_mm <= 0) {
    echo json_encode(array('error' => 'Ungueltige Werte'));
    exit;
}
$allowed_pages = array('first', 'last');
if (!in_array($page, $allowed_pages, true) && !ctype_digit((string) $page)) {
    $page = 'last';
}

$sql = "INSERT INTO ".$db->prefix()."bericht_signature_box"
    ." (entity, template_name, page, x_mm, y_mm, w_mm, h_mm, label, fk_user_modif)"
    ." VALUES ("
    .((int) $conf->entity).","
    ."'".$db->escape($template)."',"
    ."'".$db->escape($page)."',"
    .((float) $x_mm).","
    .((float) $y_mm).","
    .((float) $w_mm).","
    .((float) $h_mm).","
    ."'".$db->escape($label)."',"
    .((int) $user->id)
    .") ON DUPLICATE KEY UPDATE "
    ."page='".$db->escape($page)."',"
    ."x_mm=".((float) $x_mm).","
    ."y_mm=".((float) $y_mm).","
    ."w_mm=".((float) $w_mm).","
    ."h_mm=".((float) $h_mm).","
    ."label='".$db->escape($label)."',"
    ."fk_user_modif=".((int) $user->id);

if (!$db->query($sql)) {
    echo json_encode(array('error' => $db->lasterror()));
    exit;
}
echo json_encode(array('ok' => true));
