<?php
/* Copyright (C) 2026		Eduard Wisch				<data@data-it-solution.de>
 *
 * AJAX: PWA Token Verify - Prueft gespeicherten Token und startet Session
 */

if (!defined('NOTOKENRENEWAL')) {
	define('NOTOKENRENEWAL', '1');
}
if (!defined('NOREQUIREMENU')) {
	define('NOREQUIREMENU', '1');
}
if (!defined('NOREQUIREHTML')) {
	define('NOREQUIREHTML', '1');
}
if (!defined('NOREQUIREAJAX')) {
	define('NOREQUIREAJAX', '1');
}
if (!defined('NOLOGIN')) {
	define('NOLOGIN', '1');
}

// Load Dolibarr environment
$res = 0;
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 && file_exists("../../../../main.inc.php")) {
	$res = @include "../../../../main.inc.php";
}
if (!$res) {
	die(json_encode(['success' => false, 'error' => 'Failed to load Dolibarr']));
}

require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';

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

// Token aus Header oder POST
$pwaToken = '';
if (!empty($_SERVER['HTTP_X_PWA_TOKEN'])) {
	$pwaToken = $_SERVER['HTTP_X_PWA_TOKEN'];
} else {
	$pwaToken = GETPOST('pwa_token', 'alphanohtml');
}

if (empty($pwaToken)) {
	echo json_encode(['success' => false, 'error' => 'Token fehlt', 'need_login' => true]);
	exit;
}

// Token dekodieren
$tokenJson = base64_decode($pwaToken);
if ($tokenJson === false) {
	echo json_encode(['success' => false, 'error' => 'Ungueltiger Token', 'need_login' => true]);
	exit;
}

$tokenData = json_decode($tokenJson, true);
if (!$tokenData || !isset($tokenData['user_id']) || !isset($tokenData['expires'])) {
	echo json_encode(['success' => false, 'error' => 'Token-Format ungueltig', 'need_login' => true]);
	exit;
}

// Ablauf pruefen
if ($tokenData['expires'] < time()) {
	echo json_encode(['success' => false, 'error' => 'Token abgelaufen', 'need_login' => true]);
	exit;
}

// Benutzer laden
$userobj = new User($db);
$result = $userobj->fetch($tokenData['user_id']);

if ($result <= 0) {
	echo json_encode(['success' => false, 'error' => 'Benutzer nicht gefunden', 'need_login' => true]);
	exit;
}

// Benutzer noch aktiv?
if ($userobj->statut != 1) {
	echo json_encode(['success' => false, 'error' => 'Benutzer deaktiviert', 'need_login' => true]);
	exit;
}

// Login stimmt ueberein?
if ($userobj->login !== $tokenData['login']) {
	echo json_encode(['success' => false, 'error' => 'Token ungueltig', 'need_login' => true]);
	exit;
}

// Rechte pruefen
$userobj->getrights();
$hasAccess = false;

if ($userobj->hasRight('handybarcodescanner', 'use')) {
	$hasAccess = true;
} elseif ($userobj->hasRight('fournisseur', 'commande', 'creer') || $userobj->hasRight('supplier_order', 'creer')) {
	$hasAccess = true;
}

if (!$hasAccess) {
	echo json_encode(['success' => false, 'error' => 'Keine Berechtigung', 'need_login' => true]);
	exit;
}

// Session starten/aktualisieren
if (session_status() === PHP_SESSION_NONE) {
	session_start();
}

$_SESSION['dol_login'] = $userobj->login;
$_SESSION['dol_authmode'] = 'dolibarr';
$_SESSION['dol_entity'] = $tokenData['entity'] ?? $conf->entity;

// Neuen CSRF-Token generieren
$csrfToken = newToken();

// Verbleibende Zeit berechnen
$remainingDays = ceil(($tokenData['expires'] - time()) / (24 * 60 * 60));

echo json_encode([
	'success' => true,
	'csrf_token' => $csrfToken,
	'user' => [
		'id' => $userobj->id,
		'login' => $userobj->login,
		'firstname' => $userobj->firstname,
		'lastname' => $userobj->lastname
	],
	'expires' => $tokenData['expires'],
	'remaining_days' => $remainingDays
]);
