<?php
/* POST /api/auth.php
 * Body: { "login": "...", "password": "..." }
 * Response: { "token": "...", "user": { id, login, fullname }, "expires": <unix> }
 */
require_once __DIR__.'/_inc.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') api_fail('POST erforderlich', 405);

$in = api_input();
$login = trim($in['login'] ?? '');
$pass  = (string) ($in['password'] ?? '');
if (empty($login) || empty($pass)) api_fail('login + password erforderlich');

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

$u = new User($db);
if ($u->fetch('', $login) <= 0) api_fail('Login fehlgeschlagen', 401);

// Passwort prüfen — Dolibarr's checkPassword braucht den schon geladenen User
if (!dol_verifyHash($pass, $u->pass_indatabase_crypted ?: $u->pass_indatabase)) {
    // Fallback: alter Hash-Vergleich
    if (md5($pass) !== $u->pass_indatabase) {
        api_fail('Login fehlgeschlagen', 401);
    }
}

if (empty($u->statut)) api_fail('User deaktiviert', 403);

$u->loadRights();
if (!$u->hasRight('bericht', 'read')) api_fail('Keine Bericht-Rechte', 403);

// JWT erstellen
$exp = time() + BERICHT_JWT_TTL;
$payload = array(
    'sub'    => (int) $u->id,
    'login'  => $u->login,
    'name'   => method_exists($u, 'getFullName') ? $u->getFullName($langs ?? null) : $u->login,
    'iat'    => time(),
    'exp'    => $exp,
    'iss'    => 'bericht-api',
    'perms'  => array(
        'read'   => (bool) $u->hasRight('bericht', 'read'),
        'write'  => (bool) $u->hasRight('bericht', 'write'),
        'delete' => (bool) $u->hasRight('bericht', 'delete'),
        'admin'  => (bool) $u->hasRight('bericht', 'admin'),
    ),
);
$token = bericht_jwt_encode($payload);

api_ok(array(
    'token' => $token,
    'expires' => $exp,
    'user' => array(
        'id'    => (int) $u->id,
        'login' => $u->login,
        'name'  => $payload['name'],
        'admin' => (bool) ($u->admin ?? false),
    ),
    'perms' => $payload['perms'],
));
