<?php
/* Copyright (C) 2026		Eduard Wisch				<data@data-it-solution.de>
 *
 * AJAX: PWA Login - Authentifiziert Benutzer und gibt Token zurueck
 */

if (!defined('NOTOKENRENEWAL')) {
	define('NOTOKENRENEWAL', '1');
}
if (!defined('NOREQUIREMENU')) {
	define('NOREQUIREMENU', '1');
}
if (!defined('NOREQUIREHTML')) {
	define('NOREQUIREHTML', '1');
}
if (!defined('NOREQUIREAJAX')) {
	define('NOREQUIREAJAX', '1');
}
// Wichtig: Kein Login erforderlich fuer diese Seite
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');

// Nur POST erlaubt
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
	echo json_encode(['success' => false, 'error' => 'Method not allowed']);
	exit;
}

$login = GETPOST('login', 'alphanohtml');
$password = GETPOST('password', 'none'); // 'none' = kein Filter fuer Passwort

if (empty($login) || empty($password)) {
	echo json_encode(['success' => false, 'error' => 'Login und Passwort erforderlich']);
	exit;
}

// Benutzer authentifizieren
$userobj = new User($db);
$result = $userobj->fetch('', $login);

if ($result <= 0) {
	// Benutzer nicht gefunden - generische Fehlermeldung aus Sicherheitsgruenden
	sleep(1); // Brute-Force-Schutz
	echo json_encode(['success' => false, 'error' => 'Login fehlgeschlagen']);
	exit;
}

// Passwort pruefen
$passOk = false;

// Methode 1: password_verify (moderne Dolibarr-Versionen)
if (function_exists('password_verify') && !empty($userobj->pass_indatabase_crypted)) {
	$passOk = password_verify($password, $userobj->pass_indatabase_crypted);
}

// Methode 2: dol_hash (aeltere Versionen)
if (!$passOk && !empty($userobj->pass_indatabase_crypted)) {
	$passOk = (dol_hash($password) === $userobj->pass_indatabase_crypted);
}

// Methode 3: MD5 (sehr alte Installationen)
if (!$passOk && !empty($userobj->pass_indatabase_crypted)) {
	$passOk = (md5($password) === $userobj->pass_indatabase_crypted);
}

if (!$passOk) {
	sleep(1); // Brute-Force-Schutz
	echo json_encode(['success' => false, 'error' => 'Login fehlgeschlagen']);
	exit;
}

// Benutzer ist aktiv?
if ($userobj->statut != 1) {
	echo json_encode(['success' => false, 'error' => 'Benutzer deaktiviert']);
	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 fuer Scanner']);
	exit;
}

// Session starten und Benutzer einloggen
if (session_status() === PHP_SESSION_NONE) {
	session_start();
}

// Dolibarr Session-Variablen setzen
$_SESSION['dol_login'] = $userobj->login;
$_SESSION['dol_authmode'] = 'dolibarr';
$_SESSION['dol_tz'] = GETPOST('tz', 'alpha');
$_SESSION['dol_entity'] = $conf->entity;

// Token generieren fuer 15 Tage
$tokenData = [
	'user_id' => $userobj->id,
	'login' => $userobj->login,
	'entity' => $conf->entity,
	'created' => time(),
	'expires' => time() + (15 * 24 * 60 * 60), // 15 Tage
	'hash' => bin2hex(random_bytes(16))
];

// Token als Base64-encoded JSON (nicht sicher fuer echte Auth, aber reicht fuer PWA-Cache)
$pwaToken = base64_encode(json_encode($tokenData));

// Dolibarr CSRF-Token
$csrfToken = newToken();

echo json_encode([
	'success' => true,
	'pwa_token' => $pwaToken,
	'csrf_token' => $csrfToken,
	'user' => [
		'id' => $userobj->id,
		'login' => $userobj->login,
		'firstname' => $userobj->firstname,
		'lastname' => $userobj->lastname
	],
	'expires' => $tokenData['expires'],
	'expires_human' => date('Y-m-d H:i:s', $tokenData['expires'])
]);
